MQL 5
MQL 5
MQL 5
Write information trading systems for solving a wide range of tasks (trading, monitoring,
alerting, etc.)
Content
Content
MQL5 Reference
............................................................................................................................42 Sy ntax Comments......................................................................................................................... 43 Identifiers ......................................................................................................................... 44 Reserved ......................................................................................................................... 45 Words Data Ty pes ............................................................................................................................47 Integer Types ......................................................................................................................... 48 Char, Short, Int and Long Types ................................................................................................................ 49 Character Constants ................................................................................................................ 52 Datetime Type ................................................................................................................ 55 Color Type ................................................................................................................ 56 Bool Type ................................................................................................................ 57 Enumerations................................................................................................................ 58 Real Types ......................................................................................................................... 60 String Type ......................................................................................................................... 65 Structures and Classes ......................................................................................................................... 67 Dynamic Array Object ......................................................................................................................... 72 Typecasting ......................................................................................................................... 74 Void Type......................................................................................................................... 80 and NULL Constant Object Pointers ......................................................................................................................... 81 Reference. Modifier & and Keyword this ......................................................................................................................... 82 ............................................................................................................................84 Operations and Expressions Expressions ......................................................................................................................... 85 Arithmetical Operations ......................................................................................................................... 86 Assignment Operations ......................................................................................................................... 87 Operations of Relation ......................................................................................................................... 88 Boolean Operations ......................................................................................................................... 89 Bitwise Operations ......................................................................................................................... 91 Other Operations ......................................................................................................................... 94 Precedence Rules ......................................................................................................................... 98 Operators ............................................................................................................................100 Compound Operator ......................................................................................................................... 102 Expression Operator ......................................................................................................................... 103 Return Operator ......................................................................................................................... 104 Conditional Operator if-else ......................................................................................................................... 105 Conditional Operator ?: ......................................................................................................................... 106 Switch Operator ......................................................................................................................... 108 Loop Operator while ......................................................................................................................... 110 Loop Operator for ......................................................................................................................... 111 Loop Operator do while ......................................................................................................................... 112 Break Operator ......................................................................................................................... 113 Continue Operator ......................................................................................................................... 114 Object Create Operator new ......................................................................................................................... 115 Object Delete Operator delete ......................................................................................................................... 116 Functions ............................................................................................................................117 Function......................................................................................................................... 119 Call Passing Parameters ......................................................................................................................... 120 Function......................................................................................................................... 123 Overloading Description of External Functions ......................................................................................................................... 126 Exporting Functions ......................................................................................................................... 127 Event Handling Functions ......................................................................................................................... 128 V ariables ............................................................................................................................136 2000-2011, MetaQuotes Software Corp.
40
Content
Local Variables ......................................................................................................................... 139 Formal Parameters ......................................................................................................................... 141 Static Variables ......................................................................................................................... 143 Global Variables ......................................................................................................................... 145 Input Variables ......................................................................................................................... 146 Extern Variables ......................................................................................................................... 149 Initialization of Variables ......................................................................................................................... 150 Visibility ......................................................................................................................... 152 Scope and Lifetime of Variables Creating......................................................................................................................... 154 and Deleting Objects ............................................................................................................................157 Preprocessor Declaration of Constants ......................................................................................................................... 158 Program......................................................................................................................... 159 Properties Including......................................................................................................................... 163 Files Importing Functions ......................................................................................................................... 164 ............................................................................................................................166 Object-Oriented Programming Encapsulation and Extensibility of Types ......................................................................................................................... 168 Inheritance ......................................................................................................................... 171 Polymorphism ......................................................................................................................... 174 Overload ......................................................................................................................... 176 Virtual Functions ......................................................................................................................... 177
Content
Predefined Macrosubstitutions ......................................................................................................................... 261 Mathematical Constants ......................................................................................................................... 263 Numerical Type Constants ......................................................................................................................... 265 Uninitalization Reason Codes ......................................................................................................................... 268 Checking Object Pointer ......................................................................................................................... 270 Other Constants ......................................................................................................................... 271 ............................................................................................................................274 Data Structures Structure of the Date Type ......................................................................................................................... 275 Structure of Input Parameters ......................................................................................................................... 276 History Data Structure ......................................................................................................................... 277 DOM Structure ......................................................................................................................... 278 Trade Request Structure ......................................................................................................................... 279 Structure of Request Check Results ......................................................................................................................... 283 Structure of a Trade Request Result ......................................................................................................................... 284 Structure for Current Prices ......................................................................................................................... 287 ............................................................................................................................288 Codes of Errors and W arnings Trade Server Return Codes ......................................................................................................................... 289 Compiler......................................................................................................................... 291 Warnings Compilation Errors ......................................................................................................................... 294 Runtime ......................................................................................................................... 302 Errors ............................................................................................................................309 Input/Output Constants File Opening Flags ......................................................................................................................... 310 In-File Position ......................................................................................................................... 312 Use of a ......................................................................................................................... 313 Codepage MessageBox ......................................................................................................................... 314
Content
............................................................................................................................365 TesterW ithdraw al ............................................................................................................................366 ZeroMemory
Content 9
10
12
Checkup
................................................................................................. 462
............................................................................................................................463 GetLastError IsStopped ............................................................................................................................464 ............................................................................................................................465 UninitializeReason ............................................................................................................................466 TerminalInfoInteger ............................................................................................................................467 TerminalInfoString ............................................................................................................................468 MQL5InfoInteger ............................................................................................................................469 MQL5InfoString ............................................................................................................................470 Sy mbol ............................................................................................................................471 Period ............................................................................................................................472 Digits ............................................................................................................................473 Point
13
Market Info
................................................................................................. 474
............................................................................................................................475 Sy mbolsTotal ............................................................................................................................476 Sy mbolName ............................................................................................................................477 Sy mbolSelect Sy mbolIsSy............................................................................................................................478 nchronized ............................................................................................................................479 Sy mbolInfoDouble ............................................................................................................................481 Sy mbolInfoInteger ............................................................................................................................483 Sy mbolInfoString ............................................................................................................................484 Sy mbolInfoTick ............................................................................................................................485 Sy mbolInfoSessionQuote ............................................................................................................................486 Sy mbolInfoSessionTrade ............................................................................................................................487 MarketBookAdd ............................................................................................................................488 MarketBookRelease ............................................................................................................................489 MarketBookGet
Content 14
15
16
Content
............................................................................................................................601 PositionGetString ............................................................................................................................602 OrdersTotal ............................................................................................................................603 OrderGetTicket ............................................................................................................................605 OrderSelect ............................................................................................................................606 OrderGetDouble ............................................................................................................................607 OrderGetInteger ............................................................................................................................608 OrderGetString ............................................................................................................................609 History Select ............................................................................................................................611 History SelectBy Position ............................................................................................................................612 History OrderSelect ............................................................................................................................613 History OrdersTotal ............................................................................................................................614 History OrderGetTicket ............................................................................................................................616 History OrderGetDouble ............................................................................................................................617 History OrderGetInteger ............................................................................................................................618 History OrderGetString ............................................................................................................................619 History DealSelect ............................................................................................................................620 History DealsTotal ............................................................................................................................621 History DealGetTicket ............................................................................................................................624 History DealGetDouble ............................................................................................................................625 History DealGetInteger ............................................................................................................................626 History DealGetString
17
18
Content
............................................................................................................................668 FileTell FileW rite ............................................................................................................................669 ............................................................................................................................670 FileW riteArray ............................................................................................................................671 FileW riteDouble ............................................................................................................................672 FileW riteFloat ............................................................................................................................673 FileW riteInteger ............................................................................................................................674 FileW riteLong ............................................................................................................................675 FileW riteString ............................................................................................................................676 FileW riteStruct ............................................................................................................................677 FolderCreate ............................................................................................................................678 FolderDelete ............................................................................................................................679 FolderClean
19
20
10
Content
iFractals ............................................................................................................................747 ............................................................................................................................748 iFrAMA ............................................................................................................................749 iGator iIchimoku ............................................................................................................................751 ............................................................................................................................752 iBW MFI ............................................................................................................................753 iMomentum ............................................................................................................................754 iMFI ............................................................................................................................755 iMA ............................................................................................................................756 iOsMA ............................................................................................................................757 iMACD ............................................................................................................................758 iOBV ............................................................................................................................759 iSAR ............................................................................................................................760 iRSI ............................................................................................................................761 iRV I ............................................................................................................................762 iStdDev iStochastic ............................................................................................................................763 ............................................................................................................................764 iTEMA ............................................................................................................................765 iTriX ............................................................................................................................766 iW PR ............................................................................................................................767 iV IDy A iV olumes ............................................................................................................................768
22
23
11
Content
AssignArray ................................................................................................................ 817 AssignArray ................................................................................................................ 818 Update ................................................................................................................ 820 Shift ................................................................................................................ 821 Delete ................................................................................................................ 822 DeleteRange ................................................................................................................ 823 At ................................................................................................................ 824 CompareArray ................................................................................................................ 826 CompareArray ................................................................................................................ 827 InsertSort ................................................................................................................ 828 Search ................................................................................................................ 829 SearchGreat ................................................................................................................ 830 SearchLess ................................................................................................................ 831 SearchGreatOrEqual ................................................................................................................ 832 SearchLessOrEqual ................................................................................................................ 833 SearchFirst ................................................................................................................ 834 SearchLast ................................................................................................................ 835 Save ................................................................................................................ 836 Load ................................................................................................................ 837 Type ................................................................................................................ 839 CArrayShort ......................................................................................................................... 840 Reserve ................................................................................................................ 842 Resize ................................................................................................................ 843 Shutdown ................................................................................................................ 844 Add ................................................................................................................ 845 AddArray ................................................................................................................ 846 AddArray ................................................................................................................ 847 Insert ................................................................................................................ 849 InsertArray ................................................................................................................ 850 InsertArray ................................................................................................................ 851 AssignArray ................................................................................................................ 853 AssignArray ................................................................................................................ 854 Update ................................................................................................................ 856 Shift ................................................................................................................ 857 Delete ................................................................................................................ 858 DeleteRange ................................................................................................................ 859 At ................................................................................................................ 860 CompareArray ................................................................................................................ 862 CompareArray ................................................................................................................ 863 InsertSort ................................................................................................................ 864 Search ................................................................................................................ 865 SearchGreat ................................................................................................................ 866 SearchLess ................................................................................................................ 867 SearchGreatOrEqual ................................................................................................................ 868 SearchLessOrEqual ................................................................................................................ 869 SearchFirst ................................................................................................................ 870 SearchLast ................................................................................................................ 871 Save ................................................................................................................ 872 Load ................................................................................................................ 874 Type ................................................................................................................ 876 CArrayInt ......................................................................................................................... 877 Reserve ................................................................................................................ 879 Resize ................................................................................................................ 880 Shutdown ................................................................................................................ 881 Add ................................................................................................................ 882 AddArray ................................................................................................................ 883 AddArray ................................................................................................................ 884 Insert ................................................................................................................ 886 2000-2011, MetaQuotes Software Corp.
12
Content
InsertArray ................................................................................................................ 887 InsertArray ................................................................................................................ 888 AssignArray ................................................................................................................ 890 AssignArray ................................................................................................................ 891 Update ................................................................................................................ 893 Shift ................................................................................................................ 894 Delete ................................................................................................................ 895 DeleteRange ................................................................................................................ 896 At ................................................................................................................ 897 CompareArray ................................................................................................................ 899 CompareArray ................................................................................................................ 900 InsertSort ................................................................................................................ 901 Search ................................................................................................................ 902 SearchGreat ................................................................................................................ 903 SearchLess ................................................................................................................ 904 SearchGreatOrEqual ................................................................................................................ 905 SearchLessOrEqual ................................................................................................................ 906 SearchFirst ................................................................................................................ 907 SearchLast ................................................................................................................ 908 Save ................................................................................................................ 909 Load ................................................................................................................ 911 Type ................................................................................................................ 913 CArrayLong ......................................................................................................................... 914 Reserve ................................................................................................................ 916 Resize ................................................................................................................ 917 Shutdown ................................................................................................................ 918 Add ................................................................................................................ 919 AddArray ................................................................................................................ 920 AddArray ................................................................................................................ 921 Insert ................................................................................................................ 923 InsertArray ................................................................................................................ 924 InsertArray ................................................................................................................ 925 AssignArray ................................................................................................................ 927 AssignArray ................................................................................................................ 928 Update ................................................................................................................ 930 Shift ................................................................................................................ 931 Delete ................................................................................................................ 932 DeleteRange ................................................................................................................ 933 At ................................................................................................................ 934 CompareArray ................................................................................................................ 936 CompareArray ................................................................................................................ 937 InsertSort ................................................................................................................ 938 Search ................................................................................................................ 939 SearchGreat ................................................................................................................ 940 SearchLess ................................................................................................................ 941 SearchGreatOrEqual ................................................................................................................ 942 SearchLessOrEqual ................................................................................................................ 943 SearchFirst ................................................................................................................ 944 SearchLast ................................................................................................................ 945 Save ................................................................................................................ 946 Load ................................................................................................................ 948 Type ................................................................................................................ 950 CArrayFloat ......................................................................................................................... 951 Delta ................................................................................................................ 953 Reserve ................................................................................................................ 954 Resize ................................................................................................................ 955 Shutdown ................................................................................................................ 956 Add ................................................................................................................ 957 2000-2011, MetaQuotes Software Corp.
13
Content
AddArray ................................................................................................................ 958 AddArray ................................................................................................................ 959 Insert ................................................................................................................ 961 InsertArray ................................................................................................................ 962 InsertArray ................................................................................................................ 963 AssignArray ................................................................................................................ 965 AssignArray ................................................................................................................ 966 Update ................................................................................................................ 968 Shift ................................................................................................................ 969 Delete ................................................................................................................ 970 DeleteRange ................................................................................................................ 971 At ................................................................................................................ 972 CompareArray ................................................................................................................ 974 CompareArray ................................................................................................................ 975 InsertSort ................................................................................................................ 976 Search ................................................................................................................ 977 SearchGreat ................................................................................................................ 978 SearchLess ................................................................................................................ 979 SearchGreatOrEqual ................................................................................................................ 980 SearchLessOrEqual ................................................................................................................ 981 SearchFirst ................................................................................................................ 982 SearchLast ................................................................................................................ 983 Save ................................................................................................................ 984 Load ................................................................................................................ 986 Type ................................................................................................................ 988 CArrayDouble ......................................................................................................................... 989 Delta ................................................................................................................ 991 Reserve ................................................................................................................ 992 Resize ................................................................................................................ 993 Shutdown ................................................................................................................ 994 Add ................................................................................................................ 995 AddArray ................................................................................................................ 996 AddArray ................................................................................................................ 997 Insert ................................................................................................................ 999 InsertArray ................................................................................................................ 1000 InsertArray ................................................................................................................ 1001 AssignArray ................................................................................................................ 1003 AssignArray ................................................................................................................ 1004 Update ................................................................................................................ 1006 Shift ................................................................................................................ 1007 Delete ................................................................................................................ 1008 DeleteRange ................................................................................................................ 1009 At ................................................................................................................ 1010 CompareArray ................................................................................................................ 1012 CompareArray ................................................................................................................ 1013 InsertSort ................................................................................................................ 1014 Search ................................................................................................................ 1015 SearchGreat ................................................................................................................ 1016 SearchLess................................................................................................................ 1017 SearchGreatOrEqual ................................................................................................................ 1018 SearchLessOrEqual ................................................................................................................ 1019 SearchFirst ................................................................................................................ 1020 SearchLast................................................................................................................ 1021 Save ................................................................................................................ 1022 Load ................................................................................................................ 1024 Type ................................................................................................................ 1026 CArrayString ......................................................................................................................... 1027 Reserve ................................................................................................................ 1029 2000-2011, MetaQuotes Software Corp.
14
Content
Resize ................................................................................................................ 1030 Shutdown ................................................................................................................ 1031 Add ................................................................................................................ 1032 AddArray ................................................................................................................ 1033 AddArray ................................................................................................................ 1034 Insert ................................................................................................................ 1036 InsertArray ................................................................................................................ 1037 InsertArray ................................................................................................................ 1038 AssignArray ................................................................................................................ 1040 AssignArray ................................................................................................................ 1041 Update ................................................................................................................ 1043 Shift ................................................................................................................ 1044 Delete ................................................................................................................ 1045 DeleteRange ................................................................................................................ 1046 At ................................................................................................................ 1047 CompareArray ................................................................................................................ 1049 CompareArray ................................................................................................................ 1050 InsertSort ................................................................................................................ 1051 Search ................................................................................................................ 1052 SearchGreat ................................................................................................................ 1053 SearchLess................................................................................................................ 1054 SearchGreatOrEqual ................................................................................................................ 1055 SearchLessOrEqual ................................................................................................................ 1056 SearchFirst ................................................................................................................ 1057 SearchLast................................................................................................................ 1058 Save ................................................................................................................ 1059 Load ................................................................................................................ 1061 Type ................................................................................................................ 1063 CArrayObj ......................................................................................................................... 1064 FreeMode ................................................................................................................ 1069 FreeMode ................................................................................................................ 1070 Reserve ................................................................................................................ 1072 Resize ................................................................................................................ 1073 Clear ................................................................................................................ 1075 Shutdown ................................................................................................................ 1076 CreateElement ................................................................................................................ 1077 Add ................................................................................................................ 1079 AddArray ................................................................................................................ 1080 Insert ................................................................................................................ 1083 InsertArray ................................................................................................................ 1085 AssignArray ................................................................................................................ 1087 Update ................................................................................................................ 1089 Shift ................................................................................................................ 1090 Detach ................................................................................................................ 1091 Delete ................................................................................................................ 1092 DeleteRange ................................................................................................................ 1093 At ................................................................................................................ 1094 CompareArray ................................................................................................................ 1095 InsertSort ................................................................................................................ 1096 Search ................................................................................................................ 1097 SearchGreat ................................................................................................................ 1098 SearchLess................................................................................................................ 1099 SearchGreatOrEqual ................................................................................................................ 1100 SearchLessOrEqual ................................................................................................................ 1101 SearchFirst ................................................................................................................ 1102 SearchLast................................................................................................................ 1103 Save ................................................................................................................ 1104 Load ................................................................................................................ 1105 2000-2011, MetaQuotes Software Corp.
15
Content
Type ................................................................................................................ 1107 CList ......................................................................................................................... 1108 FreeMode ................................................................................................................ 1110 FreeMode ................................................................................................................ 1111 Total ................................................................................................................ 1113 IsSorted ................................................................................................................ 1114 SortMode ................................................................................................................ 1115 CreateElement ................................................................................................................ 1116 Add ................................................................................................................ 1117 Insert ................................................................................................................ 1118 DetachCurrent ................................................................................................................ 1120 DeleteCurrent ................................................................................................................ 1121 Delete ................................................................................................................ 1122 Clear ................................................................................................................ 1123 IndexOf ................................................................................................................ 1124 GetNodeAtIndex ................................................................................................................ 1125 GetFirstNode ................................................................................................................ 1126 GetPrevNode ................................................................................................................ 1127 GetCurrentNode ................................................................................................................ 1128 GetNextNode ................................................................................................................ 1129 GetLastNode ................................................................................................................ 1130 Sort ................................................................................................................ 1131 MoveToIndex ................................................................................................................ 1132 Exchange ................................................................................................................ 1133 CompareList ................................................................................................................ 1134 Search ................................................................................................................ 1135 Save ................................................................................................................ 1136 Load ................................................................................................................ 1138 Type ................................................................................................................ 1140 CTreeNode ......................................................................................................................... 1141 Owner ................................................................................................................ 1146 Left ................................................................................................................ 1147 Right ................................................................................................................ 1148 Balance ................................................................................................................ 1149 BalanceL ................................................................................................................ 1150 BalanceR ................................................................................................................ 1151 CreateSample ................................................................................................................ 1152 RefreshBalance ................................................................................................................ 1153 GetNext ................................................................................................................ 1154 SaveNode ................................................................................................................ 1155 LoadNode ................................................................................................................ 1156 Type ................................................................................................................ 1157 CTree ......................................................................................................................... 1158 Root ................................................................................................................ 1163 CreateElement ................................................................................................................ 1164 Insert ................................................................................................................ 1165 Detach ................................................................................................................ 1166 Delete ................................................................................................................ 1167 Clear ................................................................................................................ 1168 Find ................................................................................................................ 1169 Save ................................................................................................................ 1170 Load ................................................................................................................ 1171 Type ................................................................................................................ 1172 ............................................................................................................................1173 Classes for Graphic Objects CChartObject ......................................................................................................................... 1174 ChartId ................................................................................................................ 1177 Window ................................................................................................................ 1178 Name ................................................................................................................ 1179 2000-2011, MetaQuotes Software Corp.
16
Content
NumPoints ................................................................................................................ 1180 Attach ................................................................................................................ 1181 SetPoint ................................................................................................................ 1182 Delete ................................................................................................................ 1183 Detach ................................................................................................................ 1184 ShiftObject ................................................................................................................ 1185 ShiftPoint ................................................................................................................ 1186 Time ................................................................................................................ 1187 Price ................................................................................................................ 1189 Color ................................................................................................................ 1191 Style ................................................................................................................ 1192 Width ................................................................................................................ 1193 Background ................................................................................................................ 1194 Selected ................................................................................................................ 1195 Selectable ................................................................................................................ 1196 Description ................................................................................................................ 1197 Timeframes ................................................................................................................ 1198 CreateTime ................................................................................................................ 1199 LevelsCount ................................................................................................................ 1200 LevelColor ................................................................................................................ 1201 LevelStyle ................................................................................................................ 1203 LevelWidth ................................................................................................................ 1205 LevelValue ................................................................................................................ 1207 LevelDescription ................................................................................................................ 1209 GetInteger................................................................................................................ 1211 SetInteger................................................................................................................ 1213 GetDouble ................................................................................................................ 1215 SetDouble ................................................................................................................ 1217 GetString ................................................................................................................ 1219 SetString ................................................................................................................ 1221 Save ................................................................................................................ 1223 Load ................................................................................................................ 1224 Type ................................................................................................................ 1225 Objects Lines ......................................................................................................................... 1226 CChartObjectVLine ................................................................................................................ 1227 Create ........................................................................................................... 1228 Type ........................................................................................................... 1229 CChartObjectHLine ................................................................................................................ 1230 Create ........................................................................................................... 1231 Type ........................................................................................................... 1232 CChartObjectTrend ................................................................................................................ 1233 Create ........................................................................................................... 1234 RayLeft ........................................................................................................... 1235 RayRight ........................................................................................................... 1236 Save ........................................................................................................... 1237 Load ........................................................................................................... 1238 Type ........................................................................................................... 1239 CChartObjectTrendByAngle ................................................................................................................ 1240 Create ........................................................................................................... 1241 Angle ........................................................................................................... 1242 Type ........................................................................................................... 1243 CChartObjectCycles ................................................................................................................ 1244 Create ........................................................................................................... 1245 Type ........................................................................................................... 1246 Objects Channels ......................................................................................................................... 1247 CChartObjectChannel ................................................................................................................ 1248 Create ........................................................................................................... 1249 Type ........................................................................................................... 1250 2000-2011, MetaQuotes Software Corp.
17
Content
CChartObjectRegression ................................................................................................................ 1251 Create ........................................................................................................... 1252 Type ........................................................................................................... 1253 CChartObjectStdDevChannel ................................................................................................................ 1254 Create ........................................................................................................... 1255 Deviations........................................................................................................... 1256 Save ........................................................................................................... 1257 Load ........................................................................................................... 1258 Type ........................................................................................................... 1259 CChartObjectPitchfork ................................................................................................................ 1260 Create ........................................................................................................... 1261 Type ........................................................................................................... 1262 Gann Tools ......................................................................................................................... 1263 CChartObjectGannLine ................................................................................................................ 1264 Create ........................................................................................................... 1265 PipsPerBar........................................................................................................... 1266 Save ........................................................................................................... 1267 Load ........................................................................................................... 1268 Type ........................................................................................................... 1269 CChartObjectGannFan ................................................................................................................ 1270 Create ........................................................................................................... 1271 PipsPerBar........................................................................................................... 1272 Downtrend ........................................................................................................... 1273 Save ........................................................................................................... 1274 Load ........................................................................................................... 1275 Type ........................................................................................................... 1276 CChartObjectGannGrid ................................................................................................................ 1277 Create ........................................................................................................... 1278 PipsPerBar........................................................................................................... 1279 Downtrend ........................................................................................................... 1280 Save ........................................................................................................... 1281 Load ........................................................................................................... 1282 Type ........................................................................................................... 1283 Fibonacci Tools ......................................................................................................................... 1284 CChartObjectFibo ................................................................................................................ 1285 Create ........................................................................................................... 1286 Type ........................................................................................................... 1287 CChartObjectFiboTimes ................................................................................................................ 1288 Create ........................................................................................................... 1289 Type ........................................................................................................... 1290 CChartObjectFiboFan ................................................................................................................ 1291 Create ........................................................................................................... 1292 Type ........................................................................................................... 1293 CChartObjectFiboArc ................................................................................................................ 1294 Create ........................................................................................................... 1295 Scale ........................................................................................................... 1296 Ellipse ........................................................................................................... 1297 Save ........................................................................................................... 1298 Load ........................................................................................................... 1299 Type ........................................................................................................... 1300 CChartObjectFiboChannel ................................................................................................................ 1301 Create ........................................................................................................... 1302 Type ........................................................................................................... 1303 CChartObjectFiboExpansion ................................................................................................................ 1304 Create ........................................................................................................... 1305 Type ........................................................................................................... 1306 Elliott Tools ......................................................................................................................... 1307 CChartObjectElliottWave3 ................................................................................................................ 1308 2000-2011, MetaQuotes Software Corp.
18
Content
Create ........................................................................................................... 1309 Degree ........................................................................................................... 1310 Lines ........................................................................................................... 1311 Save ........................................................................................................... 1312 Load ........................................................................................................... 1313 Type ........................................................................................................... 1314 CChartObjectElliottWave5 ................................................................................................................ 1315 Create ........................................................................................................... 1316 Type ........................................................................................................... 1318 Objects Shapes ......................................................................................................................... 1319 CChartObjectRectangle ................................................................................................................ 1320 Create ........................................................................................................... 1321 Type ........................................................................................................... 1322 CChartObjectTriangle ................................................................................................................ 1323 Create ........................................................................................................... 1324 Type ........................................................................................................... 1325 CChartObjectEllipse ................................................................................................................ 1326 Create ........................................................................................................... 1327 Type ........................................................................................................... 1328 Objects Arrows ......................................................................................................................... 1329 CChartObjectArrow ................................................................................................................ 1330 Create ........................................................................................................... 1331 ArrowCode ........................................................................................................... 1333 Anchor ........................................................................................................... 1335 Save ........................................................................................................... 1337 Load ........................................................................................................... 1338 Type ........................................................................................................... 1339 Arrows with fixed code ................................................................................................................ 1340 Create ........................................................................................................... 1342 ArrowCode ........................................................................................................... 1344 Type ........................................................................................................... 1345 Objects Controls ......................................................................................................................... 1346 CChartObjectText ................................................................................................................ 1347 Create ........................................................................................................... 1348 Angle ........................................................................................................... 1349 Font ........................................................................................................... 1350 FontSize ........................................................................................................... 1351 Anchor ........................................................................................................... 1352 Save ........................................................................................................... 1353 Load ........................................................................................................... 1354 Type ........................................................................................................... 1355 CChartObjectLabel ................................................................................................................ 1356 Create ........................................................................................................... 1357 X_Distance ........................................................................................................... 1358 Y_Distance ........................................................................................................... 1359 X_Size ........................................................................................................... 1360 Y_Size ........................................................................................................... 1361 Corner ........................................................................................................... 1362 Time ........................................................................................................... 1363 Price ........................................................................................................... 1364 Save ........................................................................................................... 1365 Load ........................................................................................................... 1366 Type ........................................................................................................... 1367 CChartObjectEdit ................................................................................................................ 1368 Create ........................................................................................................... 1369 X_Size ........................................................................................................... 1370 Y_Size ........................................................................................................... 1371 BackColor ........................................................................................................... 1372 2000-2011, MetaQuotes Software Corp.
19
Content
Angle ........................................................................................................... 1373 Save ........................................................................................................... 1374 Load ........................................................................................................... 1375 Type ........................................................................................................... 1376 CChartObjectButton ................................................................................................................ 1377 State ........................................................................................................... 1378 Save ........................................................................................................... 1379 Load ........................................................................................................... 1380 Type ........................................................................................................... 1381 CChartObjectSubChart ................................................................................................................ 1382 Create ........................................................................................................... 1384 X_Distance ........................................................................................................... 1385 Y_Distance ........................................................................................................... 1386 Corner ........................................................................................................... 1387 X_Size ........................................................................................................... 1388 Y_Size ........................................................................................................... 1389 Symbol ........................................................................................................... 1390 Period ........................................................................................................... 1391 Scale ........................................................................................................... 1392 DateScale ........................................................................................................... 1393 PriceScale ........................................................................................................... 1394 Time ........................................................................................................... 1395 Price ........................................................................................................... 1396 Save ........................................................................................................... 1397 Load ........................................................................................................... 1398 Type ........................................................................................................... 1399 CChartObjectBitmap ................................................................................................................ 1400 Create ........................................................................................................... 1401 BmpFile ........................................................................................................... 1402 Save ........................................................................................................... 1403 Load ........................................................................................................... 1404 Type ........................................................................................................... 1405 CChartObjectBmpLabel ................................................................................................................ 1406 Create ........................................................................................................... 1408 X_Distance ........................................................................................................... 1409 Y_Distance ........................................................................................................... 1410 Corner ........................................................................................................... 1411 X_Size ........................................................................................................... 1412 Y_Size ........................................................................................................... 1413 BmpFileOn ........................................................................................................... 1414 BmpFileOff........................................................................................................... 1415 State ........................................................................................................... 1416 Time ........................................................................................................... 1417 Price ........................................................................................................... 1418 Save ........................................................................................................... 1419 Load ........................................................................................................... 1420 Type ........................................................................................................... 1421 CChartObjectRectLabel ................................................................................................................ 1422 Create ........................................................................................................... 1423 X_Size ........................................................................................................... 1424 Y_Size ........................................................................................................... 1425 BackColor ........................................................................................................... 1426 Angle ........................................................................................................... 1427 BorderType ........................................................................................................... 1428 Save ........................................................................................................... 1429 Load ........................................................................................................... 1430 Type ........................................................................................................... 1431 ............................................................................................................................1432 Class for w orking w ith chart 2000-2011, MetaQuotes Software Corp.
20
Content
ChartID ......................................................................................................................... 1436 Mode ......................................................................................................................... 1437 Foreground ......................................................................................................................... 1438 Shift ......................................................................................................................... 1439 ShiftSize ......................................................................................................................... 1440 AutoScroll ......................................................................................................................... 1441 Scale ......................................................................................................................... 1442 ScaleFix ......................................................................................................................... 1443 ScaleFix_11 ......................................................................................................................... 1444 FixedMax ......................................................................................................................... 1445 FixedMin ......................................................................................................................... 1446 PointsPerBar ......................................................................................................................... 1447 ScalePPB ......................................................................................................................... 1448 ShowOHLC ......................................................................................................................... 1449 ShowLineBid ......................................................................................................................... 1450 ShowLineAsk ......................................................................................................................... 1451 ShowLastLine ......................................................................................................................... 1452 ShowPeriodSep ......................................................................................................................... 1453 ShowGrid ......................................................................................................................... 1454 ShowVolumes ......................................................................................................................... 1455 ShowObjectDescr ......................................................................................................................... 1456 ColorBackground ......................................................................................................................... 1457 ColorForeground ......................................................................................................................... 1458 ColorGrid ......................................................................................................................... 1459 ColorBarUp ......................................................................................................................... 1460 ColorBarDown ......................................................................................................................... 1461 ColorCandleBull ......................................................................................................................... 1462 ColorCandleBear ......................................................................................................................... 1463 ColorChartLine ......................................................................................................................... 1464 ColorVolumes ......................................................................................................................... 1465 ColorLineBid ......................................................................................................................... 1466 ColorLineAsk ......................................................................................................................... 1467 ColorLineLast ......................................................................................................................... 1468 ColorStopLevels ......................................................................................................................... 1469 VisibleBars ......................................................................................................................... 1470 WindowsTotal ......................................................................................................................... 1471 WindowIsVisible ......................................................................................................................... 1472 WindowHandle ......................................................................................................................... 1473 FirstVisibleBar ......................................................................................................................... 1474 WidthInBars ......................................................................................................................... 1475 WidthInPixels ......................................................................................................................... 1476 HeightInPixels ......................................................................................................................... 1477 PriceMin ......................................................................................................................... 1478 PriceMax ......................................................................................................................... 1479 Attach ......................................................................................................................... 1480 FirstChart ......................................................................................................................... 1481 NextChart ......................................................................................................................... 1482 Open ......................................................................................................................... 1483 Detach......................................................................................................................... 1484 Close ......................................................................................................................... 1485 Navigate ......................................................................................................................... 1486 Symbol ......................................................................................................................... 1487 Period ......................................................................................................................... 1488 Redraw......................................................................................................................... 1489 GetInteger ......................................................................................................................... 1490 SetInteger ......................................................................................................................... 1491 GetDouble ......................................................................................................................... 1492 SetDouble ......................................................................................................................... 1493 2000-2011, MetaQuotes Software Corp.
21
Content
GetString ......................................................................................................................... 1494 SetString ......................................................................................................................... 1495 SetSymbolPeriod ......................................................................................................................... 1496 ApplyTemplate ......................................................................................................................... 1497 ScreenShot ......................................................................................................................... 1498 WindowOnDropped ......................................................................................................................... 1499 PriceOnDropped ......................................................................................................................... 1500 TimeOnDropped ......................................................................................................................... 1501 XOnDropped ......................................................................................................................... 1502 YOnDropped ......................................................................................................................... 1503 Save ......................................................................................................................... 1504 Load ......................................................................................................................... 1505 Type ......................................................................................................................... 1506 ............................................................................................................................1507 Classes for file operations CFile ......................................................................................................................... 1508 Handle ................................................................................................................ 1510 Filename ................................................................................................................ 1511 Flags ................................................................................................................ 1512 SetUnicode ................................................................................................................ 1513 SetCommon ................................................................................................................ 1514 Open ................................................................................................................ 1515 Close ................................................................................................................ 1516 Delete ................................................................................................................ 1517 IsExist ................................................................................................................ 1518 Copy ................................................................................................................ 1519 Move ................................................................................................................ 1520 Size ................................................................................................................ 1521 Tell ................................................................................................................ 1522 Seek ................................................................................................................ 1523 Flush ................................................................................................................ 1524 IsEnding ................................................................................................................ 1525 IsLineEnding ................................................................................................................ 1526 FolderCreate ................................................................................................................ 1527 FolderDelete ................................................................................................................ 1528 FolderClean ................................................................................................................ 1529 FileFindFirst ................................................................................................................ 1530 FileFindNext ................................................................................................................ 1531 FileFindClose ................................................................................................................ 1532 CFileBin ......................................................................................................................... 1533 Open ................................................................................................................ 1535 WriteChar ................................................................................................................ 1536 WriteShort................................................................................................................ 1537 WriteInteger ................................................................................................................ 1538 WriteLong ................................................................................................................ 1539 WriteFloat................................................................................................................ 1540 WriteDouble ................................................................................................................ 1541 WriteString ................................................................................................................ 1542 WriteCharArray ................................................................................................................ 1543 WriteShortArray ................................................................................................................ 1544 WriteIntegerArray ................................................................................................................ 1545 WriteLongArray ................................................................................................................ 1546 WriteFloatArray ................................................................................................................ 1547 WriteDoubleArray ................................................................................................................ 1548 WriteObject ................................................................................................................ 1549 ReadChar ................................................................................................................ 1550 ReadShort ................................................................................................................ 1551 ReadInteger ................................................................................................................ 1552 ReadLong ................................................................................................................ 1553 2000-2011, MetaQuotes Software Corp.
22
Content
ReadFloat ................................................................................................................ 1554 ReadDouble ................................................................................................................ 1555 ReadString................................................................................................................ 1556 ReadCharArray ................................................................................................................ 1557 ReadShortArray ................................................................................................................ 1558 ReadIntegerArray ................................................................................................................ 1559 ReadLongArray ................................................................................................................ 1560 ReadFloatArray ................................................................................................................ 1561 ReadDoubleArray ................................................................................................................ 1562 ReadObject ................................................................................................................ 1563 CFileTxt ......................................................................................................................... 1564 Open ................................................................................................................ 1565 WriteString ................................................................................................................ 1566 ReadString................................................................................................................ 1567 ............................................................................................................................1568 Class for String operations CString......................................................................................................................... 1569 Str ................................................................................................................ 1571 Len ................................................................................................................ 1572 Copy ................................................................................................................ 1573 Fill ................................................................................................................ 1574 Assign ................................................................................................................ 1575 Append ................................................................................................................ 1576 Insert ................................................................................................................ 1577 Compare ................................................................................................................ 1578 CompareNoCase ................................................................................................................ 1579 Left ................................................................................................................ 1580 Right ................................................................................................................ 1581 Mid ................................................................................................................ 1582 Trim ................................................................................................................ 1583 TrimLeft ................................................................................................................ 1584 TrimRight ................................................................................................................ 1585 Clear ................................................................................................................ 1586 ToUpper ................................................................................................................ 1587 ToLower ................................................................................................................ 1588 Reverse ................................................................................................................ 1589 Find ................................................................................................................ 1590 FindRev ................................................................................................................ 1591 Remove ................................................................................................................ 1592 Replace ................................................................................................................ 1593 ............................................................................................................................1594 Classes for w orking w ith Indicators Base classes ......................................................................................................................... 1595 CSpreadBuffer ................................................................................................................ 1596 Size ........................................................................................................... 1597 SetSymbolPeriod ........................................................................................................... 1598 At ........................................................................................................... 1599 Refresh ........................................................................................................... 1600 RefreshCurrent ........................................................................................................... 1601 CTimeBuffer ................................................................................................................ 1602 Size ........................................................................................................... 1603 SetSymbolPeriod ........................................................................................................... 1604 At ........................................................................................................... 1605 Refresh ........................................................................................................... 1606 RefreshCurrent ........................................................................................................... 1607 CTickVolumeBuffer ................................................................................................................ 1608 Size ........................................................................................................... 1609 SetSymbolPeriod ........................................................................................................... 1610 At ........................................................................................................... 1611 Refresh ........................................................................................................... 1612 2000-2011, MetaQuotes Software Corp.
23
Content
RefreshCurrent ........................................................................................................... 1613 CRealVolumeBuffer ................................................................................................................ 1614 Size ........................................................................................................... 1615 SetSymbolPeriod ........................................................................................................... 1616 At ........................................................................................................... 1617 Refresh ........................................................................................................... 1618 RefreshCurrent ........................................................................................................... 1619 CDoubleBuffer ................................................................................................................ 1620 Size ........................................................................................................... 1621 SetSymbolPeriod ........................................................................................................... 1622 At ........................................................................................................... 1623 Refresh ........................................................................................................... 1624 RefreshCurrent ........................................................................................................... 1625 Minimum ........................................................................................................... 1626 Maximum ........................................................................................................... 1627 COpenBuffer ................................................................................................................ 1628 Refresh ........................................................................................................... 1629 RefreshCurrent ........................................................................................................... 1630 CHighBuffer ................................................................................................................ 1631 Refresh ........................................................................................................... 1632 RefreshCurrent ........................................................................................................... 1633 CLowBuffer ................................................................................................................ 1634 Refresh ........................................................................................................... 1635 RefreshCurrent ........................................................................................................... 1636 CCloseBuffer ................................................................................................................ 1637 Refresh ........................................................................................................... 1638 RefreshCurrent ........................................................................................................... 1639 CIndicatorBuffer ................................................................................................................ 1640 Offset ........................................................................................................... 1641 Name ........................................................................................................... 1642 At ........................................................................................................... 1643 Refresh ........................................................................................................... 1644 RefreshCurrent ........................................................................................................... 1645 CSeries ................................................................................................................ 1646 Name ........................................................................................................... 1647 BuffersTotal ........................................................................................................... 1648 Timeframe ........................................................................................................... 1649 Symbol ........................................................................................................... 1650 Period ........................................................................................................... 1651 RefreshCurrent ........................................................................................................... 1652 BufferResize ........................................................................................................... 1653 Refresh ........................................................................................................... 1654 PeriodDescription ........................................................................................................... 1655 CPriceSeries ................................................................................................................ 1656 BufferResize ........................................................................................................... 1657 GetData ........................................................................................................... 1658 Refresh ........................................................................................................... 1659 MinIndex ........................................................................................................... 1660 MinValue ........................................................................................................... 1661 MaxIndex ........................................................................................................... 1662 MaxValue ........................................................................................................... 1663 CIndicator................................................................................................................ 1664 Handle ........................................................................................................... 1667 Status ........................................................................................................... 1668 FullRelease........................................................................................................... 1669 Create ........................................................................................................... 1670 BufferResize ........................................................................................................... 1671 GetData ........................................................................................................... 1672 2000-2011, MetaQuotes Software Corp.
24
Content
Refresh ........................................................................................................... 1675 Minimum ........................................................................................................... 1676 MinValue ........................................................................................................... 1677 Maximum ........................................................................................................... 1678 MaxValue ........................................................................................................... 1679 MethodDescription ........................................................................................................... 1680 PriceDescription ........................................................................................................... 1681 VolumeDescription ........................................................................................................... 1682 CIndicators ................................................................................................................ 1683 Create ........................................................................................................... 1684 Refresh ........................................................................................................... 1685 Timeseries classes ......................................................................................................................... 1686 CiSpread ................................................................................................................ 1687 Create ........................................................................................................... 1688 BufferResize ........................................................................................................... 1689 GetData ........................................................................................................... 1690 Refresh ........................................................................................................... 1692 CiTime ................................................................................................................ 1693 Create ........................................................................................................... 1694 BufferResize ........................................................................................................... 1695 GetData ........................................................................................................... 1696 Refresh ........................................................................................................... 1698 CiTickVolume ................................................................................................................ 1699 Create ........................................................................................................... 1700 BufferResize ........................................................................................................... 1701 GetData ........................................................................................................... 1702 Refresh ........................................................................................................... 1704 CiRealVolume ................................................................................................................ 1705 Create ........................................................................................................... 1706 BufferResize ........................................................................................................... 1707 GetData ........................................................................................................... 1708 Refresh ........................................................................................................... 1710 CiOpen ................................................................................................................ 1711 Create ........................................................................................................... 1712 GetData ........................................................................................................... 1713 CiHigh ................................................................................................................ 1715 Create ........................................................................................................... 1716 GetData ........................................................................................................... 1717 CiLow ................................................................................................................ 1719 Create ........................................................................................................... 1720 GetData ........................................................................................................... 1721 CiClose ................................................................................................................ 1723 Create ........................................................................................................... 1724 GetData ........................................................................................................... 1725 Trend Indicators ......................................................................................................................... 1727 CiADX ................................................................................................................ 1728 MaPeriod ........................................................................................................... 1729 Create ........................................................................................................... 1730 Main ........................................................................................................... 1731 Plus ........................................................................................................... 1732 Minus ........................................................................................................... 1733 Type ........................................................................................................... 1734 CiADXWilder ................................................................................................................ 1735 MaPeriod ........................................................................................................... 1736 Create ........................................................................................................... 1737 Main ........................................................................................................... 1738 Plus ........................................................................................................... 1739 Minus ........................................................................................................... 1740 2000-2011, MetaQuotes Software Corp.
25
Content
Type ........................................................................................................... 1741 CiBands ................................................................................................................ 1742 MaPeriod ........................................................................................................... 1743 MaShift ........................................................................................................... 1744 Deviation ........................................................................................................... 1745 Applied ........................................................................................................... 1746 Create ........................................................................................................... 1747 Base ........................................................................................................... 1748 Upper ........................................................................................................... 1749 Lower ........................................................................................................... 1750 Type ........................................................................................................... 1751 CiEnvelopes ................................................................................................................ 1752 MaPeriod ........................................................................................................... 1753 MaShift ........................................................................................................... 1754 MaMethod ........................................................................................................... 1755 Deviation ........................................................................................................... 1756 Applied ........................................................................................................... 1757 Create ........................................................................................................... 1758 Upper ........................................................................................................... 1759 Lower ........................................................................................................... 1760 Type ........................................................................................................... 1761 CiIchimoku................................................................................................................ 1762 TenkanSenPeriod ........................................................................................................... 1763 KijunSenPeriod ........................................................................................................... 1764 SenkouSpanBPeriod ........................................................................................................... 1765 Create ........................................................................................................... 1766 TenkanSen........................................................................................................... 1767 KijunSen ........................................................................................................... 1768 SenkouSpanA ........................................................................................................... 1769 SenkouSpanB ........................................................................................................... 1770 ChinkouSpan ........................................................................................................... 1771 Type ........................................................................................................... 1772 CiMA ................................................................................................................ 1773 MaPeriod ........................................................................................................... 1774 MaShift ........................................................................................................... 1775 MaMethod ........................................................................................................... 1776 Applied ........................................................................................................... 1777 Create ........................................................................................................... 1778 Main ........................................................................................................... 1779 Type ........................................................................................................... 1780 CiSAR ................................................................................................................ 1781 SarStep ........................................................................................................... 1782 Maximum ........................................................................................................... 1783 Create ........................................................................................................... 1784 Main ........................................................................................................... 1785 Type ........................................................................................................... 1786 CiStdDev ................................................................................................................ 1787 MaPeriod ........................................................................................................... 1788 MaShift ........................................................................................................... 1789 MaMethod ........................................................................................................... 1790 Applied ........................................................................................................... 1791 Create ........................................................................................................... 1792 Main ........................................................................................................... 1793 Type ........................................................................................................... 1794 CiDEMA ................................................................................................................ 1795 MaPeriod ........................................................................................................... 1796 IndShift ........................................................................................................... 1797 Applied ........................................................................................................... 1798 2000-2011, MetaQuotes Software Corp.
26
Content
Create ........................................................................................................... 1799 Main ........................................................................................................... 1800 Type ........................................................................................................... 1801 CiTEMA ................................................................................................................ 1802 MaPeriod ........................................................................................................... 1803 IndShift ........................................................................................................... 1804 Applied ........................................................................................................... 1805 Create ........................................................................................................... 1806 Main ........................................................................................................... 1807 Type ........................................................................................................... 1808 CiFrAMA ................................................................................................................ 1809 MaPeriod ........................................................................................................... 1810 IndShift ........................................................................................................... 1811 Applied ........................................................................................................... 1812 Create ........................................................................................................... 1813 Main ........................................................................................................... 1814 Type ........................................................................................................... 1815 CiAMA ................................................................................................................ 1816 MaPeriod ........................................................................................................... 1817 FastEmaPeriod ........................................................................................................... 1818 SlowEmaPeriod ........................................................................................................... 1819 IndShift ........................................................................................................... 1820 Applied ........................................................................................................... 1821 Create ........................................................................................................... 1822 Main ........................................................................................................... 1823 Type ........................................................................................................... 1824 CiVIDyA ................................................................................................................ 1825 CmoPeriod........................................................................................................... 1826 EmaPeriod ........................................................................................................... 1827 IndShift ........................................................................................................... 1828 Applied ........................................................................................................... 1829 Create ........................................................................................................... 1830 Main ........................................................................................................... 1831 Type ........................................................................................................... 1832 Oscillators ......................................................................................................................... 1833 CiATR ................................................................................................................ 1834 MaPeriod ........................................................................................................... 1835 Create ........................................................................................................... 1836 Main ........................................................................................................... 1837 Type ........................................................................................................... 1838 CiBearsPower ................................................................................................................ 1839 MaPeriod ........................................................................................................... 1840 Create ........................................................................................................... 1841 Main ........................................................................................................... 1842 Type ........................................................................................................... 1843 CiBullsPower ................................................................................................................ 1844 MaPeriod ........................................................................................................... 1845 Create ........................................................................................................... 1846 Main ........................................................................................................... 1847 Type ........................................................................................................... 1848 CiCCI ................................................................................................................ 1849 MaPeriod ........................................................................................................... 1850 Applied ........................................................................................................... 1851 Create ........................................................................................................... 1852 Main ........................................................................................................... 1853 Type ........................................................................................................... 1854 CiChaikin ................................................................................................................ 1855 FastMaPeriod ........................................................................................................... 1856 2000-2011, MetaQuotes Software Corp.
27
Content
SlowMaPeriod ........................................................................................................... 1857 MaMethod ........................................................................................................... 1858 Applied ........................................................................................................... 1859 Create ........................................................................................................... 1860 Main ........................................................................................................... 1861 Type ........................................................................................................... 1862 CiDeMarker ................................................................................................................ 1863 MaPeriod ........................................................................................................... 1864 Create ........................................................................................................... 1865 Main ........................................................................................................... 1866 Type ........................................................................................................... 1867 CiForce ................................................................................................................ 1868 MaPeriod ........................................................................................................... 1869 MaMethod ........................................................................................................... 1870 Applied ........................................................................................................... 1871 Create ........................................................................................................... 1872 Main ........................................................................................................... 1873 Type ........................................................................................................... 1874 CiMACD ................................................................................................................ 1875 FastEmaPeriod ........................................................................................................... 1876 SlowEmaPeriod ........................................................................................................... 1877 SignalPeriod ........................................................................................................... 1878 Applied ........................................................................................................... 1879 Create ........................................................................................................... 1880 Main ........................................................................................................... 1881 Signal ........................................................................................................... 1882 Type ........................................................................................................... 1883 CiMomentum ................................................................................................................ 1884 MaPeriod ........................................................................................................... 1885 Applied ........................................................................................................... 1886 Create ........................................................................................................... 1887 Main ........................................................................................................... 1888 Type ........................................................................................................... 1889 CiOsMA ................................................................................................................ 1890 FastEmaPeriod ........................................................................................................... 1891 SlowEmaPeriod ........................................................................................................... 1892 SignalPeriod ........................................................................................................... 1893 Applied ........................................................................................................... 1894 Create ........................................................................................................... 1895 Main ........................................................................................................... 1896 Type ........................................................................................................... 1897 CiRSI ................................................................................................................ 1898 MaPeriod ........................................................................................................... 1899 Applied ........................................................................................................... 1900 Create ........................................................................................................... 1901 Main ........................................................................................................... 1902 Type ........................................................................................................... 1903 CiRVI ................................................................................................................ 1904 MaPeriod ........................................................................................................... 1905 Create ........................................................................................................... 1906 Main ........................................................................................................... 1907 Signal ........................................................................................................... 1908 Type ........................................................................................................... 1909 CiStochastic ................................................................................................................ 1910 Kperiod ........................................................................................................... 1911 Dperiod ........................................................................................................... 1912 Slowing ........................................................................................................... 1913 MaMethod ........................................................................................................... 1914 2000-2011, MetaQuotes Software Corp.
28
Content
PriceField ........................................................................................................... 1915 Create ........................................................................................................... 1916 Main ........................................................................................................... 1917 Signal ........................................................................................................... 1918 Type ........................................................................................................... 1919 CiTriX ................................................................................................................ 1920 MaPeriod ........................................................................................................... 1921 Applied ........................................................................................................... 1922 Create ........................................................................................................... 1923 Main ........................................................................................................... 1924 Type ........................................................................................................... 1925 CiWPR ................................................................................................................ 1926 CalcPeriod........................................................................................................... 1927 Create ........................................................................................................... 1928 Main ........................................................................................................... 1929 Type ........................................................................................................... 1930 Volume ......................................................................................................................... 1931 Indicators CiAD ................................................................................................................ 1932 Applied ........................................................................................................... 1933 Create ........................................................................................................... 1934 Main ........................................................................................................... 1935 Type ........................................................................................................... 1936 CiMFI ................................................................................................................ 1937 MaPeriod ........................................................................................................... 1938 Applied ........................................................................................................... 1939 Create ........................................................................................................... 1940 Main ........................................................................................................... 1941 Type ........................................................................................................... 1942 CiOBV ................................................................................................................ 1943 Applied ........................................................................................................... 1944 Create ........................................................................................................... 1945 Main ........................................................................................................... 1946 Type ........................................................................................................... 1947 CiVolumes ................................................................................................................ 1948 Applied ........................................................................................................... 1949 Create ........................................................................................................... 1950 Main ........................................................................................................... 1951 Type ........................................................................................................... 1952 Bill Williams Indicators ......................................................................................................................... 1953 CiAC ................................................................................................................ 1954 Create ........................................................................................................... 1955 Main ........................................................................................................... 1956 Type ........................................................................................................... 1957 CiAlligator ................................................................................................................ 1958 JawPeriod ........................................................................................................... 1959 JawShift ........................................................................................................... 1960 TeethPeriod ........................................................................................................... 1961 TeethShift ........................................................................................................... 1962 LipsPeriod ........................................................................................................... 1963 LipsShift ........................................................................................................... 1964 MaMethod ........................................................................................................... 1965 Applied ........................................................................................................... 1966 Create ........................................................................................................... 1967 Jaw ........................................................................................................... 1968 Teeth ........................................................................................................... 1969 Lips ........................................................................................................... 1970 Type ........................................................................................................... 1971 CiAO ................................................................................................................ 1972 2000-2011, MetaQuotes Software Corp.
29
Content
Create ........................................................................................................... 1973 Main ........................................................................................................... 1974 Type ........................................................................................................... 1975 CiFractals ................................................................................................................ 1976 Create ........................................................................................................... 1977 Upper ........................................................................................................... 1978 Lower ........................................................................................................... 1979 Type ........................................................................................................... 1980 CiGator ................................................................................................................ 1981 JawPeriod ........................................................................................................... 1982 JawShift ........................................................................................................... 1983 TeethPeriod ........................................................................................................... 1984 TeethShift ........................................................................................................... 1985 LipsPeriod ........................................................................................................... 1986 LipsShift ........................................................................................................... 1987 MaMethod ........................................................................................................... 1988 Applied ........................................................................................................... 1989 Create ........................................................................................................... 1990 Upper ........................................................................................................... 1991 Lower ........................................................................................................... 1992 Type ........................................................................................................... 1993 CiBWMFI ................................................................................................................ 1994 Applied ........................................................................................................... 1995 Create ........................................................................................................... 1996 Main ........................................................................................................... 1997 Type ........................................................................................................... 1998 Custom......................................................................................................................... 1999 indicators NumBuffers ................................................................................................................ 2000 NumParams ................................................................................................................ 2001 ParamType................................................................................................................ 2002 ParamLong................................................................................................................ 2003 ParamDouble ................................................................................................................ 2004 ParamString ................................................................................................................ 2005 Type ................................................................................................................ 2006 ............................................................................................................................2007 Trade Classes CAccountInfo ......................................................................................................................... 2008 Login ................................................................................................................ 2010 TradeMode................................................................................................................ 2011 TradeModeDescription ................................................................................................................ 2012 Leverage ................................................................................................................ 2013 MarginMode ................................................................................................................ 2014 MarginModeDescription ................................................................................................................ 2015 TradeAllowed ................................................................................................................ 2016 TradeExpert ................................................................................................................ 2017 LimitOrders ................................................................................................................ 2018 Balance ................................................................................................................ 2019 Credit ................................................................................................................ 2020 Profit ................................................................................................................ 2021 Equity ................................................................................................................ 2022 Margin ................................................................................................................ 2023 FreeMargin ................................................................................................................ 2024 MarginLevel ................................................................................................................ 2025 MarginCall ................................................................................................................ 2026 MarginStopOut ................................................................................................................ 2027 Name ................................................................................................................ 2028 Server ................................................................................................................ 2029 Currency ................................................................................................................ 2030 Company ................................................................................................................ 2031 2000-2011, MetaQuotes Software Corp.
30
Content
InfoInteger ................................................................................................................ 2032 InfoDouble ................................................................................................................ 2033 InfoString ................................................................................................................ 2034 OrderProfitCheck ................................................................................................................ 2035 MarginCheck ................................................................................................................ 2036 FreeMarginCheck ................................................................................................................ 2037 MaxLotCheck ................................................................................................................ 2038 CSymbolInfo ......................................................................................................................... 2039 Refresh ................................................................................................................ 2043 RefreshRates ................................................................................................................ 2044 Name ................................................................................................................ 2045 Select ................................................................................................................ 2046 IsSynchronized ................................................................................................................ 2047 Volume ................................................................................................................ 2048 VolumeHigh ................................................................................................................ 2049 VolumeLow................................................................................................................ 2050 VolumeBid ................................................................................................................ 2051 VolumeAsk ................................................................................................................ 2052 Time ................................................................................................................ 2053 Spread ................................................................................................................ 2054 SpreadFloat ................................................................................................................ 2055 TickBookDepth ................................................................................................................ 2056 StopsLevel................................................................................................................ 2057 FreezeLevel ................................................................................................................ 2058 Bid ................................................................................................................ 2059 BidHigh ................................................................................................................ 2060 BidLow ................................................................................................................ 2061 Ask ................................................................................................................ 2062 AskHigh ................................................................................................................ 2063 AskLow ................................................................................................................ 2064 Last ................................................................................................................ 2065 LastHigh ................................................................................................................ 2066 LastLow ................................................................................................................ 2067 TradeCalcMode ................................................................................................................ 2068 TradeCalcModeDescription ................................................................................................................ 2069 TradeMode................................................................................................................ 2070 TradeModeDescription ................................................................................................................ 2071 TradeExecution ................................................................................................................ 2072 TradeExecutionDescription ................................................................................................................ 2073 SwapMode ................................................................................................................ 2074 SwapModeDescription ................................................................................................................ 2075 SwapRollover3days ................................................................................................................ 2076 SwapRollover3daysDescription ................................................................................................................ 2077 MarginInitial ................................................................................................................ 2078 MarginMaintenance ................................................................................................................ 2079 MarginLong ................................................................................................................ 2080 MarginShort ................................................................................................................ 2081 MarginLimit ................................................................................................................ 2082 MarginStop ................................................................................................................ 2083 MarginStopLimit ................................................................................................................ 2084 TradeTimeFlags ................................................................................................................ 2085 TradeFillFlags ................................................................................................................ 2086 Digits ................................................................................................................ 2087 Point ................................................................................................................ 2088 TickValue ................................................................................................................ 2089 TickValueProfit ................................................................................................................ 2090 TickValueLoss ................................................................................................................ 2091 TickSize ................................................................................................................ 2092 2000-2011, MetaQuotes Software Corp.
31
Content
ContractSize ................................................................................................................ 2093 LotsMin ................................................................................................................ 2094 LotsMax ................................................................................................................ 2095 LotsStep ................................................................................................................ 2096 LotsLimit ................................................................................................................ 2097 SwapLong ................................................................................................................ 2098 SwapShort ................................................................................................................ 2099 CurrencyBase ................................................................................................................ 2100 CurrencyProfit ................................................................................................................ 2101 CurrencyMargin ................................................................................................................ 2102 Bank ................................................................................................................ 2103 Description ................................................................................................................ 2104 Path ................................................................................................................ 2105 InfoInteger ................................................................................................................ 2106 InfoDouble ................................................................................................................ 2107 InfoString ................................................................................................................ 2108 NormalizePrice ................................................................................................................ 2109 COrderInfo ......................................................................................................................... 2110 Ticket ................................................................................................................ 2112 TimeSetup ................................................................................................................ 2113 OrderType................................................................................................................ 2114 TypeDescription ................................................................................................................ 2115 State ................................................................................................................ 2116 StateDescription ................................................................................................................ 2117 TimeExpiration ................................................................................................................ 2118 TimeDone ................................................................................................................ 2119 TypeFilling ................................................................................................................ 2120 TypeFillingDescription ................................................................................................................ 2121 TypeTime ................................................................................................................ 2122 TypeTimeDescription ................................................................................................................ 2123 Magic ................................................................................................................ 2124 PositionId ................................................................................................................ 2125 VolumeInitial ................................................................................................................ 2126 VolumeCurrent ................................................................................................................ 2127 PriceOpen ................................................................................................................ 2128 StopLoss ................................................................................................................ 2129 TakeProfit ................................................................................................................ 2130 PriceCurrent ................................................................................................................ 2131 PriceStopLimit ................................................................................................................ 2132 Symbol ................................................................................................................ 2133 Comment ................................................................................................................ 2134 InfoInteger ................................................................................................................ 2135 InfoDouble ................................................................................................................ 2136 InfoString ................................................................................................................ 2137 StoreState................................................................................................................ 2138 CheckState ................................................................................................................ 2139 Select ................................................................................................................ 2140 SelectByIndex ................................................................................................................ 2141 CHistoryOrderInfo ......................................................................................................................... 2142 TimeSetup ................................................................................................................ 2144 OrderType................................................................................................................ 2145 TypeDescription ................................................................................................................ 2146 State ................................................................................................................ 2147 StateDescription ................................................................................................................ 2148 TimeExpiration ................................................................................................................ 2149 TimeDone ................................................................................................................ 2150 TypeFilling ................................................................................................................ 2151 TypeFillingDescription ................................................................................................................ 2152 2000-2011, MetaQuotes Software Corp.
32
Content
TypeTime ................................................................................................................ 2153 TypeTimeDescription ................................................................................................................ 2154 Magic ................................................................................................................ 2155 PositionId ................................................................................................................ 2156 VolumeInitial ................................................................................................................ 2157 VolumeCurrent ................................................................................................................ 2158 PriceOpen ................................................................................................................ 2159 StopLoss ................................................................................................................ 2160 TakeProfit ................................................................................................................ 2161 PriceCurrent ................................................................................................................ 2162 PriceStopLimit ................................................................................................................ 2163 Symbol ................................................................................................................ 2164 Comment ................................................................................................................ 2165 InfoInteger ................................................................................................................ 2166 InfoDouble ................................................................................................................ 2167 InfoString ................................................................................................................ 2168 Ticket ................................................................................................................ 2169 SelectByIndex ................................................................................................................ 2170 CPositionInfo ......................................................................................................................... 2171 Time ................................................................................................................ 2173 PositionType ................................................................................................................ 2174 TypeDescription ................................................................................................................ 2175 Magic ................................................................................................................ 2176 Identifier ................................................................................................................ 2177 Volume ................................................................................................................ 2178 PriceOpen ................................................................................................................ 2179 StopLoss ................................................................................................................ 2180 TakeProfit ................................................................................................................ 2181 PriceCurrent ................................................................................................................ 2182 Commission ................................................................................................................ 2183 Swap ................................................................................................................ 2184 Profit ................................................................................................................ 2185 Symbol ................................................................................................................ 2186 InfoInteger ................................................................................................................ 2187 InfoDouble ................................................................................................................ 2188 InfoString ................................................................................................................ 2189 Select ................................................................................................................ 2190 SelectByIndex ................................................................................................................ 2191 StoreState................................................................................................................ 2192 CheckState ................................................................................................................ 2193 CDealInfo ......................................................................................................................... 2194 Order ................................................................................................................ 2196 Time ................................................................................................................ 2197 DealType ................................................................................................................ 2198 TypeDescription ................................................................................................................ 2199 Entry ................................................................................................................ 2200 EntryDescription ................................................................................................................ 2201 Magic ................................................................................................................ 2202 PositionId ................................................................................................................ 2203 Volume ................................................................................................................ 2204 Price ................................................................................................................ 2205 Commision ................................................................................................................ 2206 Swap ................................................................................................................ 2207 Profit ................................................................................................................ 2208 Symbol ................................................................................................................ 2209 Comment ................................................................................................................ 2210 InfoInteger ................................................................................................................ 2211 InfoDouble ................................................................................................................ 2212 2000-2011, MetaQuotes Software Corp.
33
Content
InfoString ................................................................................................................ 2213 Ticket ................................................................................................................ 2214 SelectByIndex ................................................................................................................ 2215 CTrade ......................................................................................................................... 2216 LogLevel ................................................................................................................ 2220 SetExpertMagicNumber ................................................................................................................ 2221 SetDeviationInPoints ................................................................................................................ 2222 SetTypeFilling ................................................................................................................ 2223 OrderOpen ................................................................................................................ 2224 OrderModify ................................................................................................................ 2226 OrderDelete ................................................................................................................ 2227 PositionOpen ................................................................................................................ 2228 PositionModify ................................................................................................................ 2229 PositionClose ................................................................................................................ 2230 Buy ................................................................................................................ 2231 Sell ................................................................................................................ 2232 BuyLimit ................................................................................................................ 2233 BuyStop ................................................................................................................ 2234 SellLimit ................................................................................................................ 2235 SellStop ................................................................................................................ 2236 Request ................................................................................................................ 2237 RequestAction ................................................................................................................ 2238 RequestActionDescription ................................................................................................................ 2239 RequestMagic ................................................................................................................ 2240 RequestOrder ................................................................................................................ 2241 RequestSymbol ................................................................................................................ 2242 RequestVolume ................................................................................................................ 2243 RequestPrice ................................................................................................................ 2244 RequestStopLimit ................................................................................................................ 2245 RequestSL ................................................................................................................ 2246 RequestTP ................................................................................................................ 2247 RequestDeviation ................................................................................................................ 2248 RequestType ................................................................................................................ 2249 RequestTypeDescription ................................................................................................................ 2250 RequestTypeFilling ................................................................................................................ 2251 RequestTypeFillingDescription ................................................................................................................ 2252 RequestTypeTime ................................................................................................................ 2253 RequestTypeTimeDescription ................................................................................................................ 2254 RequestExpiration ................................................................................................................ 2255 RequestComment ................................................................................................................ 2256 Result ................................................................................................................ 2257 ResultRetcode ................................................................................................................ 2258 ResultRetcodeDescription ................................................................................................................ 2259 ResultDeal ................................................................................................................ 2260 ResultOrder ................................................................................................................ 2261 ResultVolume ................................................................................................................ 2262 ResultPrice ................................................................................................................ 2263 ResultBid ................................................................................................................ 2264 ResultAsk ................................................................................................................ 2265 ResultComment ................................................................................................................ 2266 CheckResult ................................................................................................................ 2267 CheckResultRetcode ................................................................................................................ 2268 CheckResultRetcodeDescription ................................................................................................................ 2269 CheckResultBalance ................................................................................................................ 2270 CheckResultEquity ................................................................................................................ 2271 CheckResultProfit ................................................................................................................ 2272 CheckResultMargin ................................................................................................................ 2273 CheckResultMarginFree ................................................................................................................ 2274 2000-2011, MetaQuotes Software Corp.
34
Content
CheckResultMarginLevel ................................................................................................................ 2275 CheckResultComment ................................................................................................................ 2276 PrintRequest ................................................................................................................ 2277 PrintResult................................................................................................................ 2278 FormatRequest ................................................................................................................ 2279 FormatRequestResult ................................................................................................................ 2280 ............................................................................................................................2281 Trading Strategy Classes Base classes for Expert Advisors ......................................................................................................................... 2283 CExpert ................................................................................................................ 2284 Init ........................................................................................................... 2288 InitSignal ........................................................................................................... 2289 InitTrailing........................................................................................................... 2290 InitMoney ........................................................................................................... 2291 Deinit ........................................................................................................... 2292 MaxOrders........................................................................................................... 2293 OnTick ........................................................................................................... 2294 OnTrade ........................................................................................................... 2295 OnTimer ........................................................................................................... 2296 InitParameters ........................................................................................................... 2297 InitIndicators ........................................................................................................... 2298 InitTrade ........................................................................................................... 2299 DeinitTrade ........................................................................................................... 2300 DeinitSignal ........................................................................................................... 2301 DeinitTrailing ........................................................................................................... 2302 DeinitMoney ........................................................................................................... 2303 DeinitIndicators ........................................................................................................... 2304 Refresh ........................................................................................................... 2305 Processing........................................................................................................... 2306 CheckOpen ........................................................................................................... 2308 CheckOpenLong ........................................................................................................... 2309 CheckOpenShort ........................................................................................................... 2310 OpenLong ........................................................................................................... 2311 OpenShort........................................................................................................... 2312 CheckClose ........................................................................................................... 2313 CheckCloseLong ........................................................................................................... 2315 CheckCloseShort ........................................................................................................... 2316 CloseAll ........................................................................................................... 2317 Close ........................................................................................................... 2318 CloseLong ........................................................................................................... 2319 CloseShort........................................................................................................... 2320 CheckReverse ........................................................................................................... 2321 CheckReverseLong ........................................................................................................... 2322 CheckReverseShort ........................................................................................................... 2323 ReverseLong ........................................................................................................... 2324 ReverseShort ........................................................................................................... 2325 CheckTrailingStop ........................................................................................................... 2326 CheckTrailingStopLong ........................................................................................................... 2327 CheckTrailingStopShort ........................................................................................................... 2328 TrailingStopLong ........................................................................................................... 2329 TrailingStopShort ........................................................................................................... 2330 CheckTrailingOrderLong ........................................................................................................... 2331 CheckTrailingOrderShort ........................................................................................................... 2332 TrailingOrderLong ........................................................................................................... 2333 TrailingOrderShort ........................................................................................................... 2334 CheckDeleteOrderLong ........................................................................................................... 2335 CheckDeleteOrderShort ........................................................................................................... 2336 DeleteOrders ........................................................................................................... 2337 DeleteOrder ........................................................................................................... 2338 2000-2011, MetaQuotes Software Corp.
35
Content
DeleteOrderLong ........................................................................................................... 2339 DeleteOrderShort ........................................................................................................... 2340 LotOpenLong ........................................................................................................... 2341 LotOpenShort ........................................................................................................... 2342 LotReverse ........................................................................................................... 2343 PrepareHistoryDate ........................................................................................................... 2344 HistoryPoint ........................................................................................................... 2345 CheckTradeState ........................................................................................................... 2346 WaitEvent........................................................................................................... 2347 NoWaitEvent ........................................................................................................... 2348 IsWaitingPositionOpened ........................................................................................................... 2349 IsWaitingPositionVolumeChanged ........................................................................................................... 2350 IsWaitingPositionModified ........................................................................................................... 2351 IsWaitingPositionClosed ........................................................................................................... 2352 IsWaitingPositionStopTake ........................................................................................................... 2353 IsWaitingOrderPlaced ........................................................................................................... 2354 IsWaitingOrderModified ........................................................................................................... 2355 IsWaitingOrderDeleted ........................................................................................................... 2356 IsWaitingOrderTriggered ........................................................................................................... 2357 TradeEventPositionStopTake ........................................................................................................... 2358 TradeEventOrderTriggered ........................................................................................................... 2359 TradeEventPositionOpened ........................................................................................................... 2360 TradeEventPositionVolumeChanged ........................................................................................................... 2361 TradeEventPositionModified ........................................................................................................... 2362 TradeEventPositionClosed ........................................................................................................... 2363 TradeEventOrderPlaced ........................................................................................................... 2364 TradeEventOrderModified ........................................................................................................... 2365 TradeEventOrderDeleted ........................................................................................................... 2366 TradeEventNotIdentified ........................................................................................................... 2367 TimeframeAdd ........................................................................................................... 2368 TimeframesFlags ........................................................................................................... 2369 CExpertSignal ................................................................................................................ 2370 Init ........................................................................................................... 2371 InitIndicators ........................................................................................................... 2372 ValidationSettings ........................................................................................................... 2373 CheckOpenLong ........................................................................................................... 2374 CheckCloseLong ........................................................................................................... 2375 CheckOpenShort ........................................................................................................... 2376 CheckCloseShort ........................................................................................................... 2377 CheckReverseLong ........................................................................................................... 2378 CheckReverseShort ........................................................................................................... 2379 CheckTrailingOrderLong ........................................................................................................... 2380 CheckTrailingOrderShort ........................................................................................................... 2381 CExpertTrailing ................................................................................................................ 2382 Init ........................................................................................................... 2383 InitIndicators ........................................................................................................... 2384 ValidationSettings ........................................................................................................... 2385 CheckTrailingStopLong ........................................................................................................... 2386 CheckTrailingStopShort ........................................................................................................... 2387 CExpertMoney ................................................................................................................ 2388 Percent ........................................................................................................... 2389 Init ........................................................................................................... 2390 InitIndicators ........................................................................................................... 2391 ValidationSettings ........................................................................................................... 2392 CheckOpenLong ........................................................................................................... 2393 CheckOpenShort ........................................................................................................... 2394 CheckReverse ........................................................................................................... 2395 CheckClose ........................................................................................................... 2396 2000-2011, MetaQuotes Software Corp.
36
Content
Trading......................................................................................................................... 2397 Signal Classes CSignal3EMA ................................................................................................................ 2399 FastPeriod........................................................................................................... 2400 MediumPeriod ........................................................................................................... 2401 SlowPeriod........................................................................................................... 2402 StopLoss ........................................................................................................... 2403 TakeProfit........................................................................................................... 2404 InitIndicators ........................................................................................................... 2405 ValidationSettings ........................................................................................................... 2406 CheckOpenLong ........................................................................................................... 2407 CheckCloseLong ........................................................................................................... 2408 CheckOpenShort ........................................................................................................... 2409 CheckCloseShort ........................................................................................................... 2410 CSignalADX_MA ................................................................................................................ 2411 PeriodADX ........................................................................................................... 2412 MinimumADX ........................................................................................................... 2413 PeriodMA ........................................................................................................... 2414 TakeProfit........................................................................................................... 2415 StopLoss ........................................................................................................... 2416 InitIndicators ........................................................................................................... 2417 CheckOpenLong ........................................................................................................... 2418 CheckCloseLong ........................................................................................................... 2419 CheckOpenShort ........................................................................................................... 2420 CheckCloseShort ........................................................................................................... 2421 CSignalAlligator ................................................................................................................ 2422 JawPeriod ........................................................................................................... 2423 JawShift ........................................................................................................... 2424 TeethPeriod ........................................................................................................... 2425 TeethShift ........................................................................................................... 2426 LipsPeriod ........................................................................................................... 2427 LipsShift ........................................................................................................... 2428 MaMethod ........................................................................................................... 2429 Applied ........................................................................................................... 2430 CrossMeasure ........................................................................................................... 2431 InitIndicators ........................................................................................................... 2432 ValidationSettings ........................................................................................................... 2433 CheckOpenLong ........................................................................................................... 2434 CheckCloseLong ........................................................................................................... 2435 CheckOpenShort ........................................................................................................... 2436 CheckCloseShort ........................................................................................................... 2437 CSignalCandles ................................................................................................................ 2438 Range ........................................................................................................... 2440 Minimum ........................................................................................................... 2441 ShadowBig ........................................................................................................... 2442 ShadowSmall ........................................................................................................... 2443 Limit ........................................................................................................... 2444 TakeProfit........................................................................................................... 2445 StopLoss ........................................................................................................... 2446 Expiration........................................................................................................... 2447 InitIndicators ........................................................................................................... 2448 ValidationSettings ........................................................................................................... 2449 CheckOpenLong ........................................................................................................... 2450 CheckCloseLong ........................................................................................................... 2451 CheckOpenShort ........................................................................................................... 2452 CheckCloseShort ........................................................................................................... 2453 Candle ........................................................................................................... 2454 CSignalCandlesRSI ................................................................................................................ 2455 PeriodRSI ........................................................................................................... 2456 2000-2011, MetaQuotes Software Corp.
37
Content
AppliedRSI ........................................................................................................... 2457 ExtrMap ........................................................................................................... 2458 InitIndicators ........................................................................................................... 2459 ValidationSettings ........................................................................................................... 2460 CheckOpenLong ........................................................................................................... 2461 CheckCloseLong ........................................................................................................... 2462 CheckOpenShort ........................................................................................................... 2463 CheckCloseShort ........................................................................................................... 2464 CSignalCandlesStoch ................................................................................................................ 2465 PeriodK ........................................................................................................... 2466 PeriodD ........................................................................................................... 2467 PeriodSlow........................................................................................................... 2468 Applied ........................................................................................................... 2469 ExtrMap ........................................................................................................... 2470 InitIndicators ........................................................................................................... 2471 ValidationSettings ........................................................................................................... 2472 CheckOpenLong ........................................................................................................... 2473 CheckCloseLong ........................................................................................................... 2474 CheckOpenShort ........................................................................................................... 2475 CheckCloseShort ........................................................................................................... 2476 CSignalCrossEMA ................................................................................................................ 2477 FastPeriod........................................................................................................... 2478 SlowPeriod........................................................................................................... 2479 InitIndicators ........................................................................................................... 2480 ValidationSettings ........................................................................................................... 2481 CheckOpenLong ........................................................................................................... 2482 CheckCloseLong ........................................................................................................... 2483 CheckOpenShort ........................................................................................................... 2484 CheckCloseShort ........................................................................................................... 2485 CSignalCrossMA ................................................................................................................ 2486 FastPeriod........................................................................................................... 2487 FastShift ........................................................................................................... 2488 FastMethod ........................................................................................................... 2489 FastApplied ........................................................................................................... 2490 SlowPeriod........................................................................................................... 2491 SlowShift ........................................................................................................... 2492 SlowMethod ........................................................................................................... 2493 SlowApplied ........................................................................................................... 2494 StopLoss ........................................................................................................... 2495 TakeProfit........................................................................................................... 2496 InitIndicators ........................................................................................................... 2497 ValidationSettings ........................................................................................................... 2498 CheckOpenLong ........................................................................................................... 2499 CheckCloseLong ........................................................................................................... 2500 CheckOpenShort ........................................................................................................... 2501 CheckCloseShort ........................................................................................................... 2502 CSignalMA ................................................................................................................ 2503 Period ........................................................................................................... 2504 Shift ........................................................................................................... 2505 Method ........................................................................................................... 2506 Applied ........................................................................................................... 2507 InitIndicators ........................................................................................................... 2508 ValidationSettings ........................................................................................................... 2509 CheckOpenLong ........................................................................................................... 2510 CheckCloseLong ........................................................................................................... 2511 CheckOpenShort ........................................................................................................... 2512 CheckCloseShort ........................................................................................................... 2513 CSignalMACD ................................................................................................................ 2514 2000-2011, MetaQuotes Software Corp.
38
Content
PeriodFast........................................................................................................... 2515 PeriodSlow........................................................................................................... 2516 PeriodSignal ........................................................................................................... 2517 TakeProfit........................................................................................................... 2518 StopLoss ........................................................................................................... 2519 InitIndicators ........................................................................................................... 2520 ValidationSettings ........................................................................................................... 2521 CheckOpenLong ........................................................................................................... 2522 CheckCloseLong ........................................................................................................... 2523 CheckOpenShort ........................................................................................................... 2524 CheckCloseShort ........................................................................................................... 2525 CSignalMovingAverage ................................................................................................................ 2526 Period ........................................................................................................... 2527 Shift ........................................................................................................... 2528 InitIndicators ........................................................................................................... 2529 ValidationSettings ........................................................................................................... 2530 CheckOpenLong ........................................................................................................... 2531 CheckCloseLong ........................................................................................................... 2532 CheckOpenShort ........................................................................................................... 2533 CheckCloseShort ........................................................................................................... 2534 CSignalITF ................................................................................................................ 2535 GoodMinuteOfHour ........................................................................................................... 2536 BadMinutesOfHour ........................................................................................................... 2537 GoodHourOfDay ........................................................................................................... 2538 BadHoursOfDay ........................................................................................................... 2539 GoodDayOfWeek ........................................................................................................... 2540 BadDaysOfWeek ........................................................................................................... 2541 CheckOpenLong ........................................................................................................... 2542 CheckOpenShort ........................................................................................................... 2543 CSignal2EMA_ITF ................................................................................................................ 2544 PeriodFastEMA ........................................................................................................... 2546 PeriodSlowEMA ........................................................................................................... 2547 PeriodATR ........................................................................................................... 2548 Limit ........................................................................................................... 2549 StopLoss ........................................................................................................... 2550 TakeProfit........................................................................................................... 2551 Expiration........................................................................................................... 2552 GoodMinuteOfHour ........................................................................................................... 2553 BadMinutesOfHour ........................................................................................................... 2554 GoodHourOfDay ........................................................................................................... 2555 BadHoursOfDay ........................................................................................................... 2556 GoodDayOfWeek ........................................................................................................... 2557 BadDaysOfWeek ........................................................................................................... 2558 InitIndicators ........................................................................................................... 2559 ValidationSettings ........................................................................................................... 2560 CheckOpenLong ........................................................................................................... 2561 CheckCloseLong ........................................................................................................... 2562 CheckOpenShort ........................................................................................................... 2563 CheckCloseShort ........................................................................................................... 2564 CheckTrailingOrderLong ........................................................................................................... 2565 CheckTrailingOrderShort ........................................................................................................... 2566 Trailing......................................................................................................................... 2567 Stop Classes CTrailingFixedPips ................................................................................................................ 2568 StopLevel ........................................................................................................... 2569 ProfitLevel ........................................................................................................... 2570 ValidationSettings ........................................................................................................... 2571 CheckTrailingStopLong ........................................................................................................... 2572 CheckTrailingStopShort ........................................................................................................... 2573 2000-2011, MetaQuotes Software Corp.
39
Content
CTrailingMA ................................................................................................................ 2574 Period ........................................................................................................... 2575 Shift ........................................................................................................... 2576 Method ........................................................................................................... 2577 Applied ........................................................................................................... 2578 InitIndicators ........................................................................................................... 2579 ValidationSettings ........................................................................................................... 2580 CheckTrailingStopLong ........................................................................................................... 2581 CheckTrailingStopShort ........................................................................................................... 2582 CTrailingNone ................................................................................................................ 2583 CheckTrailingStopLong ........................................................................................................... 2584 CheckTrailingStopShort ........................................................................................................... 2585 CTrailingPSAR ................................................................................................................ 2586 Step ........................................................................................................... 2587 Maximum ........................................................................................................... 2588 InitIndicators ........................................................................................................... 2589 CheckTrailingStopLong ........................................................................................................... 2590 CheckTrailingStopShort ........................................................................................................... 2591 Money Management Classes ......................................................................................................................... 2592 CMoneyFixedLot ................................................................................................................ 2593 Lots ........................................................................................................... 2594 ValidationSettings ........................................................................................................... 2595 CheckOpenLong ........................................................................................................... 2596 CheckOpenShort ........................................................................................................... 2597 CMoneyFixedMargin ................................................................................................................ 2598 CheckOpenLong ........................................................................................................... 2599 CheckOpenShort ........................................................................................................... 2600 CMoneyFixedRisk ................................................................................................................ 2601 CheckOpenLong ........................................................................................................... 2602 CheckOpenShort ........................................................................................................... 2603 CMoneyNone ................................................................................................................ 2604 ValidationSettings ........................................................................................................... 2605 CheckOpenLong ........................................................................................................... 2606 CheckOpenShort ........................................................................................................... 2607 CMoneySizeOptimized ................................................................................................................ 2608 DecreaseFactor ........................................................................................................... 2609 ValidationSettings ........................................................................................................... 2610 CheckOpenLong ........................................................................................................... 2611 CheckOpenShort ........................................................................................................... 2612
24
40
MQL5 Reference
MetaQuotes Language 5 (MQL5) is a built-in language for programming trading strategies. This language is developed by MetaQuotes Software Corp. based on their long experience in the creation of online trading platforms. Using this language, you can create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies. Besides, using MQL5 you can create your own technical indicators (custom indicators), scripts and libraries. MQL5 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade positions and controlling them. The MetaEditor 5 (text editor) that highlights different constructions of MQL5 language is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily. MetaQuotes Language Dictionary is used as a Help System for MQL5 language. The brief guide contains functions, operations, reserved words, and other language constructions divided into categories, and allows finding the description of every used element of the language. Programs written in MetaQuotes Language 5 have different features and purposes: Expert Advisor is a mechanical trading system linked up to a certain chart. An Expert Advisor starts to run when an event happens that can be handled by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event, chart event and custom events. An Expert Advisor can both inform you about a possibility to trade and automatically trade on an account sending orders directly to a trade server. Expert Advisors are stored in terminal_directory\MQL5\Experts. Custom Indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only. Custom indicators are stored in terminal_directory\MQL5\Indicators Script is a program intended for a single execution of some actions. Unlike Expert Advisors, scripts do not process any actions, except for the start event (this requires the OnStart handler function in a script). Scripts are stored in terminal_directory\MQL5\Scripts Library is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves. Libraries are stored in terminal_directory\MQL5\Libraries Include File is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of Expert Advisors, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions. Include files can be stored in the same directory as a source file - in this case the #include directive with double quotes is used. Another place to store include files is terminal_directory\MQL5\Include, in this case the #include directive is used with angle brackets.
41
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
42
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; constructors of classes and structures can't have parameters; no multiple inheritance. See also Enumerations, Structures and Classes, Inheritance
43
Language Basics
Comments
Multi-line comments start with the /* pair of symbols and end with the */ one. Such kind of comments cannot be nested. Single-line comments begin with the // pair of symbols and end with the newline character, they can be nested in other multi-line comments. Comments are allowed everywhere where the spaces are allowed, they can have any number of spaces in them. Examples:
//--- Single-line comment /* Multiline comment */ // Nested single-line comment
44
Language Basics
Identifiers
Identifiers are used as names of variables and functions. The length of the identifier can not exceed 31 characters. Characters allowed ti be written in an identifier: figures 0-9, the Latin uppercase and lowercase letters a-z and A-Z, recognized as different characters, the underscore character (_).The first character can not be a digit. The identifier must not coincide with reserved word. Examples:
NAME1 namel Total_5 Paper
45
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 char class color datetime double enum float int long short string struct uchar uint ulong ushort void
Operators break case continue default delete do else for if new return sizeof switch while
46
Language Basics
47
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 complicity of internal presentation of data with floating point, they are processed slower than the integer ones. String data are processed at the longest because of dynamic computer memory allocation/reallocation. 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 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
48
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 types conversion. The table below lists the characteristics of each type. Besides, the last column features a type in C++ corresponding to each type. Type char uchar Size in Bytes 1 1 Minimum Value -128 0 Maximum Value 127 255 C++ Analog char unsigned BYTE bool short, wchar_t unsigned WORD int unsigned DWORD int, short, char,
1 2 2
int uint
4 4
color long
4 8
16 777 215 9 223 372 036 854 775 807 18 446 744 073 709 551 615 32 535 244 799 (3000.12.31 23:59:59)
ulong
unsigned __int64
datetime
0 (1970.01.01 0:00:00)
__time64_t
Integer type values can also be presented as numeric constants, color literals, date-time literals, character constants and enumerations. See also Data Conversion, Constants of Numeric Types
49
Language Basics
uchar
The uchar integer type also occupies 1 byte of memory, as well as the char type, but unlike it uchar is intended only for positive values. The minimum value is zero, the maximum value is 255. The first letter u in the name of the uchar type is the abbreviation for unsigned.
short
The size of the short type is 2 bytes (16 bits) and, accordingly, it allows expressing the range of values equal to 2 to the power 16: 2^16 = 65 536.Since the short type is a sign one, and contains both positive and negative values, the range of values is between -32 768 and 32 767.
ushort
The unsigned short type is the type ushort, which also has a size of 2 bytes. The minimum value is 0, the maximum value is 65 535.
int
The size of the int type is 4 bytes (32 bits). The minimal value is -2 147 483 648, the maximal one is 2 147 483 647.
uint
The unsigned integer type is uint. It takes 4 bytes of memory and allows expressing integers from 0 to 4 294 967 295.
long
The size of the long type is 8 bytes (64 bits). The minimum value is -9 223 372 036 854 775 808, the maximum value is 9 223 372 036 854 775 807.
ulong
The ulong type also occupies 8 bytes and can store values from 0 to 18 446 744 073 709 551 615. Examples:
char int ch=12; in=2445777;
short sh=-5000;
50
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;
Result:
ch= -128 ch= -127 ch= -126 ch= -125 ch= -124 ch= -123 ch= -122 ch= -121 ch= -120 ch= -119 ch= -118 ch= -117 ch= -116 ch= -115 ch= -114 ch= -113 ch= -112 ch= -111 u_ch= 128 u_ch= 129 u_ch= 130 u_ch= 131 u_ch= 132 u_ch= 133 u_ch= 134 u_ch= 135 u_ch= 136 u_ch= 137 u_ch= 138 u_ch= 139 u_ch= 140 u_ch= 141 u_ch= 142 u_ch= 143 u_ch= 144 u_ch= 145
51
Language Basics
...
Examples:
//--- Negative values can not be stored in unsigned types uchar uint u_ch=-120; u_in=-401280; ushort u_sh=-5000;
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
52
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, //--- 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); } symbol_9 = %d",symbol_0,symbol_9); symbol_9 = 0x%x",symbol_0,symbol_9); printf("In a hexadecimal form: symbol_0 = 0x%x,
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 LF HT CR \ ' " hhhh Record in MQL5 Numeric value
new line (line feed) horizontal tab carriage return backslash single quote double quote hexadecimal code
decimal code
'\d'
53
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=''; int d='\xAE'; 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); } // coed 0xA9 // code of the symbol
As it was mentioned above, th value of a character constant (or variable) is an index in the table of characters. Index being an integer, it can be written in different ways.
void OnStart() {
54
Language Basics
//--int a=0xAE; int b=0x24; int c=0xA9; int d=0x263A; //--- 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 code of corresponds to the '\xAE' literal // the code of $ corresponds to the '\x24' literal // the code of corresponds to the '\xA9' literal // the code of O corresponds to the '\x263A' literal
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()
55
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. Either date (year , month, day) or time (hours, minutes, seconds), or all together can be omitted. Values range from 1 January, 1970 to 31 December, 3000. Examples:
D'2004.01.01 00:00' D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' D'01.01.2004' D'12:30:27' D'' //equivalent to D'1980.07.19 12:00:00' //equivalent to D'01.01.2004 00:00:00' //equivalent to D'[compilation date] 12:30:27' //equivalent to D'[compilation date] 00:00:00' // New Year
See also Structure of the Date Type, Date and Time, TimeToString, StringToTime
56
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' //color names Red Yellow Black 0xFFFFFF 16777215 0x008000 32768 // Red // Yellow // Black // White // White // Green // Green // Gray C'0x00,0x00,0xFF' // Blue
57
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
58
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 { January, February, March, April, May, June, July, August, September, October, November, December }; // enumeration of named constants
After the enumeration is declared, a new integer-valued 4-byte data type appears. Declaration of the new data type allows the compiler to strictly control types of passed parameters, because enumeration introduces new named constants. In the above example, the January named constant has the value of 0, February - 1, December - 11. Rule: If a certain value is not assigned to a named constant - a member of the enumeration, its new value will be formed automatically. If it is the first member of the enumeration, the 0 value will be assigned to it. For all subsequent members, values will be calculated based on the value of the previous members by adding one. Example:
enum intervals { month=1, two_months, quarter, halfyear=6, year=12, }; // Interval of one month // Two months // Three months - quarter // Half a year // Year - 12 months // Enumeration of named constants
Notes
59
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
60
Language Basics
float
float
double
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 float c =0.0001; 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
61
Language Basics precisely represented in the decimal system can be written only as an infinite fraction in the binary system. For example, numbers 0.3 and 0.7 are represented in the computer as infinite fractions, while the number of 0.25 is stored exactly, because it represents the power of two. In this regard, it is strongly recommended not to compare two real numbers for equality, because such a comparison is not correct. Example:
void OnStart() { //--double three=3.0; double x,y,z; x=1/three; y=4/three; z=5/three; if(x+y==z) Print("1/3 + 4/3 == 5/3"); else Print("1/3 + 4/3 != 5/3"); // Result: 1/3 + 4/3 != 5/3 }
If you still need to compare the equality of two real numbers, then you can do this in two different ways. The first way is to compare the difference between two numbers with some small quantity that specifies the accuracy of comparison. Example:
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)); f_val= 0.6999999880790710 // Result: Different: d_val= 0.7000000000000000
Noted that the value of epsilon in the above example can not be less than the predefined constants DBL_EPSILON.The value of this constant is 2.2204460492503131e-016. The constant corresponding to
62
Language Basics the float type is FLT_EPSILON = 1.192092896e-07. The meaning of these values is the following: it is the lowest value that satisfies the condition 1.0 + DBL_EPSILON! = 1.0 (for numbers of float type 1.0 + FLT_EPSILON! = 1.0). The second way offers comparing the normalized difference of two real numbers with zero. It's meaningless to compare the difference of normalized numbers with a zero, because any mathematical operation with normalized numbers gives a non-normalized result. Example:
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)); f_val= 0.3000000119209290 // Result: Different: d_val= 0.3000000000000000
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; };
63
Language Basics
//--- Start str1 s1; str2 s2; //--s1.d=MathArcsin(2.0); s2=s1; printf("1. //--s2.l=0xFFFF000000000000; s1=s2; printf("2. //--s2.l=0x7FF7000000000000; s1=s2; printf("3. //--s2.l=0x7FF8000000000000; s1=s2; printf("4. //--s2.l=0x7FFF000000000000; s1=s2; printf("5. //--s2.l=0x7FF0000000000000; s1=s2; printf("6. //--s2.l=0xFFF0000000000000; s1=s2; printf("7. //--s2.l=0x8000000000000000; s1=s2; printf("8. //--s2.l=0x3FE0000000000000; s1=s2; printf("9. //--s2.l=0x3FF0000000000000; s1=s2; printf("10. //--s2.l=0x7FEFFFFFFFFFFFFF; s1=s2; printf("11. //--%.16e %I64X",s1.d,s2.l); // Greatest normalized number (MAX_DBL) %f %I64X",s1.d,s2.l); // 1.0 %f %I64X",s1.d,s2.l); // 0.5 %f %I64X",s1.d,s2.l); // Negative zero -0.0 %f %I64X",s1.d,s2.l); // Negative infinity -1.#INF %f %I64X",s1.d,s2.l); // Positive infinity 1.#INF and smallest nnonnumber SNaN %f %I64X",s1.d,s2.l); // greatest nonnumber QNaN %f %I64X",s1.d,s2.l); // smallest nonnumber QNaN %f %I64X",s1.d,s2.l); // greatest nonnumber SNaN %f %I64X",s1.d,s2.l); // invalid number -1.#QNAN %f %I64X",s1.d,s2.l); // Get the invalid number -1.#IND
64
Language Basics
s2.l=0x0010000000000000; s1=s2; printf("12. //--s1.d=0.7; s2=s1; printf("13. /* 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. */ -1.#IND00 FFF8000000000000 -1.#QNAN0 FFFF000000000000 1.#SNAN0 7FF7000000000000 1.#QNAN0 7FF8000000000000 1.#QNAN0 7FFF000000000000 1.#INF00 7FF0000000000000 -1.#INF00 FFF0000000000000 -0.000000 8000000000000000 0.500000 3FE0000000000000 1.000000 3FF0000000000000 1.7976931348623157e+308 7FEFFFFFFFFFFFFF 2.2250738585072014e-308 0010000000000000 6.9999999999999996e-001 3FE6666666666666 %.16e %.16I64X",s1.d,s2.l); // Show that the number of 0.7 - endless fraction %.16e %.16I64X",s1.d,s2.l); // Smallest positive normalized (MIN_DBL)
65
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". The internal representation is the 8-byte large structure. The first element of the structure is an integer of the int buf_len type, it contains the size of the buffer allocated for the string. The second element of the buf_ptr structure is the 32-bit pointer to a buffer containing the string. Right before the buffer the str_len variable of the int type is placed; it contains the string length (number of characters in the string to the final zero). The member of the buf_len structure can take one of the following values: 0 indicates that this is a constant string that is stored in a pool of constant strings; -1 indicates that the line belongs to the client terminal (this line is cleared by the client terminal, and not by the performing subsystem); number - the size of the buffer in characters of the short type placed in the computer memory to store the string.
Tight before the buffer, there are 4 bytes for the service information about the string length. Information about the string length is obtained by the StringLen() function from this place. The string length can be of zero size, even if the buffer allocated for the string is of the non-zero size. The string end in the buffer is always at the place where where first byte containing 0 is met. 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";
If a variable of the string type is not explicitly initialized, the compiler adds the code that resets the
66
Language Basics specified structure. It is necessary for avoiding critical errors when calling such a variable. See also Conversion Functions, String Functions, FileOpen, FileReadString, FileWriteString
67
Language Basics
Structure Declaration
The structure data type is determined by the following description:
struct structure_name { elements_description };
The structure name can's be used as an identifier (name of a variable or function). It should be noted that in MQL5 structure elements follow one another directly, without alignment. In C++ such an order is made to the compiler using the following instruction:
#pragma pack(1)
If you want to do another alignment in the structure, use auxiliary members, "fillers" to the right size. Example:
struct trade_settings { uchar char short int slippage; reserved1; reserved2; reserved4; // value of the permissible slippage-size 1 byte // skip 1 byte // skip 2 bytes // another 4 bytes are skipped. ensure alignment of the boundary 8 bytes // Values of the price of profit fixing // Price value of the protective stop
Such a description of aligned structures is necessary only for transferring to imported dll-functions. Attention: This example illustrates incorrectly designed data. It would be better first to declare the take and stop large data of the double type, and then declare the slippage member of the double type. In this case, the internal representation of data will always be the same regardless of the value specified in #pragma pack(). If a structure contains variables of the string type and/or object of a dynamic array, the compiler assigns an implicit constructor to such a structure. This constructor resets all the structure members of string type and correctly initializes objects of the dynamic array.
Simple Structures
Structures that do not contain strings or objects of dynamic arrays are called simple structures; variables of such structures can be freely copied to each other, even if they are different structures. Variables of simple structures, as well as their array can be passed as parameters to functions
68
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. Datamembers 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 you a constructor is explicitly defined, the initialization of a structure or class variable using the initializing sequence is impossible. Example:
struct trade_settings { double take; double stop; uchar slippage; //--- Constructor trade_settings() { take=0.0; stop=0.0; slippage=5; } //--- Destructor ~trade_settings() { Print("This is the end"); } }; //--- Compiler will generate an error message that initialization is impossible trade_settings my_set={0.0,0.0,5}; // values of the profit fixing price // value of the protective stop price // value of the acceptable slippage
69
Language Basics
m_type; m_xpos; m_ypos; m_xsize; m_ysize; m_prev_turn; m_turn; m_right_border; CTetrisShape(); SetRightBorder(int border) { SetYPos(int ypos) { SetXPos(int xpos) { GetYPos() { GetXPos() { GetYSize() { GetXSize() { GetType() { Left() { Right() { Rotate() { Draw() { CheckDown(int& pad_array[]); CheckLeft(int& side_row[]); CheckRight(int& side_row[]);
m_right_border=border; } m_ypos=ypos; } m_xpos=xpos; } return(m_ypos); } return(m_xpos); } return(m_ysize); } return(m_xsize); } return(m_type); } m_xpos-=SHAPE_SIZE; } m_xpos+=SHAPE_SIZE; } m_prev_turn=m_turn; if(++m_turn>3) m_turn=0; } return; }
70
Language Basics Functions with SetRightBorder(int border) on the 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 as the scope. Example:
//+------------------------------------------------------------------+ //| Constructor of the basic class | //+------------------------------------------------------------------+ void CTetrisShape::CTetrisShape() { m_type=0; m_ypos=0; m_xpos=0; m_xsize=SHAPE_SIZE; m_ysize=SHAPE_SIZE; m_prev_turn=0; m_turn=0; m_right_border=0; } //+------------------------------------------------------------------+ //| Checking ability to move down (for the stick and cube) | //+------------------------------------------------------------------+ bool CTetrisShape::CheckDown(int& pad_array[]) { int i,xsize=m_xsize/SHAPE_SIZE; //--for(i=0; i<xsize; i++) { if(m_ypos+m_ysize>=pad_array[i]) return(false); } //--return(true); }
71
Language Basics
int int int CTetrisShape bool public: void void void void void void void void private: void void void }; NewShape(); CheckAndDeleteRows(); LabelOver(); CTetrisField() { m_shape=NULL; m_bover=false; } Init(); Deinit(); Down(); Left(); Right(); Rotate(); Drop(); m_field[FIELD_HEIGHT][FIELD_WIDTH]; // Matrix of the DOM m_rows[FIELD_HEIGHT]; m_last_row; *m_shape; m_bover; // Numbering of the DOM rows // Last free row // Tetris figure // Game over
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
72
Language Basics
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)) return(false);
73
Language Basics
... 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 MQL5functions. In this case, when passing the parameter a temporary object of a dynamic array, connected with the static array - structure member, will be created. See also Array Functions, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
74
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 f = ",f); f= 123456792.00000 Print("n = ",n,"
// result n= 123456789
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 */
75
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.
An expression or function execution result can be used as the var_2 variable. The functional recording of the explicit typecasting is also possible:
var_1 = type(var_2);
76
Language Basics 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; // no types casting, the result is 0 ",i); // the expression is cast to the double type, ",k); // then is to the target type of int, the result is 0
double d=1.0/2.0;
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, // the result is 0.0
// result is "0.12500000" (a string containing 10 characters) string s2=NULL; Print("s2 = NULL; ",s2); // string deinitialization // the result is an empty string
77
Language Basics
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));
78
Language Basics
s2=s1; printf("1. //--s3=s2; printf("2. //--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); high part of long %.8X low part of long %.8X", s3.high_part,s3.low_part); %f %I64X",s1.d,s2.l);
Another example illustrates the method of organizing a custom function for receiving RGB (Red, Green, Blue) representation from the color type. Create two structures of the same size but with different contents. For convenience, let's add a function returning the RGB representation of a color as a string.
#property script_show_inputs input color struct RGB { uchar uchar uchar uchar 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 }; //+------------------------------------------------------------------+ //| Script program start function void OnStart() { //--- a variable for storing in RGB RGB colorRGB; //--- variable for storing the color type builtColor test; | //+------------------------------------------------------------------+ c; blue; green; red; empty; toString(); // blue component of color // green component of color // red component of color // this byte is not used // function for receiving a string testColor=Blue;// set color for testing //--- structure for representing color as RGB
79
Language Basics
test.c=testColor; //--- casting two structures by copying contents colorRGB=test; Print("color ",test.c,"=",colorRGB.toString()); //--}
80
Language Basics
Also NULL can be compared to pointers to objects created with the new operator. See also Variables, Functions
81
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();
Again, unlike C++, the variable hobject from the example above is not a pointer to the memory, it is a descriptor of the object. See also Variables, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
82
Language Basics
m_array[];
public: void setArray(double &array[]); }; //+------------------------------------------------------------------+ //| filling the array | //+------------------------------------------------------------------+ void CDemoClass::setArray(double &array[]) { if(ArraySize(array)>0) { ArrayResize(m_array,ArraySize(array)); ArrayCopy(m_array, array); } }
In the above example class CDemoClass is declared, which contains the private member - array m_array[] of double type. Function setArray() is declared, to which array[] is passed by reference. If the function header doesn't contain the indication about passing by reference, i.e. doesn't contain the ampersand character, an error message will be generated at the attempt to compile such a code. Despite the fact that the array is passed by reference, we can't assign one array to another. We need to perform the element-wise copying of contents of the source array to the recipient array. The presence of & in the function description is the obligatory condition for arrays and structures when passed as the function parameter.
Keyword this
A variable of class type (object) can be passed both by reference and by pointer. As well as reference, 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.
83
Language Basics The reserved word this is intended for obtaining the reference of the object to itself, which is available inside class or structure methods. this always references to the object, in the method of which it is used, and the expression GetPointer(this) gives the pointer of the object, whose member is the function, in which call of GetPointer() is performed. In MQL5 functions can't return objects, but they can return the object pointer. Thus, if we need a function to return an object, we can return the pointer of this object in the form of GetPointer(this). Let's add function getDemoClass() that returns pointer of the object of this class, into the description of CDemoClass.
class CDemoClass { private: double
m_array[];
public: void setArray(double &array[]); CDemoClass *getDemoClass(); }; //+------------------------------------------------------------------+ //| filling the array | //+------------------------------------------------------------------+ void CDemoClass::setArray(double &array[]) { if(ArraySize(array)>0) { ArrayResize(m_array,ArraySize(array)); ArrayCopy(m_array,array); } } //+------------------------------------------------------------------+ //| returns its own pointer | //+------------------------------------------------------------------+ CDemoClass *CDemoClass::getDemoClass(void) { return(GetPointer(this)); }
Structures don't have pointers, operators new and delete can't be applied to them, not GetPointer (this) can be used. See also Object Pointers, Creating and Deleting Objects, Visibility Scope and Lifetime of Variables
84
Language Basics
Operation symbols are used in expressions and have sense when appropriate operands are given them. Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and semicolon. Operation symbols, punctuation marks, and spaces are used to separate language elements from each other. This section contains the description of the following topics: Expressions Arithmetical Operations Assignment Operations Operations of Relation Boolean Operations Bitwise Operations Other Operations Priorities and Operations Order
85
Language Basics
Expressions
An expression consists of one or more operands and operation symbols. An expression can be written in several lines. Examples:
a++; b = 10; //--x = (y * z) / (w + 2) + 127; // several expressions are located in one line
An expression that ends with a semicolon (;) is an operator. See also Precedence Rules
86
Language Basics
Arithmetic Operations
Arithmetical operations include additive and multiplicative operations:
Sum of variables Difference of variables Changing the sign Product of variables Division quotient Divisions reminder Adding 1 to the variable value Adding 1 to the variable value Subtracting 1 from the variable value Subtracting 1 from the variable value i = j + 2; i = j - 3; x = - x; z = 3 * x; i = j / 5; minutes = time % 60; i++; ++i; k--; --k;
Increment and decrement operations are applied only to variables, they can't be applied to constants. The prefix increment (++i) and decrement (-k) are applied to the variable right before this variable is used in an expression. Post-increment (i++) and post-decrement (k-) are applied to the variable right after this variable is used in an expression. Examples:
int a=3; a++; int b=(a++)*3; // valid expression // invalid expression
87
Language Basics
Assignment Operations
The value of the expression that includes the given operation is the value of the left operand after assignment:
Assignment the x value to the y variable y = x;
The following operations unite arithmetic or bitwise operations with operation of assignment:
Adding x to the y variable Subtracting x from the y variable Multiplying the y variable by x Dividing the y variable by x Reminder of division of the y variable by x The shift of the binary representation of y to the right by x bit The shift of the binary representation of y to the left by x bit y AND bitwise operation of binary representations of y and x OR bitwise operation of binary representations of y and x Excluding OR bitwise operation of binary representations of y and x y += x; y -= x; y *= x; y /= x; y %= x; y >>= x; y <<= x; y &= x; y |= x; y ^= x;
Bitwise operations can be applied to integers only. When performing the operation of the logical shift of the y representation to the right/left by x bits, the 5 smallest binary digits of the x value are used, the highest ones are dropped, i.e. the shift is made to 0-31 bits. By %= operation (y value by module of x), the result sign is equal to the sign of divided number. The assignment operator can be used several times in an expression . In this case the processing of the expression is performed from left to right:
y=x=3;
First, the variable x will be assigned the value 3, then the y variable will be assigned the value of x, i. e. also 3. See also Precedence Rules
88
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 True if a is not equal to b True if a is less than b True if a is greater than b True if a is less than or equal to b True if a is greater than or equal to b a == b; a != b; a < b; a > b; a <= b; a >= b;
The equality of two real numbers can't be compared. In most cases, two seemingly identical numbers can be unequal because of different values in the 15th decimal place. In order to correctly compare two real numbers, compare the normalized difference of these numbers with zero. Example:
bool CompareDoubles(double number1,double number2) { if(NormalizeDouble(number1-number2,8)==0) return(true); else return(false); } void OnStart() { double first=0.3; double second=3.0; double third=second-2.7; if(first!=third) { if(CompareDoubles(first,third)) printf("%.16f and %.16f are equal",first,third); } } // Result: 0.3000000000000000 0.2999999999999998 are equal
89
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");
Print("Operation &&: Result of the first expression is false, so the second wasn't calculated
Print("Operation ||: Result of the first expression is true, so the second wasn't calculated"
90
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); } | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
91
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, " // a = 97 b = -98 b = ",b); // The result will be:
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: b=a>>1; Print("After: // Before: // After: a = 97 a = 97 a = ",a, " b = 98 b = 48 b = ",b); // The result will be: a = ",a, " b = ",b); //--- shift to the right
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: b=a<<1; Print("After: a = ",a, " b = ",b); a = ",a, " b = ",b); //--- shift to the left
92
Language Basics
// The result will be: // Before: // After: a = 97 a = 97 b = 98 b = -62
It is not recommended to shift by the number of bits larger or equal to the length of the variable shifted, because the result of such an operation is undefined.
Example:
char a='a',b='b'; //--- AND operation char c=a&b; Print("a = ",a," b = ",b); 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
Example:
93
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 = 99
Bitwise operations are performed with integers only. See also Precedence Rules
94
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 measurement is indexed from 0 to measurement size-1. In particular case, for a one-dimensional array consisting of 50 elements, the reference to the first element will look like array [0], that to the last element will be array [49]. When addressing beyond the array, the executing subsystem will generate a critical error, and the program will be stopped.
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:
95
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 usesd. Syntax:
Variable_name_of_structure_type.Member_name
Example:
struct SessionTime { string sessionName; int int int int } st; st.sessionName="Asian"; st.startHour=0; st.startMinutes=0; st.endHour=9; st.endMinutes=0; startHour; startMinutes; endHour; endMinutes;
If there is no scope name, this is the explicit direction to use the global scope. If there is no scope resolution operation, the function is sought in the nearest scope. If there is no function n the local scope, the search is conducted in the global scope. The scope resolution operation is also used to define function-class member.
type Calss_name::Function_name(parameters_description) { // function body }
Example:
#property script_show_inputs #import "kernel32.dll" int GetLastError(void); #import
96
Language Basics
class CCheckContext { int public: CCheckContext() { m_id=1234; } protected: int }; class CCheckContext2 : public CCheckContext { int public: CCheckContext2() { m_id2=5678; } void protected: int }; 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(); } //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+ GetLastError() { return(m_id2); } Print(); m_id2; GetLastError() { return(m_id); } m_id;
Operation of Obtaining Data Type Size or Size of Any Data Type 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 the the type length). If the
97
Language Basics 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 int } str; Print("sizeof(str) = ",sizeof(str)); Print("sizeof(myStruct) = ",sizeof(myStruct)); h; b;
double f;
The size is calculated at the compilation stage. See also Precedence Rules
98
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 Function Call Referencing to an array element Referencing to a structure element Logical negation Bitwise negation (complement) Sign changing Increment by one Decrement by one Typecasting Determining size in bytes Multiplication Division Module division Addition Subtraction Left shift Right shift Less than Less than or equal Greater than Greater than or equal Equal Not equal Bitwise AND operation Bitwise exclusive OR Bitwise OR operation Logical AND operation Logical OR operation Conditional Operator Execution Order From left to right
! ~ ++ -(type) sizeof
Right to left
From left to right From left to right From left to right From left to right From left to right Right to left
99
Language Basics
Assignment Multiplication with assignment 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
Right to left
To change the operation execution order, parenthesis that are of higher priority are used.
100
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 Compound operator {} Description One or more operators of any type, enclosed in curly braces {} Any expression that ends with a semicolon (;) Terminates the current function and returns control to the calling program Is used when it's necessary to make a choice A simple analog of the if-else conditional operator Passes control to the operator, corresponds to the expression value which
Performs an operator until the expression checked becomes false. The expression is checked before each iteration Performs an operator until the expression checked becomes false. The expression is checked before each iteration 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. Terminates the execution of the nearest attached external operator switch, while, dowhile or for Passes control to the beginning of the nearest external loop operator while, do-while or for Creates an object of the appropriate size and returns a descriptor of the created object. Deletes the object created by the new operator
break operator
continue operator
new operator
delete operator
One operator can occupy one or more lines. Two or more operators can be located in the same line. Operators that control over the execution order (if, if-else, switch, while and for), can be nested into each. Example:
if(Month() == 12)
101
Language Basics
if(Day() == 31) Print("Happy New Year!");
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
102
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
103
Language Basics
Expression Operator
Any expression followed by a semicolon (;) is the operator. Here are some examples of expression operators.
Assignment Operator
Identifier = expression;
x=3; y=x=3; bool equal=(x==y);
Assignment operator can be used many times in an expression. In this case, the expression is processed from left to right:
Empty Operator
Consists only of a semicolon (;) and is used to denote an empty body of a control operator. See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
104
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
105
Language Basics
If the expression is true, operator1 is executed and control is given to the operator that follows operator2 (operator2 is not executed). If the expression is false, operator2 is executed. The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators with omitted else part. In this case, else addresses to the nearest previous if operator in the same block that has no else part. Examples:
//--- The else part refers to the second if operator: if(x>1) if(y==2) z=5; else if(x>l) { if(y==2) z=5; } else if(x=='a') { y=1; } else if(x=='b') { y=2; z=3; } else if(x=='c') { y=4; } else Print("ERROR"); z=6; //--- Nested operators z=6; //--- The else part refers to the first if operator:
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
106
Language Basics
?: conditional Operator
The general form of the ternary operator is as follows:
expression1? expression2:expression3
For the first operand - "expression1" - any expression that results in a bool type value can be used. If the result is true, then the operator set by the second operand, i.e. "expression2" is executed. If the first operand is false, the third operand - "expression3" is performed. The second and third operands, i.e. "expression2" and "expression3" should return values of one type and should not be of void type. The result of the conditional operator execution is the result of expression2 or result of the expression3, depending on the result of expression1.
//--- normalize difference between open and close prices for a day range double true_range = (High==Low)?0:(Close-Open)/(High-Low);
Note Be careful when using the conditional operator as an argument of an overloaded function, because the type of the result of a conditional operator is defined at the time of program compilation. An this type is defined as the larger of the types "expression2" "expression3". Example:
void func(double d) { Print("double argument: ",d); } void func(string s) { Print("string argument: ",s); } bool Expression1=true;
double Expression2=M_PI; string Expression3="3.1415926"; void OnStart() { func(Expression2); func(Expression3); func(Expression1?Expression2:Expression3); func(!Expression1?Expression2:Expression3); } // // // : double argument: 3.141592653589793 string argument: 3.1415926 // warning on implicit casting to string // warning on implicit casting to string
107
Language Basics
// // string argument: 3.141592653589793 string argument: 3.1415926
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
108
Language Basics
Switch Operator
It compares the expression value with constants in all variants of case and gives control to the operator that corresponds to the expression value. Each variant of case can be marked with an integer constant, a literal constant or a constant expression. The constant expression can's contain variables or function calls. Expression of the switch operator must be of integer type.
switch(expression) { case constant: operators case constant: operators ... default: operators }
Operators connected with the default label are executed if none of the constants in case operators equals to the expression value. The default variant should not necessarily be announced and should not necessarily be the last one. If none of the constants corresponds to the expression value and the default variant is not available, no actions are executed. The keyword case and the constant are just labels, and if operators are executed for some case variant, the program will further execute the operators of all following variants until the break operator occurs. It makes it possible to bind a subsequence of operators with several variants. A constant expression is calculated during compilation. No two constants in one switch operator can have the same value. Examples:
//--- 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
109
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
110
Language Basics
If the expression is true, the operator is executed until the expression becomes false. If the expression is false, the control is passed to the next operator. The expression value is defined before the operator is executed. Therefore, if the expression is false from the very beginning, the operator will not be executed at all. Example:
while(k<n) { y=y*x; k++; }
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
111
Language Basics
Expression1 describes the loop initialization. Expression2 checks the conditions of the loop termination. If it is true, the loop body for is executed. The loop repeats expression2 becomes false. If it is false, the loop is terminated, and control is transferred 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 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 ','. Examples:
for(x=1;x<=7;x++) Print(MathPower(x,2)); //--- Another example for(;;) { Print(MathPower(x,2)); x++; if(x>10) break; } //--- Third example for(i=0,j=n-l;i<n;i++,j--) a[i]=a[j];
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
112
Language Basics
First the operator is executed, then the expression is calculated. If it is true, then the operator is executed again, and so on. If the expression becomes false, the loop terminates. Example:
//--- Calculate the Fibonacci series int counterFibonacci=15; int i=0,first=0,second=1; int currentFibonacciNumber; do { currentFibonacciNumber=first+second; Print("i = ",i," first=second; second=currentFibonacciNumber; i++; // without this operator an infinite loop will appear! } while(i<counterFibonacci); currentFibonacciNumber = ",currentFibonacciNumber);
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
113
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 us 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
114
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
115
Language Basics
It should be noted that the object descriptor not a pointer to the memory. The object created with the new operator must be explicitly removed by the delete operator. See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
116
Language Basics
See also Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
117
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 { // composite operator return (a + b); } // return value // return value type
The return operator can return the value of an expression located in this operator. If necessary, the expression value is converted to the function result type. A function that returns no value should be described as that of void type. Example:
void errmesg(string s) { Print("error: "+s); }
Parameters passed to the function can have default values, which are defined by constants of that type. Example:
118
Language Basics
int somefunc(double a, double d=0.0001, int n=5, bool b=true, string s="passed string") { Print("Required parameter a = ",a); Print("Pass the following parameters: d = ",d," n = ",n," b = ",b," s = ",s); return(0); }
If any of parameters has a default value, all subsequent parameters must also have default values. Example of incorrect declaration:
int somefunc(double a, double d=0.0001, int n, bool b, { } // default value 0.0001 declared // default value is not specified ! // default value is not specified !
119
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 xl,..., Xn is calculated, and the value is passed to the function. The order of expressions calculation and that of values loading are guaranteed. During the execution, the system checks the number and type of arguments passed to the function. Such way of addressing to the function is called a value call. Function call is an expression, the value of which is the value returned by the function. The function type described above must correspond with the type of the return value. The function can be declared or described in any part of the program on the global scope, i.e., outside other functions. The function cannot be declared or described inside of another function. Examples:
int start() { double some_array[4]={0.3, 1.4, 2.5, 3.6}; double a=linfunc(some_array, 10.5, 8); //... } double linfunc(double x[], double a, double b) { return (a*x[0] + b); }
At calling of a function with default parameters, the list of parameters to be passed can be limited, but not before the first default parameter. Examples:
void somefunc(double init, double sec=0.0001, //set default values int level=10); //... somefunc(); somefunc(3.14); somefunc(3.14,0.0002); somefunc(3.14,0.0002,10); // Wrong call. The first parameter must be presented. // Correct call // Correct call // 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.
120
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; | //+------------------------------------------------------------------+
121
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 and structure type variables (class objects) are always passed by reference. In order to exclude changes in actual parameters (arguments passed at function call) use the access specifier const. When trying to change the contents of a variable declared with the const specifier, the compiler will generate an error.
Note
It should be noted that parameters are passed to a function in reversed order, i.e., first the last parameter is calculated and passed, and then the last but one, etc. The last calculated and passed parameter is the one that stands first after braces. Example:
void OnStart() { //--int a[]={0,1,2}; int i=0; 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 } //+------------------------------------------------------------------+ //| void func(int par1,int par2,string comment) { | //+------------------------------------------------------------------+ par2 = 0 par2 = 1
122
Language Basics
Print(comment,": par1 = ",par1," } par2 = ",par2);
At first call in the mentioned example the i variable first takes part in the concatenation of strings
"First call (i = "+string(i)+")"
Here its value doesn't change. The i variable takes part in the calculation of the a[i++] array element, i.e. after the i element of the array is taken, the i variable is incremented. And only after that the first parameter with the changed value of i variable is calculated. At the second call when calculating all three parameters, one and the same value of i is used, the one that was calculated on the first phase of function calling, and only after the first parameters is calculated the i variable is changed again. See also Visibility Scope and Lifetime of Variables, Overload, Virtual Functions, Polymorphism
123
Language Basics
Function Overloading
Usually the function name tends to reflect its main purpose. As a rule, readable programs contain various well selected identifiers. Sometimes different functions are used for the same purposes. Let's consider, for example, a function that calculates the average value of an array of double precision numbers and the same function, but operating with an array of integers. Both are convenient to be called AverageFromArray:
//+------------------------------------------------------------------+ //| The calculation of average for an array of double type double AverageFromArray(const double & array[],int size) { if(size<=0) return 0.0; double sum=0.0; double aver; //--for(int i=0;i<size;i++) { sum+=array[i]; } aver=sum/size; //--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]; } 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; } // Addition to the double | //+------------------------------------------------------------------+ // Just divide the sum by the number // Addition to the double | //+------------------------------------------------------------------+
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
124
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," } //--- 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 double_aver = ",double_aver); | //+------------------------------------------------------------------+
Overloading is the practice of assigning multiple values to a function. Selecting a specific value depends on the types of arguments received by the function. A specific function is selected based on the correspondence of the list of arguments when calling the function, to the list of parameters in the function declaration. When an overloaded function is called, the compiler must have an algorithm to select the appropriate function. The algorithm that performs this choice depends on conversions of what type are present. The best correlation must be unique. It must be the best for at least one argument, and as well as the other correspondences for all other arguments. Below is a matching algorithm for each argument.
125
Language Basics 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 fmax() in 3 different ways, but only two variants are correct. Example:
// overload is permissible - differs in the number of parameters double fmax(double a,double b,double c); // overload with error // 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 fmax(double a,double b,double c=DBL_MIN); // normal overload by the parameter type int fmax(int a,int b);
126
Language Basics
#import "lib.ex5"
With the help of import, it is easy to describe functions that are called from external DLL or compiled EX5 libraries. EX5 libraries are compiled ex5 files, which have the library property. Only function described with the export modifier can be imported from EX5 libraries. See also Overload, Virtual Functions, Polymorphism
127
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
128
Language Basics
OnStart
The OnStart() function is the Start event handler, which is automatically generated only for running scripts. It must be of void type, with no parameters:
void OnStart();
For the OnStart() function, the int return type can be specified.
OnInit
The OnInit() function is the Init event handler. It must be of void or int type, with no parameters:
void OnInit();
The Init event is generated immediately after an Expert Advisor or an indicator is downloaded; this event is not generated for scripts. The OnInit() function is used for initialization. If OnInit() has the int type of the return value, the non-zero return code means unsuccessful initialization, and it generates the Deinit event with the code of deinitialization reason REASON_INITFAILED. 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 a mql5 program.
OnTick
129
Language Basics The NewTick event is generated for Expert Advisors only when a new tick for a symbol is received, to the chart of which the Expert Advisor is attached. It's useless to define the OnTick() function in a custom indicator or script, because the Tick event is not generated for them. The Tick event is generated only for Expert Advisors, but this does not mean that Expert Advisors required the OnTick() function, since not only Tick events are generated for Expert Advisors, but also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type, with no parameters:
void OnTick();
OnTimer
The OnTimer() function is called when the Timer event occurs, which is generated by the system timer only for Expert Advisors and indicators - it can't be used in scripts. The frequency of the event occurrence is set when subscribing to notifications about this event to be received by the EventSetTimer() function. You can unsubscribe from receiving timer events for a particular Expert Advisor using the EventKillTimer() function. The function must be defined with the void type, with no parameters:
void OnTimer();
It is recommended to call the EventSetTimer() function once in the OnInit() function, and the EventKillTimer() function should be called once in OnDeinit(). Every Expert Advisor, as well as every indicator works with its own timer and receives events only from it. As soon as a mql5 program stops operating, the timer is destroyed forcibly if it was created but hasn't been disabled by the EventKillTimer() function.
OnTrade
The function is called when the Trade event occurs, which appears when you change the list of placed orders and open positions, the history of orders and history of deals. When a trade activity is performed pending order opening, position opening/closing, stops setting, pending order triggering, etc.) the history of orders and trades and/or list of positions and current orders is changed accordingly.
void OnTrade();
Users must independently implement in the code the verification of a trade account state when such an event is received (if this is required by the trade strategy conditions). If the OrderSend() function call has been completed successfully and returned a value of true, this means that the trading server has put the order into the queue for execution and assigned a ticket number to it. As soon as the server processes this order. the Trade event will be generated. And if the user remembers the ticket value, during OnTrade() event handling he/she will be able to find out what happened to the order using this value.
OnTester
The OnTester() function is the handler of the Tester event that is automatically generated after a history testing of an Expert Advisor on the chosen interval is over. The function must be defined with the double type, with no parameters:
130
Language Basics
double OnTester();
The function is called right before the call of OnDeinit() and has the same type of the return value double. OnTester() can be used only in the testing of Expert Advisors. Its main purpose is to calculate a certain value that is used as the Custom max criterion in the genetic optimization of input parameters. In the genetic optimization descending sorting is applied to results within one generation. I.e. from the point of view of the optimization criterion, the best results are those with largest values (for the Custom max optimization criterion values returned by the OnTester function are taken into account). In such a sorting, the worst values are positioned at the end and further thrown off and do not participate in the forming of the next generation.
OnBookEvent
The OnBookEvent() function is the BookEvent handler. BookEvent is generated for Expert Advisors only when Depth of Market changes. It must be of the void type and have one parameter of the string type:
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_OBJECT_CREATE event of graphical object creation; CHARTEVENT_OBJECT_CHANGE event of change of an object property via the properties dialog; CHARTEVENT_OBJECT_DELETE event of graphical object deletion; 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_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:
131
Language Basics
void OnChartEvent(const int id, const long& lparam, const string& sparam ); // Event ID // Parameter of type long event // 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 this parameters are listed in the below table. Event Value of the id parameter Value of lparam parameter code of pressed key the Value of dparam parameter the Value of sparam parameter the
Event of keystroke
event of graphical object creation Event of change of an object property via the properties dialog Event of graphical object deletion Event of a mouse click on the chart Event of a mouse click in a graphical object belonging to the chart Event of a graphical object dragging using the mouse Event of the finished text editing in the entry box of the LabelEdit graphical object ID of the user event under the
Name of the created graphical object Name of the modified graphical object
CHARTEVENT_OB JECT_CHANGE
CHARTEVENT_OB JECT_DELETE
CHARTEVENT_C LICK
the X coordinate
the Y coordinate
CHARTEVENT_OB JECT_CLICK
the X coordinate
the Y coordinate
CHARTEVENT_OB JECT_DRAG
CHARTEVENT_OB JECT_ENDEDIT
Name of the LabelEdit graphical object, in which text editing has completed Value set by the EventChartCusto
CHARTEVENT_CU STOM+N
132
Language Basics
N number
m() fubction
m() function
m() function
OnCalculate
The OnCalculate() function is called only in custom indicators when it's necessary to calculate the indicator values by the Calculate event. This usually happens when a new tick is received for the symbol, for which the indicator is calculated. This indicator is not required to be attached to any price chart of this symbol. The OnCalculate() function must have a return type int. There are two possible definitions. Within one indicator you cannot use both versions of the function. The first form is intended for those indicators that can be calculated on a single data buffer. An example of such an indicator is Custom Moving Average.
int OnCalculate (const int rates_total, const int prev_calculated, const int begin, const double& price[] ); // size of the price[] array // bars handled on a previous call // where the significant data start from // array to calculate
As the price[] array, one of timeseries or a calculated buffer of some indicator can be passed. To determine the direction of indexing in the price[] array, call ArrayGetAsSeries(). In order not to depend on the default values, you must unconditionally call the ArraySetAsSeries() function for those arrays, that are expected to work with. The appropriate timeseries or indicator as the price[] array is selected by the user when starting the indicator in the "Parameters" tab. To do this you must specify the necessary item in the drop-down list of the "Apply to" field.
To receive values of a custom indicator from other mql5 programs, the iCustom() function is used, which returns the indicator handle for nest operations. You can also specify the appropriate price[] array or the handle of another indicator. This parameter should be transmitted last in the list of input variables of the custom indicator. Example:
133
Language Basics
void OnStart() { //--string terminal_path=StatusInfoString(STATUS_TERMINAL_PATH); if(handle_customMA>0) Print("handle_customMA = ",handle_customMA); else }
In this example, the last parameter passed is the PRICE_TYPICAL value (from the ENUM_APPLIED_PRICE enumeration), which indicates that the custom indicator will be built on typical prices obtained as (High+Low+Close)/3. If this parameter is not specified, the indicator is built based on PRICE_CLOSE values, i.e. closing prices of each bar. Another example that shows passing of the indicator handler as the last parameter to specify the price [] array, is given in the description of the iCustom() function.
The second form is intended for all other indicators, in which more than one timeseries is used for calculations.
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[] ); // size of input timeseries // bars handled in previous call // Time // Open // High // Low // Close // Tick Volume // Real Volume // Spread
Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and low prices and close prices of the current timeframe.The time[] parameter contains an array with open time values, the spread[] parameter has an array containing the history of spreads (if any spread is provided for the traded security). The parameters of volume[] and tick_volume[] contain the history of trade and tick volume, respectively. To determine the indexing direction of time[], open[], high[], low[], close[], tick_volume[], volume[] and spread[], call ArrayGetAsSeries(). In order not to depend on default values, you should unconditionally call the ArraySetAsSeries() function for those arrays, which are expected to work with. The first rates_total parameter contains the number of bars, available to the indicator for calculation, and corresponds to the number of bars available in the chart. We should noted the connection between the return value of OnCalculate() and the second input parameter prev_calculated. During the function call, the prev_calculated parameter contains a value returned by OnCalculate() during previous call. This allows for economical algorithms for calculating the custom indicator in order to avoid repeated calculations for those bars that haven't changed since
134
Language Basics the previous run of this function. For this, it is usually enough to return the value of the rates_total parameter, which contains the number of bars in the current function call. If since the last call of OnCalculate() price data has changed (a deeper history downloaded or history blanks filled), the value of the input parameter prev_calculated will be set to zero by the terminal. Note: if OnCalculate returns zero, then the indicator values are not shown in the DataWindow of the client terminal. To understand it better, it would be useful to start the indicator, whose code is attached below. Indicator Example:
#property indicator_chart_window #property indicator_buffers 1 #property indicator_plots //---- plot Line #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- indicator buffers double LineBuffer[]; | //+------------------------------------------------------------------+ //| Custom indicator initialization function int OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,LineBuffer,INDICATOR_DATA); //--return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime& time[], const double& open[], const double& high[], const double& low[], const double& close[], const long& tick_volume[], const long& volume[], const int& spread[]) { //--- Get the number of bars available for the current symbol and chart period | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "Line" DRAW_LINE DarkBlue STYLE_SOLID 1 1
135
Language Basics
int bars=Bars(Symbol(),0); Print("Bars = ",bars,", rates_total = ",rates_total,", //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+ prev_calculated = ",prev_calculated); Print("time[0] = ",time[0]," time[rates_total-1] = ",time[rates_total-1]);
See also Running Programs, Client Terminal Events, Working with Events
136
Language Basics
Variables
Declaring Variables
Variables must be declared before they are used. Unique names are used to identify variables. Descriptions of variables are used for them to be defined and for types to be declared. Description is not an operator. 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 bool color nOrders; bLog; = D'2004.01.01 00:00'; cModify_Color = C'0x44,0xB9,0xE6'; double dSymbolPrice; datetime tBegin_Data
Complex or compound types: Structures are composite data types, constructed using other types.
struct MyTime { int hour; int minute; int second; }; ... MyTime strTime; // Variable of the previously declared structure MyTime MyTime // 0-23 // 0-59 // 0-59
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]; // 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
double m[7][50];
137
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. The const specifier can't be applied to members of structures and classes. Sample
int OnCalculate (const int rates_total, const int prev_calculated, const int begin, const double& price[] ); // size of the price[] array // bars handled on a previous call // where the significant data start from // 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 declare on a local level is not a static one, memory for such a variable is allocated automatically at a program stack. Freeing of memory allocated for a non-static array is also performed automatically when going beyond the visibility area of the block, in which the array is declared. See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
138
139
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 referred to. Variables declared inside a block (at the internal level), have the block as their scope. The block scope start with the variable declaration and ends with the final right brace. Local variables declared in the beginning of a function also have the scope of block, as well as function parameters that are local variables. Any block can contain variable declarations. If blocks are nested and the identifier in the external block has the same name as the identifier in the internal block, the external block identifier is hidden, until the operation of the internal block is over. Example:
void OnStart() { //--int i=5; { int i=10; } Print("Outside block i = ",i); } // result is i=5; // function variable i=10; Print("In block i = ",i); // result is // local variable of the function
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
140
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. See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
141
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 shown in the calling function in any way. Arrays of any type and data of the structure type are always passed by reference. If it's necessary to prohibit modifying the array or structure contents, the parameters of these types must be declared with the const keyword. There is an opportunity to pass parameters of simple types by reference. In this case, modification of such parameters will affect the corresponding variables in the called function passed by reference. In order to indicate that a parameter is passed by reference, put the & modifier after the data type. Example:
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;
142
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
143
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 declare on a local level is not a static one, memory for such a variable is allocated automatically at a program stack. Example:
int Counter() { static int count; count++; if(count%100==0) Print("Function Counter has been called ",count," times"); return count; } void OnStart() { //--int c=345; for(int i=0;i<1000;i++) { int c=Counter(); } Print("c =",c); }
See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and
144
145
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; int OnStart() { ... } // Global variable
The scope of global variables is the entire program. Global variables are accessible from all functions defined in the program. They are initialized to zero unless another initial value is explicitly defined. A global variable can be initialized only by a constant or constant expression that corresponds to its type. Global Variables are initialized only once right after the program is loaded into the client terminal memory. Note: Variables declared at global level must not be mixed up with the client terminal global variables that can be accessed using the GlobalVariable...() functions. See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
146
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. Example:
//--- input parameters input int input int MA_Period=13; MA_Shift=0;
Input variables determine the input parameters of a program. They are available from the Properties window of a program.
It is possible to set another way to display names of input parameters in the Inputs tab. To do this, a string comment is used, which should be located after the description of an input parameter in the same line. Thus, names more understandable for a user can be matched to input parameters. Example:
//--- input parameters input int input int InpMAPeriod=13; InpMAShift=0; // Smoothing period // Line horizontal shift // Smoothing method
147
Language Basics
Note: Arrays and variables of complex types can't act as input variables.
148
Language Basics
//--- 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. Therefore, in order to select the input value the drop-down list is used. Mnemonic names of enumeration members are used for values displayed in the list. If a comment is associated with a mnemonic name, as shown in this example, the comment content is used instead of the mnemonic name. Each value of the dayOfWeek enumeration has its value from 0 to 6, but in the list of parameters, comments specified for each value will be shown. This provides additional flexibility for writing programs with clear descriptions of input parameters. See also iCustom, Enumerations, Properties of Programs
149
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 initializes extern variables of the same type and with the same identifier is prohibited. See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
150
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 n = 1; = "hello"; = { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 };
a[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4 } }; right[4]={WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER, WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER};
List of values of the array elements must be enclosed in curly brackets. Missed initializing sequences are considered equal to 0. The initializing sequence must have at least one value: this value is initialized to the first element of the corresponding structure or array, missing elements are considered equal to zero. If the size of the initialized array is not specified, it is determined by a compiler, based on the size of the initialization sequence. Multi-dimensional arrays cannot be initialized by a one-dimensional sequence (a sequence without additional curly brackets), except for the case, when only one initializing element is specified (zero, as a rule). Arrays (including those announced at the local level) can be initialized only by constants. Examples:
struct str3 { int int }; struct str10 { str3 double int }; void OnStart() { str10 s10_1={{1,0},{1.0,2.1,3.2,4.4,5.3,6.1,7.8,8.7,9.2,10.0},100}; str10 s10_2={{1,0},{0},100}; str10 s10_3={{1,0},{1.0}}; s3; d1[10]; i3; low_part; high_part;
151
Language Basics
//--Print("1. Print("2. Print("3. Print("4. } s10_1.d1[5] = ",s10_1.d1[5]); s10_2.d1[5] = ",s10_2.d1[5]); s10_3.d1[5] = ",s10_3.d1[5]); s10_3.d1[0] = ",s10_3.d1[0]);
See also Data Types, Encapsulation and Extensibility of Types, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects
152
Language Basics
153
Language Basics
for(int j=0; j<MA_Period; j++) sum+=(MA_Period-j)*price[i-j]; LineBuffer[i]=sum/weightsum; } //--}
Its scope is only the for cycle; outside of this cycle there is another variable with the same name, declared at the beginning of the function. In addition, the k variable is declared in the loop body, its scope is the loop body. Local variables can be declared with the access specifier static. In this case, the compiler has a variable in the global pool of memory. Therefore, the lifetime of a static variable is equal to the lifetime of the program. Here the scope of such a variable is limited to the block in which it is declared. See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Creating and Deleting Objects
154
Language Basics
155
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 are created by the new operator, and are assuredly deleted either by thedelete operator or automatically by the executing system of MQL5 during the program unloading. The order of declaration of pointers of dynamically created object does'nt influence the order of their initialization. The order of initialization and deinitialization is fully controlled by the programmer.
Initialization order
of
irrespective of the order of declaration when the delete operator is executed or before a mql5 program is unloaded irrespective of the initialization order
Deinitialization
Deinitialization order
in the order opposite to the initialization order at mql5 loading at mql5 unloading program
Constructor call
at the execution of the new operator at the execution of the delete operator
Destructor call
program
when exiting the block where the variable was initialized log in the "Experts" journal about the attempt to delete an automatically created
Error logs
log in the "Experts" journal about the attempt to delete an automatically created
log in the "Experts" journal about undeleted dynamically created objects at the
156
Language Basics
object
object
unload of program
mql5
See also Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility Scope and Lifetime of Variables
157
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 If the # symbol is used in the first line of the program, this line is a preprocessor directive. A preprocessor directive ends with a line feed character.
158
Language Basics
The #define directive substitutes token_string 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 #define PI #define COMPANY_NAME ... void ShowCopyright() { Print("Copyright } 2001-2009, ",COMPANY_NAME); Print("http://www.metaquotes.net"); 100 3.14 "MetaQuotes Software Corp."
token_string can consist of several tokens, such as keywords, constants, constant and non-constant expressions. token_string ends with the end of the line and can't be transferred to the next line. Example:
#define TWO #define THREE #define COMPLETE void OnStart() { Print("2 + 3*2 = ",INCOMPLETE*2); Print("(2 + 3)*2 = ",COMPLETE*2); } // Result // 2 + 3*2 = 8 // (2 + 3)*2 = 10 2 3 (TWO+THREE)
159
Language Basics
The compiler will write declared values in the configuration of the module executed. Constant link copyright version Type string string string Description link to the company website the company name program version, maximum 31 characters 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. size of the stack for recursive calls 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 show the indicator in the chart window show the indicator separate window int number of buffers indicator calculation in a
description
string
stacksize
int
library
indicator_applied_price
indicator_chart_window
indicator_separate_window
indicator_buffers
for
indicator_plots
int
160
Language Basics
indicator_minimum
double
the bottom scaling limit for a separate indicator window the top scaling limit for a separate indicator window 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 tag names are defined by the separator ';'. the color for displaying line N, where N is the number of graphic series; numbering starts from 1 line thickness in graphic series , where N - number of graphic series, numbering starts from 1 line style in graphic series, specified by the values of ENUM_LINE_STYLE. N number of graphic series, numbering starts from 1 type of graphical plotting, specified by the values of ENUM_DRAW_TYPE. N number of graphic series, numbering starts from 1 horizontal level of N in a separate indicator window color of horizontal levels of the indicator thickness of horizontal levels of the indicator style of horizontal levels of the indicator display a confirmation window before running the script display a window with the properties before running the
indicator_maximum
double
indicator_labelN
string
indicator_colorN
color
indicator_widthN
int
indicator_styleN
int
indicator_typeN
int
indicator_levelN
double
indicator_levelcolor
color
indicator_levelwidth
int
indicator_levelstyle
int
script_show_confirm
script_show_inputs
161
Language Basics
this
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 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 necessary ones, must always be specified. 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
tester_file
string
tester_library
string
#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
162
Language Basics
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 #property indicator_width1 #property indicator_label1 1 DRAW_CANDLES 3 "C open;C high;C low;C close"
163
Language Basics
Examples:
#include <WinUser32.mqh> #include "mylib.mqh"
The preprocessor replaces the line #include <file_name> with the content of the file WinUser32.mqh. Angle brackets indicate that the WinUser32.mqh file will be taken from the standard directory (usually it is terminal_installation_directory\MQL5\Include). The current directory is not visible. If the file name is enclosed in quotation marks, the search is made in the current directory (which contains the main source file). The standard directory is not visible. See also Standard Library, Importing Functions
164
Language Basics
Imported functions can have any names. Functions having the same names but from different modules can be imported at the same time. Imported functions can have names that coincide with the names of built-in functions. Operation of scope resolution defines which of the functions should be called. 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 bool RGB(int red_value,int green_value,int blue_value); CompareDoubles(double number1,double number2);
string DoubleToStrMorePrecision(double number,int precision); string IntegerToHexString(int integer_number); #import "ExpertSample.dll" int GetIntValue(int); double GetDoubleValue(double); string GetStringValue(string); double GetArrayItemValue(double &arr[],int,int); bool SetArrayItemValue(double &arr[],int,int,double); double GetRatesItemValue(double &rates[][6],int,int,int); #import
165
Language Basics 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
166
Language Basics
Object-Oriented Programming
Object-oriented programming (OOP) is programming primarily focused on data, data and behavior being inseparably linked. Data and behavior together constitute a class, while objects are class instances. 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 ribs. Also we need to regulate the falling speed of shapes, define operations of rotation and shift of shapes. Moving of shapes on the screen is limited by the DOM boundaries, this requirement must also be modeled. Besides that, filled rows of cubes must be destroyed and earned points must be counted.
Thus, this easy-to-understand game requires the creation of several models - shape model, DOM model, shape movement model and so on. All these models are abstractions, represented by calculations in the computer. To describe these models, the concept of Abstract Data Type, ADT (or complex data type) is used. Strictly speaking, the model of the "shapes" motion in the DOM is not a data type, but it is the totality of operations with the "shape" data type, using the restrictions of the "DOM" data type. Objects are class variables. Object-oriented programming allows you to easily create and use ADT. Object-oriented programming uses the inheritance mechanism. The advance of the inheritance is in the fact that it allows obtaining derivative types from data types already defined by a user. For example, to create Tetris shapes, it's convenient to create a base class Shape first; the other seven classes representing all of the possible shape types can be derived on its basis. Behavior of shapes is defined in the base class, while implementation of behavior of each separate shape is defined in derivative classes. In OOP objects are responsible for their behavior. ADT developer should include a code to describe any behavior that would normally be expected from the corresponding objects. The fact that the object itself is responsible for its behavior, greatly simplifies the task of programming for the user of this object. If we want to draw a shape on the screen, we need to know where the center will be and how to draw it. If a separate shape is well aware of how to draw itself, the programmer should send a "draw" message when using such a shape. The MQL5 Language is a C++ like, and it also has the encapsulation mechanism for the implementation of ADT. Encapsulation combines, on the one hand, the internal details of the implementation of a particular type and, on the other hand, externally accessible functions that can influence objects of this type. Implementation details may be inaccessible for a program that uses this
167
The concept of OOP has a set of related concepts, including the following: Simulation of actions from the real world Availability of 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 of general character.
168
Language Basics
Example:
class CPerson{} { protected: string public: void string }; SetName(string n){m_name=n;}// sets name GetName(){return (m_name);} // returns name m_name; // name
This approach offers several advantages. First, by function name we can understand what it does -
169
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 CPerson variable in the CPerson class or in any it's derivative classes. In this case, we'll need just to change the implementation of functions SetName() and GetName(), while objects of the CPerson class will be available for using in a program without any code changes because the user will not even know that the data type of m_name has changed. Example:
struct Name { string string }; class CPerson { protected: Name public: void string private: string string }; 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); GetFirstName(string full_name); GetLastName(string full_name); SetName(string n); GetName(){return(m_name.first_name+" "+m_name.last_name);} m_name; // name first_name; last_name; // name // last name
See also
170
171
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 its a property of all inert gases. Consider an example of the inheritance of geometric shapes. To describe the whole variety of simple shapes (circle, triangle, rectangle, square etc.), the best way is to create a base class (ADT), which is the ancestor of all the derived classes. Let's create a base class CShape, which contains just the most common members describing the shape. These members describe properties that are characteristic of any shape - the type of the shape and main anchor point coordinates. Example:
//--- The base class Shape class CShape { protected: int int int public: CShape(){m_type=0; m_xpos=0; m_ypos=0;} // constructor void void }; SetXPos(int x){m_xpos=x;} // set X SetYPos(int y){m_ypos=y;} // set Y m_type; m_xpos; m_ypos; // Shape type // X - coordinate of the base point // Y - coordinate of the base point
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:
172
Language Basics
//--- The derived class circle class CCircle : public CShape { private: int public: CCircle(){m_type=1;}// constructor, type 1 }; m_radius; // circle radius // After a colon we define the base class // from which inheritance is made
It should be noted that while object is created the base class constructor is called first, and then the constructor of the derived class is called. When an object is destroyed first the destructor of the derived class is called, and then a base class destructor is called. Thus, by declaring the most general members in the base class, we can add an additional members in derived classes, which specify a particular class. Inheritance allows creating powerful code libraries that can be reused many times. The syntax for creating a derived class from an already existing on is as follows:
class class_name : (public | protected | private) opt { class members declaration }; base_class_name
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
173
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. MQL5 has no multiple inheritance. See also Structures and Classes
174
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 re-define this function in accordance with rules of calculating the area of a particular shape. For a square (class CSquare), the area is calculated through its sides, for a circle (class CCircle), area is expressed through its radius etc. We can create an array to store objects of CShape type, in which both objects of a base class and those of all descendant classes can be stored. Further we can call the same function for each element of the array. Example:
//--- Base class class CShape{}; { protected: int int int public: void int virtual double }; GetArea(){return (0); }// returns area of the shape CShape(){m_type=0;}; // constructor, type=0 GetType(){return(m_type);};// returns type of the shape m_type; m_xpos; m_ypos; // Shape type // X - coordinate of the base point // Y - coordinate of the base point
Now, all of the derived classes have a member function getArea(), which returns a zero value. The implementation of this function in each descendant will vary.
//--- The derived class Circle class CCircle{} : public CShape { private: int public: void void }; CCircle(){m_type=1;}; // constructor, type=1 SetRadius(double r){m_radius=r;}; m_radius; // circle radius // After a colon we define the base class // from which inheritance is made
175
Language Basics
private: int public: void void }; CSquare(){m_type=2;}; // constructor, type=1 SetSide(double s){m_square_side=s;}; m_square_side; // square side
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. Now we can declare an array of the Shap typee and fill it with objects of derived classes:
CShape[10] shapes; for (int i=0; i<10;i++) { //--- type and area of the shape Print("Object type "+shapes[i].GetType()+" has an area "+ shapes[i].GetArea()); }; // array of CShape objects
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
176
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 polymorthism 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. MQL5 has no operator overloading. See also Reloading Functions
177
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 int int int int int int int public: void void void void int int int int int void void void CTetrisShape(); SetRightBorder(int border) { m_right_border=border; } SetYPos(int ypos) SetXPos(int xpos) GetYPos() GetXPos() GetYSize() GetXSize() GetType() Left() Right() Rotate() { m_ypos=ypos; { m_xpos=xpos; { return(m_ypos); { return(m_xpos); { return(m_ysize); { return(m_xsize); { return(m_type); { m_xpos-=SHAPE_SIZE; { m_xpos+=SHAPE_SIZE; } } } } } } } } } m_type; m_xpos; m_ypos; m_xsize; m_ysize; m_prev_turn; m_turn; m_right_border;
178
Language Basics
virtual void virtual bool virtual bool virtual bool }; Draw() { return; }
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 { int //--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); } } } } i; string name; Draw()
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()
179
Language Basics
{ int //--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); } } }; i; string name;
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(); //--}
180
181
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.
182
CHARTEVENT_CUSTOM_LAST
For each type of event, the input parameters of the OnChartEvent() function have definite values that are required for the processing of this event. The events and values passed through this parameters are listed in the below table. Event Value of the id parameter Value of lparam parameter code of pressed key the Value of dparam parameter the Value of sparam parameter the
Event of keystroke
event of graphical object creation Event of change of an object property via the properties dialog Event of
Name of the created graphical object Name of the modified graphical object
CHARTEVENT_OB JECT_CHANGE
CHARTEVENT_OB
Name
of
the
183
graphical object deletion Event of a mouse click on the chart Event of a mouse click in a graphical object belonging to the chart Event of a graphical object dragging using the mouse Event of the finished text editing in the entry box of the LabelEdit graphical object ID of the user event under the N number Example:
JECT_DELETE
CHARTEVENT_C LICK
CHARTEVENT_OB JECT_CLICK
the X coordinate
the Y coordinate
CHARTEVENT_OB JECT_DRAG
CHARTEVENT_OB JECT_ENDEDIT
Name of the LabelEdit graphical object, in which text editing has completed Value set by the EventChartCusto m() function
CHARTEVENT_CU STOM+N
184
185
186
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 PERIOD_CURRENT PERIOD_M1 PERIOD_M2 PERIOD_M3 PERIOD_M4 PERIOD_M5 PERIOD_M6 PERIOD_M10 PERIOD_M12 PERIOD_M15 PERIOD_M20 PERIOD_M30 PERIOD_H1 PERIOD_H2 PERIOD_H3 PERIOD_H4 PERIOD_H6 PERIOD_H8 PERIOD_H12 PERIOD_D1 PERIOD_W1 PERIOD_MN1 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);
Description Current timeframe 1 minute 2 minutes 3 minutes 4 minutes 5 minutes 6 minutes 10 minutes 12 minutes 15 minutes 20 minutes 30 minutes 1 hour 2 hours 3 hours 4 hours 6 hours 8 hours 12 hours 1 day 1 week 1 month
187
188
Chart Properties
Identifiers of ENUM_CHART_PROPERTY enumerations are used as parameters of functions for working with charts. The abbreviation of r/o in the "Type property" column means that this property is readonly and can not be changed. When accessing certain properties, it's necessary to specify an additional parameter-modifier (modifier), which serves to indicate the number of chart subwindows. 0 means the main window. For functions ChartSetInteger() and ChartGetInteger() ENUM_CHART_PROPERTY_INTEGER ID CHART_BRING_TO_TOP Description Show chart on top of other charts Chart type (candlesticks, bars or line) Price chart in the background Mode of price chart indent from the right border Mode of automatic moving to the right border of the chart Scale Fixed scale mode Scale 1:1 mode Scale to be specified in points per bar Show OHLC values in the upper left corner Display Bid values as horizontal line in a chart Display Ask values as horizontal line in a chart Display Last values as horizontal line in a chart a Property Type bool
CHART_MODE
enum
ENUM_CHART_MODE
CHART_FOREGROUND CHART_SHIFT
bool bool
CHART_AUTOSCROLL
bool
from 0 to 5
CHART_SHOW_OHLC
bool
CHART_SHOW_BID_LINE
bool
CHART_SHOW_ASK_LINE
bool
CHART_SHOW_LAST_LINE
bool
CHART_SHOW_PERIOD_SEP
Display vertical separators between adjacent periods Display grid in the chart Display volume in the chart
bool
CHART_SHOW_GRID CHART_SHOW_VOLUMES
CHART_SHOW_OBJECT_DESCR
Pop-up
descriptions
189
graphical objects CHART_VISIBLE_BARS The number of bars on the chart that can be displayed The total number of chart windows, including indicator subwindows Visibility of subwindows int r/o
CHART_WINDOWS_TOTAL
int r/o
CHART_WINDOW_IS_VISIBLE
CHART_WINDOW_HANDLE CHART_FIRST_VISIBLE_BAR
Chart window handle (HWND) Number of the first visible bar in the chart. Indexing of bars is the same as for timeseries. Chart width in bars Chart width in pixels Chart height in pixels
int r/o int r/o int r/o modifier subwindow number color color
CHART_COLOR_BACKGROUND CHART_COLOR_FOREGROUND
Chart background color Color of axes, scales and OHLC line Grid color Color of volumes and position opening levels Color for the up bar, shadows and body borders of bull candlesticks Color for the down bar, shadows and body borders of bear candlesticks Line chart color and color of Japanese candlesticks Dodge Body color of a bull candlestick Body color of a bear candlestick Bid price level color Ask price level color Line color of the last executed deal price (Last) Color of stop order levels (Stop Loss and Take Profit)
CHART_COLOR_GRID CHART_COLOR_VOLUME
color color
CHART_COLOR_CHART_UP
color
CHART_COLOR_CHART_DOWN
color
CHART_COLOR_CHART_LINE
color
CHART_COLOR_STOP_LEVEL
color
190
CHART_SHOW_TRADE_LEVELS
Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders)
bool
For functions ChartSetDouble() and ChartGetDouble() ENUM_CHART_PROPERTY_DOUBLE ID CHART_SHIFT_SIZE Description The size of the zero bar indent from the right border in percents Fixed chart maximum Fixed chart minimum Scale in points per bar Chart maximum Property Type double (from percents) 10 to 50
double double double double r/o modifier subwindow number double r/o modifier subwindow number -
CHART_PRICE_MAX
Chart minimum
191
192
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 CHART_BEGIN CHART_CURRENT_POS CHART_END Example:
long handle=ChartOpen("EURUSD",PERIOD_H12); if(handle!=0) { ChartSetInteger(handle,CHART_AUTOSCROLL,false); ChartSetInteger(handle,CHART_SHIFT,true); ChartSetInteger(handle,CHART_MODE,CHART_LINE); ResetLastError(); bool res=ChartNavigate(handle,CHART_END,150); if(!res) Print("Navigate failed. Error = ",GetLastError()); ChartRedraw(); }
Description Chart beginning (the oldest prices) Current position Chart end (the latest prices)
193
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 CHART_BARS CHART_CANDLES CHART_LINE Description Display as a sequence of bars Display as Japanese candlesticks 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.
194
195
Object Constants
There are 39 graphical objects that can be created and displayed in the price chart. All constants for working with objects are divided into 9 groups: Object types 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 an indication of the angle of the schedule, which is positioned on the object; Visibility of objects setting timeframes in which an object is visible; Levels of Elliott Waves wave gradation markings; 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.
196
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 OBJ_VLINE OBJ_HLINE OBJ_TREND OBJ_TRENDBYANGLE OBJ_CHANNEL OBJ_STDDEVCHANNEL OBJ_REGRESSION OBJ_PITCHFORK OBJ_GANNLINE OBJ_GANNFAN OBJ_GANNGRID OBJ_FIBO OBJ_FIBOTIMES OBJ_FIBOFAN OBJ_FIBOARC OBJ_FIBOCHANNEL OBJ_EXPANSION OBJ_ELLIOTWAVE5 OBJ_ELLIOTWAVE3 OBJ_RECTANGLE OBJ_TRIANGLE OBJ_ELLIPSE OBJ_CYCLES OBJ_ARROW_THUMB_UP OBJ_ARROW_THUMB_DOWN OBJ_ARROW_UP Description Vertical Line Horizontal Line Trend Line Trend Line By Angle Equidistant Channel Standard Deviation Channel Linear Regression Channel Andrews Pitchfork Gann Line Gann Fan Gann Grid Fibonacci Retracement Fibonacci Time Zones Fibonacci Fan Fibonacci Arcs Fibonacci Channel Fibonacci Expansion Elliott Motive Wave Elliott Correction Wave Rectangle Triangle Ellipse Cycle Lines Thumbs Up Thumbs Down Arrow Up
197
Standard Constants, Enumerations and Structures OBJ_ARROW_DOWN OBJ_ARROW_STOP OBJ_ARROW_CHECK OBJ_ARROW_LEFT_PRICE OBJ_ARROW_RIGHT_PRICE OBJ_ARROW_BUY OBJ_ARROW_SELL OBJ_ARROW OBJ_TEXT OBJ_LABEL OBJ_BUTTON OBJ_CHART OBJ_BITMAP OBJ_BITMAP_LABEL OBJ_EDIT OBJ_ARROWED_LINE OBJ_EVENT Arrow Down Stop Sign Check Sign Left Price Label Right Price Label Buy Sign Sell Sign Arrow Text Label Button Chart Bitmap Bitmap Label Edit Arrowed Line The "Event" object corresponding to an event in the economic calendar The "Rectangle label" object for creating and designing the custom graphical interface.
OBJ_RECTANGLE_LABEL
198
Object Properties
Every graphical object in a price chart has a certain set of properties. Values of object properties are wet up and received by corresponding functions for working with graphical objects. For each object type there is its own set of properties. Here al possible values from the ENUM_OBJECT_PROPERTY enumeration family are listed. Some properties require clarification, such as the level number for the Fibonacci extension object. In such cases it is necessary to specify the value of the modifier parameter in the functions of ObjectSet...() and ObjectGet...(). For functions ObjectSetInteger() and ObjectGetInteger() ENUM_OBJECT_PROPERTY_INTEGER Identifier OBJPROP_COLOR OBJPROP_STYLE OBJPROP_WIDTH OBJPROP_BACK OBJPROP_SELECTED OBJPROP_READONLY Description Color Style Line thickness Object in the background Object is selected Ability to edit text in the Edit object Object type Time coordinate Property Type color ENUM_LINE_STYLE int bool bool bool
OBJPROP_TYPE OBJPROP_TIME
ENUM_OBJECT datetime modifier=number of anchor point bool datetime int color modifier=level number ENUM_LINE_STYLE modifier=level number int int bool bool bool Arrow char modifier=level number r/o
Object availability Time of object creation Number of levels Color of the line-level Style of the line-level
Thickness of the line-level Font size Ray goes to the left Ray goes to the right Ellipse Arrow code for the object Visibility of timeframes an
OBJPROP_TIMEFRAMES
object
at
199
Standard Constants, Enumerations and Structures OBJPROP_ANCHOR Location of the anchor point of a graphical object ENUM_ARROW_ANCHOR (for OBJ_ARROW), ENUM_ANCHORPOINT (for OBJ_LABEL and OBJ_TEXT) int
OBJPROP_XDISTANCE
The distance in pixels along the X axis from the binding corner The distance in pixels along the Y axis from the binding corner Trend of the Gann object Level of Marking the Elliott Wave
OBJPROP_YDISTANCE
int
OBJPROP_DIRECTION OBJPROP_DEGREE
ENUM_GANN_DIRECTION ENUM_ELLIOT_WAVE_DEGREE
OBJPROP_DRAWLINES
Displaying lines for marking the Elliott Wave Button state depressed) (pressed /
bool
OBJPROP_STATE
bool
OBJPROP_XSIZE
The size of the Chart object along the X axis (width in pixels) The size of the Chart object along the Y axis (height in pixels) Timeframe object for the Chart
int
OBJPROP_YSIZE
int
OBJPROP_PERIOD
ENUM_TIMEFRAMES
OBJPROP_DATE_SCALE
Displaying the time scale for the Chart object Displaying the price scale for the Chart object The scale for the Chart object The background color for the Edit object The corner of the chart to link a graphical object Border type for the "Rectangle label" object
bool
OBJPROP_PRICE_SCALE
bool
OBJPROP_CHART_SCALE OBJPROP_BGCOLOR
OBJPROP_CORNER
ENUM_BASECORNER
OBJPROP_BORDER_TYPE
ENUM_BORDER_TYPE
For functions ObjectSetDouble() and ObjectGetDouble() ENUM_OBJECT_PROPERTY_DOUBLE Identifier Description Property Type
200
Standard Constants, Enumerations and Structures OBJPROP_PRICE Price coordinate double modifier=number of anchor point double double modifier=level number
OBJPROP_LEVELVALUE OBJPROP_SCALE
Level value Scale (properties of Gann objects and Fibonacci Arcs) Angle Deviation for the Deviation Channel Standard
OBJPROP_ANGLE OBJPROP_DEVIATION
double double
For functions ObjectSetString() and ObjectGetString() ENUM_OBJECT_PROPERTY_STRING Identifier OBJPROP_NAME OBJPROP_TEXT Description Object name Description of the object (the text contained in the object) Level description Font The name of Bitmap Label BMP-file for Property Type string string
string string
modifier=level number
OBJPROP_SYMBOL
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 BORDER_FLAT BORDER_RAISED BORDER_SUNKEN Example:
#define UP "\x0431" |
201
202
Description Anchor point at the upper left corner Anchor point to the left in the center Anchor point at the lower left corner Anchor point below in the center Anchor point at the lower right corner Anchor point to the right in the center Anchor point at the upper right corner Anchor point above in the center Anchor point strictly in the center of the object
203
Graphical objects Arrow (OBJ_ARROW) have only 2 ways of linking their coordinates. Identifiers are listed in ENUM_ARROW_ANCHOR. ENUM_ARROW_ANCHOR ID ANCHOR_TOP ANCHOR_BOTTOM Example:
void OnStart() { //--- Auxiliary arrays double Ups[],Downs[]; datetime Time[]; //--- Set the arrays as timeseries ArraySetAsSeries(Ups,true); ArraySetAsSeries(Downs,true); ArraySetAsSeries(Time,true); //--- Create handle of the Indicator Fractals int FractalsHandle=iFractals(NULL,0); Print("FractalsHandle = ",FractalsHandle); //--- Set Last error value to Zero ResetLastError(); //--- Try to copy the values of the indicator int copied=CopyBuffer(FractalsHandle,0,0,1000,Ups); if(copied<=0) { Print("Unable to copy the upper fractals. Error = ",GetLastError()); return; } ResetLastError(); //--- Try to copy the values of the indicator copied=CopyBuffer(FractalsHandle,1,0,1000,Downs); if(copied<=0) { Print("Unable to copy the bottom fractals. Error = ",GetLastError()); return; } ResetLastError(); //--- Copy timeseries containing the opening bars of the last 1000 ones
204
After the script execution the chart will look like in this figure.
205
206
CORNER_LEFT_LOWER
CORNER_RIGHT_LOWER
CORNER_RIGHT_UPPER
Example:
void CreateLabel(long int int int { //--ObjectCreate(chart_id,name,OBJ_LABEL,0,0,0); ResetLastError(); if(!ObjectSetInteger(chart_id,name,OBJPROP_CORNER,chart_corner)) Print("Unable to set the angle to bind the object ", chart_id, chart_corner, x_ord, y_ord)
207
208
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 OBJ_NO_PERIODS 0 Value Description The object is not drawn in all timeframes The object is drawn in 1minute chart The object is drawn in 2minute chart The object is drawn in 3minute chart The object is drawn in 4minute chart The object is drawn in 5minute chart The object is drawn in 6minute chart The object is drawn in 10minute chart The object is drawn in 12minute chart The object is drawn in 15minute chart The object is drawn in 20minute chart The object is drawn in 30minute chart The object is drawn in 1-hour chart The object is drawn in 2-hour chart The object is drawn in 3-hour chart The object is drawn in 4-hour chart The object is drawn in 6-hour chart
OBJ_PERIOD_M1
0x00000001
OBJ_PERIOD_M2
0x00000002
OBJ_PERIOD_M3
0x00000004
OBJ_PERIOD_M4
0x00000008
OBJ_PERIOD_M5
0x00000010
OBJ_PERIOD_M6
0x00000020
OBJ_PERIOD_M10
0x00000040
OBJ_PERIOD_M12
0x00000080
OBJ_PERIOD_M15
0x00000100
OBJ_PERIOD_M20
0x00000200
OBJ_PERIOD_M30
0x00000400
OBJ_PERIOD_H1
0x00000800
OBJ_PERIOD_H2
0x00001000
OBJ_PERIOD_H3
0x00002000
OBJ_PERIOD_H4
0x00004000
OBJ_PERIOD_H6
0x00008000
209
Standard Constants, Enumerations and Structures OBJ_PERIOD_H8 0x00010000 The object is drawn in 8-hour chart The object is drawn in 12-hour chart The object is drawn in day charts The object is drawn in week charts The object is drawn in month charts The object is drawn in all timeframes
OBJ_PERIOD_H12
0x00020000
OBJ_PERIOD_D1
0x00040000
OBJ_PERIOD_W1
0x00080000
OBJ_PERIOD_MN1
0x00100000
OBJ_ALL_PERIODS
0xffffffff
Visibility flags can be combined using the symbol "| for example, the combination of flags ", OBJ_PERIOD_M10| OBJ_PERIOD_H4 means that the object will be visible on the 10-minute and 4-hour timeframes. Example:
void OnStart() { //--string highlevel="PreviousDayHigh"; string lowlevel="PreviousDayLow"; double prevHigh; double prevLow; double highs[],lows[]; //--- 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 // The previous day High // The previous day Low // Arrays for High and Low
210
211
Description Grand Supercycle Supercycle Cycle Primary Intermediate Minor Minute Minuette Subminuette
212
Gann Objects
For Gann Fan (OBJ_GANNFAN) and Gann Grid (OBJ_GANNGRID) ENUM_GANN_DIRECTION can be specified, which will set the trend direction. ENUM_GANN_DIRECTION ID GANN_UP_TREND GANN_DOWN_TREND Description Line corresponding to the uptrend line Line corresponding to the downward trend of two values of
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.
213
Time[center_bar/2] = "+(string)Time[c
214
Web Colors
The following color constants are defined for the color type:
Black DarkGreen DarkSlateG ray M idnightBl ue DarkSlateB lue FireBrick Olive Green Teal Navy Purple
M aroon
Indigo
DarkBlue
SaddleBro wn Brown
OliveDrab
SeaGreen
Sienna
DimGray
Chocolate
SteelBlue
LawnGree n Gold
YellowGre en Lime
LimeGreen
OrangeRed
Yellow
SpringGree n Peru
Aqua
Blue
M agenta
Red
SlateGray
BlueViolet
DeepPink
Turquoise
RoyalBlue
SlateBlue
DarkKhaki
Tomato
RosyBrown
Orchid
SandyBrow n LightCoral
Tan
HotPink
Violet
LightSalmo n LightBlue
Khaki
Silver
LightSkyBl ue LightGray
PaleGreen
Thistle
M occasin
LightPink
Bisque
Beige
Cornsilk
LightYello w Ivory
M istyRose
Seashell
Honeydew
AliceBlue
Lavender Blush
M intCream
Snow
Color can be set to an object using the ObjectSetInteger() function. For setting color to custom indicators the PlotIndexSetInteger() function is used. For getting color values there are similar functions ObjectGetInteger() and PlotIndexGetInteger(). Example:
215
216
Wingdings
Characters of Wingdings used with the OBJ_ARROW object:
217
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.
218
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 PRICE_CLOSE PRICE_OPEN PRICE_HIGH PRICE_LOW PRICE_MEDIAN PRICE_TYPICAL PRICE_WEIGHTED Description Close price Open price The maximum price for the period The minimum price for the period Median price, (high + low)/2 Typical price, (high + low + close)/3 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 VOLUME_TICK VOLUME_REAL Description Tick volume 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 STO_LOWHIGH STO_CLOSECLOSE Description Calculation is based on Low/High prices 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 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.
219
input ENUM_MA_METHOD meth=MODE_SMMA; // Method of smoothing //---- plot RSI #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //---- plot RSI_Smoothed #property indicator_label2 #property indicator_type2 #property indicator_color2 #property indicator_style2 #property indicator_width2 //--- indicator buffers double double int RSIBuffer[]; RSIhandle; // Here we store the values of RSI // Handle to the RSI indicator | RSI_SmoothedBuffer[]; // Here will be smoothed values of RSI "RSI_Smoothed" DRAW_LINE Navy STYLE_SOLID 1 "RSI" DRAW_LINE Red STYLE_SOLID 1
//+------------------------------------------------------------------+ //| 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[] ) { | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
220
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(),", 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(),", return(0); } //--- return value of prev_calculated for next call return(rates_total); } copied =",copied); copied =",copied);
221
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 MODE_SMA MODE_EMA MODE_SMMA MODE_LWMA Example:
double ExtJaws[]; double ExtTeeth[]; double ExtLips[]; //---- handles for moving averages int int int ExtJawsHandle; ExtTeethHandle; ExtLipsHandle;
222
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 MAIN_LINE SIGNAL_LINE 0 1 Value Description Main line Signal line
Identifiers of indicator lines permissible when copying values of ADX() and ADXW(). Constant MAIN_LINE PLUSDI_LINE MINUSDI_LINE 0 1 2 Value Description Main line Line +DI Line DI
Identifiers of indicator lines permissible when copying values of iBands(). Constant BASE_LINE UPPER_BAND LOWER_BAND 0 1 2 Value Description Main line Upper limit Lower limit
Identifiers of indicator lines permissible when copying values of iEnvelopes() and iFractals(). Constant UPPER_LINE LOWER_LINE 0 1 Value Description Upper line Bottom line
Identifiers of indicator lines permissible when copying values of iGator() Constant UPPER_HISTOGRAM LOWER_HISTOGRAM 0 2 Value Description Upper histogram Bottom histogram
Identifiers of indicator lines permissible when copying values of iAlligator(). Constant Value Description
223
Standard Constants, Enumerations and Structures GATORJAW_LINE GATORTEETH_LINE GATORLIPS_LINE 0 1 2 Jaw line Teeth line Lips line
Identifiers of indicator lines permissible when copying values of iIchimoku(). Constant TENKANSEN_LINE KIJUNSEN_LINE SENKOUSPANA_LINE SENKOUSPANB_LINE CHINKOUSPAN_LINE 0 1 2 3 4 Value Description Tenkan-sen line Kijun-sen line Senkou Span A line Senkou Span B line Chinkou Span line
224
Drawing Styles
When creating a custom indicator, you can specify one of 18 types of graphical plotting (as displayed in the main chart window or a chart subwindow), whose values are specified in the ENUM_DRAW_TYPE enumeration. In one custom indicator, it is permissible to use any indicator building/drawing types. Each construction type requires specification of one to five global arrays for storing data necessary for drawing. These data arrays must be bound with indicator buffers using the SetIndexBuffer() function. The type of data from ENUM_INDEXBUFFER_TYPE should be specified for each buffer. Depending on the drawing style, you may need one to four value buffers (marked as INDICATOR_DATA). If a style admits dynamic alternation of colors (all styles contain COLOR in their names), then you'll need one more buffer of color (indicated type INDICATOR_COLOR_INDEX). The color buffer are always bound after value buffers corresponding to the style. ENUM_DRAW_TYPE ID DRAW_NONE DRAW_LINE DRAW_SECTION DRAW_HISTOGRAM Description Not drawn Line Section Histogram from zero line the Data buffers 1 1 1 1 Color buffers 0 0 0 0
DRAW_HISTOGRAM2
Histogram of the two indicator buffers Drawing arrows Style Zigzag allows vertical section on the bar Color fill between the two levels Display as a sequence of bars Display as a sequence of candlesticks Multicolored line Multicolored section
DRAW_ARROW DRAW_ZIGZAG
1 2
0 0
DRAW_FILLING
DRAW_BARS
DRAW_CANDLES
1 1
1 1
Multicolored histogram from the zero line Multicolored histogram of the two indicator
225
Standard Constants, Enumerations and Structures buffers DRAW_COLOR_ARRO W DRAW_COLOR_ZIGZAG DRAW_COLOR_BARS DRAW_COLOR_CANDL ES Drawing arrows multicolored 1 1
2 4 4
1 1 1
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 PLOT_ARROW Description Arrow code DRAW_ARROW for style Property type uchar
PLOT_ARROW_SHIFT
Vertical shift of arrows for style DRAW_ARROW Number of initial bars without drawing and values in the DataWindow Type of graphical construction Sign of display of construction values in the DataWindow Shift of indicator plotting along the time axis in bars Drawing line style The thickness of the drawing line The number of colors The index of a buffer containing the drawing color
int
PLOT_DRAW_BEGIN
int
PLOT_DRAW_TYPE PLOT_SHOW_DATA
ENUM_DRAW_TYPE bool
PLOT_SHIFT
int
PLOT_LINE_STYLE PLOT_LINE_WIDTH
ENUM_LINE_STYLE int
PLOT_COLOR_INDEXES PLOT_LINE_COLOR
For the function PlotIndexSetDouble() ENUM_PLOT_PROPERTY_DOUBLE ID PLOT_EMPTY_VALUE Description An empty value for plotting, Property type double
226
Standard Constants, Enumerations and Structures for which there is no drawing For the function PlotIndexSetString() ENUM_PLOT_PROPERTY_STRING ID PLOT_LABEL Description The name of the indicator graphical series to display in the DataWindow Property type string
5 styles can be used for drawing lines in custom indicators. They are valid only for the line thickness 0 or 1. ENUM_LINE_STYLE ID STYLE_SOLID STYLE_DASH STYLE_DOT STYLE_DASHDOT STYLE_DASHDOTDOT Description Solid line Broken line Dotted line Dash-dot line 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 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,Red); //+------------------------------------------------------------------+ 1
227
228
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 INDICATOR_DIGITS Description Accuracy of drawing indicator values Number of levels indicator window Color of the level line in of Property type int
INDICATOR_LEVELS
the
int
INDICATOR_LEVELCOLOR
modifier =
INDICATOR_LEVELSTYLE
INDICATOR_LEVELWIDTH
ENUM_CUSTOMIND_PROPERTY_DOUBLE ID INDICATOR_MINIMUM Description Minimum window Maximum window Level value of the indicator Property type double
INDICATOR_MAXIMUM
of
the
indicator
double
INDICATOR_LEVELVALUE
modifier =
ENUM_CUSTOMIND_PROPERTY_STRING
229
Standard Constants, Enumerations and Structures ID INDICATOR_SHORTNAME INDICATOR_LEVELTEXT Description Short indicator name Level description Property type string string level number modifier =
Examples:
//--- indicator settings #property indicator_separate_window #property indicator_buffers 4 #property indicator_plots #property indicator_type1 #property indicator_type2 #property indicator_color1 #property indicator_color2 //--- 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); //--- sets first bar from what 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); | //+------------------------------------------------------------------+ 2 DRAW_LINE DRAW_LINE LightSeaGreen Red
230
231
232
Standard Constants, Enumerations and Structures IND_MA IND_MACD IND_MFI IND_MOMENTUM IND_OBV IND_OSMA IND_RSI IND_RVI IND_SAR IND_STDDEV IND_STOCHASTIC IND_TEMA IND_TRIX IND_VIDYA IND_VOLUMES IND_WPR Moving Average MACD Money Flow Index Momentum On Balance Volume OsMA Relative Strength Index Relative Vigor Index Parabolic SAR Standard Deviation Stochastic Oscillator Triple Exponential Moving Average Triple Exponential Moving Averages Oscillator Variable Index Dynamic Average Volumes Williams' Percent Range
233
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.
234
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;
235
Connection to a trade server Permission to use DLL Permission to trade Permission to send e-mails using SMTP-server and login, specified in the terminal settings Permission to send reports using FTP-server and login, specified in the terminal settings The maximal bars count on the chart Number of the code page of the language installed in the client terminal
TERMINAL_FTP_ENABLED
bool
TERMINAL_MAXBARS
int
TERMINAL_LANGUAGE
int
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 TERMINAL_COMPANY TERMINAL_NAME TERMINAL_PATH Description Company name Terminal name Folder from which the terminal is started Folder in which terminal data are stored Common path for all of the terminals installed on a computer Type string string string
TERMINAL_DATA_PATH
string
TERMINAL_COMMONDATA_PAT H
string
236
Standard Constants, Enumerations and Structures 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. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00" |
//+------------------------------------------------------------------+ //| Script program start function void OnStart() { //--Print("TERMINAL_PATH = ",TerminalInfoString(TERMINAL_PATH)); Print("TERMINAL_DATA_PATH = ",TerminalInfoString(TERMINAL_DATA_PATH)); Print("TERMINAL_COMMONDATA_PATH = ",TerminalInfoString(TERMINAL_COMMONDATA_PATH)); } //+------------------------------------------------------------------+
As result of the script execution in the Experts Journal you will see a messages, like the following:
237
MQL5_TRADE_ALLOWED
bool
MQL5_DEBUGGING
bool
MQL5_TESTING
bool
MQL5_OPTIMIZATION
bool
MQL5_VISUAL_MODE
bool
For function MQL5InfoString ENUM_MQL5_INFO_STRING Identifier MQL5_PROGRAM_NAME Description Name of the mql5-program executed Path for the given executed program Type string
MQL5_PROGRAM_PATH
string
Information about the type of the running program, values of ENUM_PROGRAM_TYPE are used. ENUM_PROGRAM_TYPE Identifier PROGRAM_SCRIPT PROGRAM_EXPERT PROGRAM_INDICATOR Description Script Expert Indicator
238
239
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 SYMBOL_SELECT Description Symbol is selected in Market Watch Volume of the last deal Maximal day volume Minimal day volume Volume for current Bid Volume for current Ask Time of the last quote Digits after a decimal point Indication of a floating spread Spread value in points Maximal number of requests shown in Depth of Market. For symbols that have no queue of requests, the value is equal to zero. Contract price calculation mode Order execution type Date of the symbol trade beginning (usually used for futures) Date of the symbol trade end (usually used for futures) Minimal indention in points from the current close price to place Stop orders Distance to freeze operations in points Deal execution mode trade Type bool
SYMBOL_VOLUME SYMBOL_VOLUMEHIGH SYMBOL_VOLUMELOW SYMBOL_VOLUMEBID SYMBOL_VOLUMEASK SYMBOL_TIME SYMBOL_DIGITS SYMBOL_SPREAD_FLOAT SYMBOL_SPREAD SYMBOL_TICKS_BOOKDEPTH
long long long long long datetime int bool int int
SYMBOL_EXPIRATION_TIME
datetime
SYMBOL_TRADE_STOPS_LEVEL
int
SYMBOL_TRADE_FREEZE_LEVEL
int
SYMBOL_TRADE_EXEMODE
ENUM_SYMBOL_TRADE_EXECUT
240
Standard Constants, Enumerations and Structures ION SYMBOL_SWAP_MODE SYMBOL_SWAP_ROLLOVER3DA YS SYMBOL_EXPIRATION_MODE Swap calculation model Weekday to charge 3 days swap rollover Flags of allowed expiration modes order ENUM_SYMBOL_SWAP_MODE ENUM_DAY_OF_WEEK
int int
SYMBOL_FILLING_MODE
For function SymbolInfoDouble() ENUM_SYMBOL_INFO_DOUBLE Identifier SYMBOL_BID SYMBOL_BIDHIGH SYMBOL_BIDLOW SYMBOL_ASK SYMBOL_ASKHIGH SYMBOL_ASKLOW SYMBOL_LAST SYMBOL_LASTHIGH SYMBOL_LASTLOW SYMBOL_POINT SYMBOL_TRADE_TICK_VALUE Description Bid - best sell offer Maximal Bid of the day Minimal Bid of the day Ask - best buy offer Maximal Ask of the day Minimal Ask of the day Price of the last deal Maximal Last of the day Minimal Last of the day Symbol point value Value of SYMBOL_TRADE_TICK_VALUE_P ROFIT Calculated tick price for a profitable position Calculated tick price for a losing position Minimal price change Trade contract size Type double double double double double double double double double double double
double
double
double double
Minimal volume for a deal Maximal volume for a deal Minimal volume change step for deal execution
241
Standard Constants, Enumerations and Structures SYMBOL_VOLUME_LIMIT Maximum allowed total volume of the open position and pending orders (regardless of direction) for one symbol Long swap value Short swap value 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. The maintenance margin. If its 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 maintenance margin is equal to 0, the initial margin is used. Rate of margin charging on long positions Rate of margin charging on short positions Rate of margin charging on Limit orders Rate of margin charging on Stop orders Rate of margin charging on Stop Limit orders double
SYMBOL_MARGIN_MAINTENANC E
double
SYMBOL_MARGIN_LONG
double
SYMBOL_MARGIN_SHORT
double
SYMBOL_MARGIN_LIMIT
double
SYMBOL_MARGIN_STOP
double
SYMBOL_MARGIN_STOPLIMIT
double
For function SymbolInfoString() ENUM_SYMBOL_INFO_STRING Identifier SYMBOL_CURRENCY_BASE SYMBOL_CURRENCY_PROFIT SYMBOL_CURRENCY_MARGIN SYMBOL_BANK SYMBOL_DESCRIPTION Description Basic currency of a symbol Profit currency Margin currency Feeder of the current quote Symbol description Type string string string string string
242
Standard Constants, Enumerations and Structures 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_SRECIFIED. In order to check whether a certain mode is allowed for the symbol, the result of the logical AND (&) should be compared to the mode flag. If flag SYMBOL_EXPIRATION_SRECIFIED is specified for a symbol, then while sending a pending order, you may specify the moment this pending order is valid till. Identifier SYMBOL_EXPIRATION_GTC Value 1 Description The order is valid during the unlimited time period, until it is explicitly canceled The order is valid till the end of the day The expiration time specified in the order is
SYMBOL_EXPIRATION_DAY
SYMBOL_EXPIRATION_SRECIFIE D Example:
//+------------------------------------------------------------------+ //| Checks if the specified expiration mode is allowed bool IsExpirationTypeAllowed(string symbol,int exp_type) { //--- Obtain the value of the property that describes allowed expiration modes int expiration=(int)SymbolInfoInteger(symbol,SYMBOL_EXPIRATION_MODE); //--- Return true, if mode exp_type is allowed return((expiration&exp_type)==exp_type); } | //+------------------------------------------------------------------+
When sending an order, you can specify the filling policy for the volume set in the order. Allowed order filling modes for each symbol are specified in the table. You can set several modes for one symbol by combining flags. The flags can be combined by the operation of the logical OR (| for example, ), SYMBOL_FILLING_ALL_OR_NONE| SYMBOL_CANCEL_REMAIND. In order to check whether a certain mode is allowed for the symbol, the result of the logical AND (&) should be compared to the mode flag. Identifier SYMBOL_FILLING_ALL_OR_NON E Value 1 Description "All or none". If the volume specified in the order with the specified price cannot be fully filled, the order is canceled and the deal is not conducted If only part of the specified
SYMBOL_CANCEL_REMAIND
243
Standard Constants, Enumerations and Structures volume can be filled, the deal for the available volume will be executed. The order remainder is canceled, and the new order is not placed SYMBOL_RETURN_REMAIND 4 A deal is executed for the available volume. A new order at the same price is set for the remainder
Example:
//+------------------------------------------------------------------+ //| Checks if the specified expiration mode is allowed | //+------------------------------------------------------------------+ bool IsFiilingTypeAllowed(string symbol,int fill_type) { //--- Obtain the value of the property that describes allowed expiration modes int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE); //--- Return true, if mode fill_type is allowed return((filling & fill_type)==fill_type); }
The ENUM_SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin requirements for a symbol are calculated. ENUM_SYMBOL_CALC_MODE Identifier SYMBOL_CALC_MODE_FOREX Description Forex mode - calculation of profit and margin for Forex Formula Margin: Lots*Contract_Size/ Leverage Profit: (close_priceopen_price)*Contract_Size*Lots Margin: Lots *InitialMargin*Percentage/100 Profit: (close_priceopen_price)*TickPrice/ TickSize*Lots Margin: Lots *ContractSize*MarketPrice*Perc entage/100 Profit: (close_priceopen_price)*Contract_Size*Lots Margin: (Lots*ContractSize*MarketPrice )*TickPrice/TickSize Profit: (close_priceopen_price)*Contract_Size*Lots
SYMBOL_CALC_MODE_FUTURE S
SYMBOL_CALC_MODE_CFD
SYMBOL_CALC_MODE_CFDINDE X
CFD index mode - calculation of margin and profit for CFD by indexes
244
Standard Constants, Enumerations and Structures SYMBOL_CALC_MODE_CFDLEVE RAGE CFD Leverage mode calculation of margin and profit for CFD at leverage trading Margin: (Lots*ContractSize*MarketPrice *Percentage)/Leverage Profit: (close_priceopen_price)*Contract_Size*Lots
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 SYMBOL_TRADE_MODE_DISABLED SYMBOL_TRADE_MODE_LONGONLY SYMBOL_TRADE_MODE_SHORTONLY SYMBOL_TRADE_MODE_CLOSEONLY SYMBOL_TRADE_MODE_FULL Description Trade is disabled for the symbol Allowed only long positions Allowed only short positions Allowed only position close operations No trade restrictions
for
certain
symbol
are
defined
in
enumeration
at
position
transfer
are
specified
in
enumeration
Description Swap mode disabled (no swaps) Swaps in points Swaps in money, its value is specified in the symbol properties in the deposit currency Swaps in yearly percents (bank mode - 360 days
SYMBOL_SWAP_MODE_BY_INTEREST
245
Standard Constants, Enumerations and Structures in a year) SYMBOL_SWAP_MODE_BY_MARGIN_CURRENCY Swaps in money, its value is specified in the symbol properties in the margin currency
Values of the ENUM_DAY_OF_WEEK enumeration are used for specifying weekdays. ENUM_DAY_OF_WEEK Identifier SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY Description Sunday Monday Tuesday Wednesday Thursday Friday Saturday
246
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 ACCOUNT_LOGIN ACCOUNT_TRADE_MODE ACCOUNT_LEVERAGE ACCOUNT_LIMIT_ORDERS Description Account number Account trade mode Account leverage Maximum allowed number of active pending orders Mode for setting the minimal allowed margin Allowed trade for the current account Allowed trade for an Expert Advisor Type long ENUM_ACCOUNT_TRADE_MODE long int
ACCOUNT_MARGIN_SO_MODE
ENUM_ACCOUNT_STOPOUT_MO DE bool
ACCOUNT_TRADE_ALLOWED
ACCOUNT_TRADE_EXPERT
bool
For the function AccountInfoDouble() ENUM_ACCOUNT_INFO_DOUBLE Identifier ACCOUNT_BALANCE Description Account balance in the deposit currency Account credit in the deposit currency Current profit of an account in the deposit currency Account equity in the deposit currency Account margin used in the deposit currency Free margin of an account in the deposit currency Account percents margin level in Type double
ACCOUNT_CREDIT
double
ACCOUNT_PROFIT
double
ACCOUNT_EQUITY
double
ACCOUNT_MARGIN
double
ACCOUNT_FREEMARGIN
double
ACCOUNT_MARGIN_LEVEL
double
ACCOUNT_MARGIN_SO_CALL
double
247
Standard Constants, Enumerations and Structures the set ACCOUNT_MARGIN_SO_MODE is expressed in percents or in the deposit currency 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
For function AccountInfoString() ENUM_ACCOUNT_INFO_STRING Identifier ACCOUNT_NAME ACCOUNT_SERVER ACCOUNT_CURRENCY ACCOUNT_COMPANY Description Client name Trade server name Account currency Name of a company that serves the account Type string string string string
ENUM_ACCOUNT_TRADE_MODE Identifier ACCOUNT_TRADE_MODE_DEMO ACCOUNT_TRADE_MODE_CONTEST ACCOUNT_TRADE_MODE_REAL ENUM_ACCOUNT_STOPOUT_MODE Identifier ACCOUNT_STOPOUT_MODE_PERCENT ACCOUNT_STOPOUT_MODE_MONEY Description Account stop out mode in percents Account stop out mode in money Description Demo account Contest account Real account
248
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 orders in DOM separation of orders according to the direction of a requested operation.
249
SERIES_FIRSTDATE
datetime
SERIES_LASTBAR_DATE
datetime
SERIES_SERVER_FIRSTDATE
datetime
SERIES_TERMINAL_FIRSTDATE
datetime
SERIES_SYNCRONIZED
bool
250
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 ORDER_TIME_SETUP ORDER_TYPE ORDER_STATE ORDER_TIME_EXPIRATION ORDER_TIME_DONE Description Order setup time Order type Order state Order expiration time Order execution or cancellation time Order filling type Order lifetime ID of an Expert Advisor that has placed the order (designed to ensure that each Expert Advisor places its own unique number) 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. Type datetime ENUM_ORDER_TYPE ENUM_ORDER_STATE datetime datetime
ORDER_POSITION_ID
long
For functions OrderGetDouble() and HistoryOrderGetDouble() ENUM_ORDER_PROPERTY_DOUBLE Identifier ORDER_VOLUME_INITIAL ORDER_VOLUME_CURRENT ORDER_PRICE_OPEN ORDER_SL Description Order initial volume Order current volume Price specified in the order Stop Loss value Type double double double double
251
Standard Constants, Enumerations and Structures ORDER_TP ORDER_PRICE_CURRENT Take Profit value The current price of the order symbol The Limit order price for the StopLimit order double double
ORDER_PRICE_STOPLIMIT
double
For functions OrderGetString() and HistoryOrderGetString() ENUM_ORDER_PROPERTY_STRING Identifier ORDER_SYMBOL ORDER_COMMENT Description Symbol of the order Order comment Type string 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 ORDER_TYPE_BUY ORDER_TYPE_SELL ORDER_TYPE_BUY_LIMIT ORDER_TYPE_SELL_LIMIT ORDER_TYPE_BUY_STOP ORDER_TYPE_SELL_STOP ORDER_TYPE_BUY_STOP_LIMIT Description Market Buy order Market Sell order Buy Limit pending order Sell Limit pending order Buy Stop pending order Sell Stop pending order Upon reaching the order price, a pending Buy Limit order is places at the StopLimit price Upon reaching the order price, a pending Sell Limit order is places at the StopLimit price
ORDER_TYPE_SELL_STOP_LIMIT
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 ORDER_STATE_STARTED Description Order checked, but not yet accepted by broker
252
Standard Constants, Enumerations and Structures ORDER_STATE_PLACED ORDER_STATE_CANCELED ORDER_STATE_PARTIAL ORDER_STATE_FILLED ORDER_STATE_REJECTED ORDER_STATE_EXPIRED Order accepted Order canceled by client Order partially executed Order fully executed Order rejected Order expired
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_AON Description The deal can be executed exclusively with a specified volume at the equal or better price than the order specified price. If there is no sufficient volume of offers on the order symbol, the order will not be executed. An agreement to execute the deal with maximal market volume at the equal or better price than the order specified price. In this case an additional order for volume unfilled will not be placed. An agreement to execute the deal with maximal market volume at the equal or better price than the order specified price. In this case an additional order for volume unfilled will be placed.
ORDER_FILLING_CANCEL
ORDER_FILLING_RETURN
The order validity period can be set in the type_time field of the special structure MqlTradeRequest when sending a trade request using the OrderSend() function. Values of the ENUM_ORDER_TYPE_TIME enumeration are allowed. To obtain the value of this property use the function OrderGetInteger() or HistoryOrderGetInteger() with the ORDER_TYPE_TIME modifier. ENUM_ORDER_TYPE_TIME Identifier ORDER_TIME_GTC ORDER_TIME_DAY Description Good till cancel order Good till current trade day order
253
Standard Constants, Enumerations and Structures ORDER_TIME_SPECIFIED Good till expired order
254
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 POSITION_TIME POSITION_TYPE POSITION_MAGIC Description Position open time Position type Position magic number (see ORDER_MAGIC) Position identifier is a unique number that is assigned to every newly opened position and doesn't change during the entire lifetime of the position. Position turnover doesn't change its identifier. Type datetime ENUM_POSITION_TYPE long
POSITION_IDENTIFIER
long
For the function PositionGetDouble() ENUM_POSITION_PROPERTY_DOUBLE Identifier POSITION_VOLUME POSITION_PRICE_OPEN POSITION_SL Description Position volume Position open price Stop Loss position level of opened Type double double double
POSITION_TP
Take Profit level of opened position Current price of the position symbol Commission Cumulative swap Current profit
double
POSITION_PRICE_CURRENT
double
255
Standard Constants, Enumerations and Structures ENUM_POSITION_PROPERTY_STRING Identifier POSITION_SYMBOL POSITION_COMMENT Description Symbol of the position Position comment Type string 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 POSITION_TYPE_BUY POSITION_TYPE_SELL Description Buy Sell
256
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 DEAL_ORDER DEAL_TIME DEAL_TYPE DEAL_ENTRY Description Deal order number Deal time Deal type Deal entry - entry in, entry out, reverse Deal magic number ORDER_MAGIC) (see Type long datetime ENUM_DEAL_TYPE ENUM_DEAL_ENTRY
DEAL_MAGIC
long
DEAL_POSITION_ID
Identifier of a position, in the opening, modification or change 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 DEAL_VOLUME DEAL_PRICE DEAL_COMMISSION DEAL_SWAP DEAL_PROFIT Description Deal volume Deal price Deal commission Cumulative swap on close Deal profit Type double double double double double
257
Standard Constants, Enumerations and Structures DEAL_SYMBOL DEAL_COMMENT Deal symbol Deal comment string 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 DEAL_TYPE_BUY DEAL_TYPE_SELL DEAL_TYPE_BALANCE DEAL_TYPE_CREDIT DEAL_TYPE_CHARGE DEAL_TYPE_CORRECTION Description Buy Sell Balance Credit Additional charge Correction
Deals differ not only in their types set in ENUM_DEAL_TYPE, but also in the way they change positions. This can be a simple position opening, or accumulation of a previously opened position (market entering), position closing by an opposite deal of a corresponding volume (market exiting), or position reversing, if the opposite-direction deal covers the volume of the previously opened position. All these situations are described by values from the ENUM_DEAL_ENTRY enumeration. In order to receive this information about a deal, use the HistoryDealGetInteger() function with the DEAL_ENTRY modifier. ENUM_DEAL_ENTRY Identifier DEAL_ENTRY_IN DEAL_ENTRY_OUT DEAL_ENTRY_INOUT DEAL_ENTRY_STATE Description Entry in Entry out Reverse Status record
258
TRADE_ACTION_PENDING
TRADE_ACTION_SLTP
TRADE_ACTION_MODIFY
TRADE_ACTION_REMOVE
259
260
Named Constants
All constants used in MQL5 can be divided into the following groups: Predefined macrosubstitutions 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.
261
Predefined Macrosubstitutions
To simplify the debugging process and obtain information about operation of a mql5-program, there are special macro constant, values of which are set at the moment of compilation. The easiest way to use these constants is outputting values by the Print() function, as it's shown in the example.
Constant __LINE__
Description String number in the source code, in which the macro is located Name of the current compiled file Name of the function, in whose body the macro is located Compiler build number
__FILE__ __FUNCTION__
__MQ5BUILD__ 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__," EventSetTimer(5); //--} //+------------------------------------------------------------------+ //| Expert deinitialization function void OnDeinit(const int reason) { //--- an example of information output at Expert Advisor deinitialization Print(" __FUNCTION__ = ",__FUNCTION__," //--} //+------------------------------------------------------------------+ //| Expert tick function void OnTick() { //--- information output at tick receipt Print(" __MQ5BUILD__ = ",__MQ5BUILD__," __FILE__ = ",__FILE__); | //+------------------------------------------------------------------+ __LINE__ = ",__LINE__); | //+------------------------------------------------------------------+ __LINE__ = ",__LINE__); //--- set the interval between the timer events //+------------------------------------------------------------------+
262
263
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 M_E M_LOG2E M_LOG10E M_LN2 M_LN10 M_PI M_PI_2 M_PI_4 M_1_PI M_2_PI M_2_SQRTPI M_SQRT2 M_SQRT1_2 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)); | //+------------------------------------------------------------------+
Description e log2(e) log10(e) ln(2) ln(10) pi pi/2 pi/4 1/pi 2/pi 2/sqrt(pi) sqrt(2) 1/sqrt(2)
Value 2.71828182845904523536 1.44269504088896340736 0.434294481903251827651 0.693147180559945309417 2.30258509299404568402 3.14159265358979323846 1.57079632679489661923 0.785398163397448309616 0.318309886183790671538 0.636619772367581343076 1.12837916709551257390 1.41421356237309504880 0.707106781186547524401
264
265
CHAR_MAX
127
UCHAR_MAX
255
SHORT_MIN
-32768
SHORT_MAX
32767
USHORT_MAX
65535
INT_MIN
-2147483648
INT_MAX
2147483647
UINT_MAX
4294967295
LONG_MIN
-9223372036854775808
LONG_MAX
9223372036854775807
ULONG_MAX
18446744073709551615
DBL_MIN
2.2250738585072014e-308
DBL_MAX
1.7976931348623158e+308
DBL_EPSILON
2.2204460492503131e-016
DBL_DIG
15
266
Standard Constants, Enumerations and Structures digits for double type DBL_MANT_DIG Bits count in a mantissa for double type Maximal decimal value of exponent degree for double type Maximal binary value of exponent degree for double type Minimal decimal value of exponent degree for double type Minimal binary value of exponent degree for double type Minimal positive value, which can be represented by float type Maximal value, which can be represented by float type Minimal value, which satisfies the condition: 1.0+DBL_EPSILON != 1.0 (for float type) Number of significant decimal digits for float type Bits count in a mantissa for float type Maximal decimal value of exponent degree for float type Maximal binary value of exponent degree for float type Minimal decimal value of exponent degree for float type Minimal binary value of exponent degree for float type 53
DBL_MAX_10_EXP
308
DBL_MAX_EXP
1024
DBL_MIN_10_EXP
(-307)
DBL_MIN_EXP
(-1021)
FLT_MIN
1.175494351e-38
FLT_MAX
3.402823466e+38
FLT_EPSILON
1.192092896e07
FLT_DIG
FLT_MANT_DIG
24
FLT_MAX_10_EXP
38
FLT_MAX_EXP
128
FLT_MIN_10_EXP
-37
FLT_MIN_EXP
(-125)
Example:
void OnStart() { //--- print the constant values printf("CHAR_MIN = %d",CHAR_MIN);
267
268
REASON_REMOVE
REASON_RECOMPILE REASON_CHARTCHANGE
2 3
Program has been recompiled Symbol or chart period has been changed Chart has been closed Input parameters have been changed by a user A new account activated has been
REASON_CHARTCLOSE REASON_PARAMETERS
4 5
REASON_ACCOUNT
REASON_TEMPLATE
been
REASON_INITFAILED
This value means that OnInit() handler has returned a nonzero value.
The uninitialization reason code is also passed as a parameter of the predetermined function OnDeinit (const int reason). Example:
input int par=7; //+------------------------------------------------------------------+ //| get text description string getUnitReasonText(int reasonCode) { string text=""; //--switch(reasonCode) { case REASON_ACCOUNT: text="Account was changed";break; case REASON_CHARTCHANGE: text="Symbol or timeframe was changed";break; case REASON_CHARTCLOSE: | //+------------------------------------------------------------------+
269
270
POINTER_AUTOMATIC
271
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 CHARTS_MAX Description The maximum possible number of simultaneously open charts in the terminal Absence of color Empty value in an indicator buffer Incorrect handle Flag that a mq5-program operates in debug mode Zero for any types Means the number of items remaining until the end of the array, i.e., the entire array will be processed The constant can be implicitly cast to any enumeration type Value 100
CLR_NONE EMPTY_VALUE
-1 DBL_MAX
INVALID_HANDLE IS_DEBUG_MODE
NULL WHOLE_ARRAY
WRONG_VALUE
-1
The EMPTY_VALUE constant usually corresponds to the values of indicators that are not shown inn the chart. For example, for built-in indicator Standard Deviation with a period of 20, the line for the first 19 bars in the history is not shown in the chart. If you create a handle of this indicator with the iStdDev() function and copy it to an array of indicator values for these bars through CopyBuffer(), then these values will be equal to EMPTY_VALUE. You can choose to specify for a custom indicator your own empty value of the indicator, when the indicator shouldn't be drawn in the chart. Use the PlotIndexSetDouble() function with the PLOT_EMPTY_VALUE modifier. The NULL constant can be assigned to a variable of any simple type or to an object structure or class pointer. The NULL assignment for a string variable means the full deinitialization of this variable. The WRONG_VALUE constant is intended for cases, when it is necessary to return value of an enumeration, and this must be a wrong value. For example, when we need to inform that a return value is a value from this enumeration. Let's consider as an example some function CheckLineStyle(), which returns the line style for an object, specified by its name. If at style check by ObjectGetInteger () the result is true, a value from ENUM_LINE_STYLE is returned; otherwise WRONG_VALUE is returned.
272
The WHOLE_ARRAY constant is intended intended for functions that require specifying the number of elements in processed arrays: ArrayCopy(); ArrayMinimum(); ArrayMaximum(); FileReadArray(); FileWriteArray(). If you want to specify, that all the array values from a specified position till the end must be processed, you should specify just the WHOLE_ARRAY value. The IS_DEBUG_MODE constant can be useful when you need to slightly change the operation of a mql5 program in the debugging mode. For example, in debug mode you may need to display additional debugging information in the terminal log or create additional graphical objects in a chart. The following example creates a Label object and sets its description and color depending on the script running mode. In order to run a script in the debug mode from MetaEditor, press F5. If you run the script from the browser window in the terminal, then the color and text of the object Label will be different. Example:
//+------------------------------------------------------------------+ //| //| //| Check_DEBUG_MODE.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.metaquotes.net |
//+------------------------------------------------------------------+ #property copyright "Copyright 2009, MetaQuotes Software Corp." #property link "http://www.metaquotes.net" //+------------------------------------------------------------------+
273
//+------------------------------------------------------------------+
274
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; MqlTradeResult contains a trade server reply to a trade request, sent by OrderSend() function; MqlTick is designed for fast retrieval of the most requested information about current prices.
275
MqlDateTime
The date type structure contains eight fields of the int type:
struct { int int int int int int int int }; MqlDateTime year; mon; day; hour; min; sec; day_of_week; day_of_year; // // // // // // // // Year Month Day Hour Minutes Seconds Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 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 */
276
// // // //
type of the input parameter, value of ENUM_DATATYPE field to store an integer type field to store a double type 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.
277
MqlRates
This structure stores information about the prices, volumes and spread.
struct MqlRates { datetime time; double open; double high; double low; double close; long tick_volume; int spread; long real_volume; };
// // // // // // // //
Period start time Open price The highest price of the period The lowest price of the period Close price Tick volume Spread 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"); }
278
MqlBookInfo
It provides information about the market depth data.
struct MqlBookInfo { ENUM_BOOK_TYPE double long };
Note The DOM is available only for some symbols. To use the MqlBookInfo structure, it is sufficient to declare a variable of such a type, so it is not necessary to specify and describe it specially. Example:
MqlBookInfo priceArray[]; bool getBook=MarketBookGet(NULL,priceArray); if(getBook) { int size=ArraySize(priceArray); Print("MarketBookInfo about ",Symbol()); } else { Print("Failed to receive DOM for the symbol ",Symbol()); }
See also MarketBookAdd, MarketBookRelease, MarketBookGet, Trade Orders in DOM, Data Types
279
struct MqlTradeRequest { ENUM_TRADE_REQUEST_ACTIONS ulong ulong string double double double double double ulong ENUM_ORDER_TYPE ENUM_ORDER_TYPE_FILLING ENUM_ORDER_TYPE_TIME datetime string };
action; magic; order; symbol; volume; price; stoplimit; sl; tp; deviation; type; type_filling; type_time; expiration; comment;
// // // // // // // // // // // // // // //
Trade operation type Expert Advisor ID (magic number) Order ticket Trade symbol Requested volume for a deal in lots Price StopLimit level of the order Stop Loss level of the order Take Profit level of the order Maximal possible deviation from the requested p Order type Order execution type Order execution time Order expiration time (for the orders of ORDER_ Order comment
Fields description Field action Description Trade operation type. Can be one of the ENUM_TRADE_REQUEST_ACTIONS enumeration values. 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 ticket. It is used for modifying pending orders. Symbol of the order. It is not necessary for order modification and position close operations. Requested order volume in lots. Note that the real volume of a deal will depend on the order execution type. Price, reaching which the order must be executed. Market orders of symbols, whose execution type is "Market Execution" ( SYMBOL_TRADE_EXECUTION_MARKET), of
magic
order
symbol
volume
price
280
TRADE_ACTION_DEAL type, do not require specification of price. stoplimit The price value, at which the StopLimit pending order will be placed, when price reaches the price value (this condition is obligatory). Until then the pending order is not placed). Stop Loss price in case of the unfavorable price movement Take Profit price in the case of the favorable price movement The maximal price deviation, specified in points Order type. Can be one of ENUM_ORDER_TYPE enumeration values. the
sl
tp
deviation
type
type_filling
Order execution type. Can be one of the enumeration ENUM_ORDER_TYPE_FILLING values. Order expiration type. Can be one of the enumeration ENUM_ORDER_TYPE_TIME values. Order expiration time (for ORDER_TIME_SPECIFIED type) Order comment orders of
type_time
expiration
comment
For sending orders to perform trade operations it is necessary to use the OrderSend() function. For each trade operation it is necessary to specify obligatory fields; optional fields also may be filled. There are seven possible cases to send a trade order: Request Execution This is a trade order to open a position in the Request Execution mode (trade upon current prices request). It requires to specify the following 9 fields: action symbol volume price sl tp deviation type type_filling 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 flow prices). It
281
Standard Constants, Enumerations and Structures 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. SL & TP Modification Trade order to modify the StopLoss and/or TakeProfit price levels. It requires to specify the following 5 fields: action symbol sl tp deviation Pending Order Trade order to place a pending order. It requires to specify the following 11 fields: action symbol volume price stoplimit sl tp type type_filling type_time expiration
282
Standard Constants, Enumerations and Structures 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
283
// // // // // // // //
Reply code Balance after the execution of the deal Equity after the execution of the deal Floating profit Margin requirements Free margin Margin level Comment to the reply code (description of the error)
Description of Fields Field retcode balance Description Return code Balance value that will be after the execution of the trade operation Equity value that will be after the execution of the trade operation Value of the floating profit that will be after the execution of the trade operation Margin required for the trade operation Free margin that will be left after the execution of the trade operation Margin level that will be set after the execution of the trade operation Comment to the reply code, error description
equity
profit
margin margin_free
margin_level
284
struct MqlTradeResult { uint retcode; ulong deal; ulong order; double volume; double price; double bid; double ask; string comment; };
// // // // // // // //
Operation return code Deal ticket, if it is performed Order ticket, if it is placed Deal volume, confirmed by broker Deal price, confirmed by broker Current Bid price Current Ask price Broker comment to operation (by default it is filled by the operatio
Fields description Field retcode deal Description Return code of a trade server Deal ticket, if a deal has been performed. It is available for a trade operation of TRADE_ACTION_DEAL type Order ticket, if a ticket has been placed. It is available for a trade operation of TRADE_ACTION_PENDING type Deal volume, confirmed by broker. It depends on the order filling type Deal price, confirmed by broker. It dependens on the deviation field of the trade request and/ or on the trade operation The current market Bid price (requote price) The current market Ask price (requote price) The broker comment to operation (by default it is filled by the operation description)
order
volume
price
The trade operation result is returned to a variable of the MqlTradeResult type, which is passed as the second parameter to OrderSend() to perform a trade operations. Example:
285
286
287
// // // // //
Time of the last prices update Current Bid price Current Ask price Price of the last deal (Last) Volume for the current Last price
The variable of the MqlTick type allows obtaining values of Ask, Bid, Last and Volume within a single call of the SymbolInfoTick() function. Example:
void OnTick() { MqlTick last_tick; //--if(SymbolInfoTick(Symbol(),last_tick)) { Print(last_tick.time,": Bid = ",last_tick.bid, " Ask = ",last_tick.ask," } else Print("SymbolInfoTick() failed, error = ",GetLastError()); //--} Volume = ",last_tick.volume);
288
289
10015
10016
10017
Trade is disabled
10018
Market is closed
10019
10020
10021
There are no quotes to process the request Invalid order expiration date in the request Order state changed
10022
10023
10024
290
Standard Constants, Enumerations and Structures 10025 TRADE_RETCODE_NO_CHANGE S TRADE_RETCODE_SERVER_DIS ABLES_AT TRADE_RETCODE_CLIENT_DISA BLES_AT TRADE_RETCODE_LOCKED TRADE_RETCODE_FROZEN TRADE_RETCODE_INVALID_FIL L TRADE_RETCODE_CONNECTION No changes in request
10026
10027
Autotrading disabled by client terminal Request locked for processing Order or position frozen Invalid order filling type
10031
No connection with the trade server Operation is allowed only for live accounts The number of pending orders has reached the limit The volume of orders and positions for the symbol has reached the limit
10032
TRADE_RETCODE_ONLY_REAL
10033
TRADE_RETCODE_LIMIT_ORDE RS TRADE_RETCODE_LIMIT_VOLU ME
10034
291
Compiler Warnings
Compiler warnings are shown for informational purposes only and are not error messages. Code 21 Description Incomplete record of a date in the datetime string 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 ).... Wrong number of datetime string for time. Requirements: Hour 0 <= X <24 Minute 0 <= X <60 Invalid color in RGB format: one of RGB components is less than 0 or greater than 255 Unknown character of the escape sequences. Known: \ n \ r \ t \ \ \ "\ '\ X \ x Too large volume of local variables (> 512Kb) of the function, reduce the number Enumeration already defined (duplication) members will be added to the first definition Overriding macro The variable is declared but is not used anywhere Constructor must be of void type Destructor must be of void type Constant does not fit in the range of integers (X> _UI64_MAX | | X <_I64_MIN) and will be converted to the double type Too long HEX - more than 16 significant characters (senior nibbles are cut) No nibbles in HEX string "0x" No function - nothing to be performed A non-initialized variable is used Function has no body, and is not called Possible loss of data at typecasting. Example: int x = (double) z;
22
23
24
25
26
29
30 31
32 33 34
35
36 37 38 41 43
292
44
Loss of accuracy (of data) when converting a constant. Example: int x = M_PI Difference between the signs of operands in the operations of comparison. Example: (char) c1> (uchar) c2 Problems with function importing - declaration of #import is required or import of functions is closed Too large description - extra characters will not be included in the executable file The number of indicator buffers declared is less than required No color to plot a graphical series in the indicator No graphical series to draw the indicator 'OnStart' handler function not found in the script 'OnStart' handler function is defined with wrong parameters 'OnStart' function can be defined only in a script 'OnInit' function parameters is defined with wrong
45
46
47
48
49
50 51
52
53 54
55 56
'OnInit' function is not used in scripts 'OnDeinit' function is parameters defined with wrong
57 58
'OnDeinit' function is not used in scripts Two 'OnCalculate' functions are defined. OnCalculate () at one price array will be used Overfilling detected when calculating a complex integer constant Probably, the variable is not initialized. This declaration makes it impossible to refer to the local variable declared on the specified line This declaration makes it impossible to refer to the global variable declared on the specified line Cannot be used for static allocated array This variable variable declaration hides predefined
59
60 61
62
63 64
293
65
294
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 100 101 Description File reading error Error of *. EX5 file opening to write it for saving Not enough free memory to complete compilation Empty syntactic unit unrecognized by compiler Incorrect file name in #include Error accessing a file in #include (probably the file does not exist) Inappropriate name for #define Unknown command of preprocessor (valid #include, #define, #property, #import) Symbol unknown to compiler Function not implemented (description is present, but no body) Double quote (") omitted Opening angle bracket (<) or double quote (") omitted Single quote (') omitted Closing angle bracket ">" omitted Type not specified in declaration No return operator or return is found not in all branches of the implementation Opening bracket of call parameters was expected Error writing EX5 Invalid access to an array The function is not of void type and the return operator must return a value Incorrect declaration of the destructor
103
108 109
110 111
112 113
118
122
295
Colon ":" is missing Variable is already declared Variable with such identifier already declared Variable name is too long (> 250 characters) Structure with such identifier already defined Structure is not defined Structure member with the same name already defined No such structure member Breached pairing of brackets Opening parenthesis "(" expected Unbalanced braces (no "}") Difficult to compile (too much branching, internal stack levels is overfilled) Error of file opening for reading Not enough memory to download the source file into memory Variable is expected Reference cannot be initialized Assignment expected (appears at declaration) Opening brace "{" expected Parameter can be a dynamic array only Use of "void" type is unacceptable No pair for ")" or "]", i.e. "(or" [ " is absent No pair for "(or" [ ", i.e. ") "or"] " is absent Incorrect array size Too many parameters (> 64) This token is not expected here Invalid use of operation (invalid operands) Expression of void type not allowed Operator is expected Misuse of break Semicolon ";" expected Comma "," expected
135 136
137 138 140 141 142 143 144 145 146 147 149 150 151 152 153 154 155
296
Must be a class type, not struct Expression is expected "non HEX character" found in HEX or too long number (number of digits> 511) String-constant has more than 65534 characters Function definition is unacceptable here Unexpected end of program Forward declaration is prohibited for structures Function with this name is already defined and has another return type Function with this name is already defined and has a different set of parameters Function with this name is already defined and implemented Function overload for this call was not found Function with a return value of void type cannot return a value Function is not defined Value is expected In case expression only integer constants are valid The value of case in this switch is already used Integer is expected In #import expression file name is expected Expressions are not allowed on global level Omitted parenthesis ")" before ";" To the left of equality sign a variable is expected The result of expression is not used Declaring of variables is not allowed in case Implicit conversion from a string to a number Implicit conversion of a number to a string Ambiguous call of an overloaded function (several overloads fit) Illegal else without proper if
164
165
166 167
183
297
Invalid case or default without a switch Inappropriate use of ellipsis The initializing sequence has more elements than the initialized variable A constant for case expected A constant expression required A constant variable can not be changed Closing bracket or a comma is expected (declaring array member) Enumerator identifier already defined Enumeration cannot have access modifiers (const, extern, static) Enumeration member already declared with a different value There is a variable defined with the same name There is a structure defined with the same name Name of enumeration member expected Integer expression expected Division by zero in constant expression Wrong number of parameters in the function Parameter by reference must be a variable Variable of the same type to pass by reference expected A constant variable cannot be passed by a nonconstant reference Requires a positive integer constant Failed to access protected class member Import already defined in another way Executable file not created 'OnCalculate' entry point not found for the indicator The continue operation can be used only inside a loop Error accessing private (closed) class member Method of structure or class is not declared
191 192
193
194 195
202
210
211 213
298
214 216
Error accessing private (closed) class method Copying of structures with objects is not allowed Index out of array range Array initialization in structure or class declaration not allowed Class constructor cannot have parameters Class destructor can not have parameters Class method or structure with the same name and parameters have already been declared Operand expected Class method or structure with the same name exists, but with different parameters (declaration!=implementation) Imported function is not described Ambiguous call of the overloaded function (exact match of parameters for several overloads) Variable name expected A reference cannot be declared in this place Already used as the enumeration name Class or structure expected Cannot call 'delete' operator to delete the array Operator ' while' expected Operator 'delete' must have a pointer There is 'default' for this 'switch' already Syntax error Escape-sequence can occur only in strings (starts with '\') Array required - square bracket '[' does not apply to an array, or non arrays are passed as array parameters Can not be initialized through the initialization sequence Import is not defined Optimizer error on the syntactic tree
218 219
223 224
225 227
228 229 230 232 235 236 237 238 239 240
241
242
243 244
299
245
Declared too many structures (try to simplify the program) Conversion of the parameter is not allowed Incorrect use of the 'delete' operator It's not allowed to declare a pointer to a reference It's not allowed to declare a reference to a reference It's not allowed to declare a pointer to a pointer Structure declaration in the list of parameter is not allowed Invalid operation of typecasting A pointer can be declared only for a class or structure Undeclared identifier Executable code optimizer error Executable code generation error Invalid expression for the 'switch' operator Pool of string constants overfilled, simplify program Cannot convert to enumeration Do not use 'virtual' for data (members of a class or structure) Cannot call protected method of class Overridden virtual functions returns a different type Class cannot be inherited from a structure Structure cannot be inherited from a class Constructor cannot be virtual (virtual specifier is not allowed) Structure cannot have virtual methods Function must have a body Overloading of system functions (terminal functions) is prohibited Const specifier is invalid for functions that are not members of a class or structure
249
250 251
252 253
262 263
264 265
272
300
273
Not allowed to use const for data (members of a class or structure) Not allowed to change class members in constant method Not allowed to declare more than 64 input parameters (input-variables) Inappropriate initialization sequence Missed default value for the parameter (specific declaration of default parameters) Overriding the default parameter (different values in declaration and implementation) Not allowed to call non-constant method for a constant object An object is necessary for accessing members (a point for a non class/structure is set) The name of an already declared structure cannot be used in declaration Structure name cannot be used as the name of a class member Incorrect type or combination of parameters for the 'OnCalculate' entry point Unauthorized conversion (at closed inheritance) Structures and arrays cannot be used as input variables Const specifier is not valid for constructor/ destructor Incorrect string expression for a datetime Unknown property (#property) Incorrect value of a property Invalid index for a property in #property Call parameter omitted - <func (x,)> Object must be passed by reference Array must be passed by reference Function was declared as exportable Function was not declared as exportable It is prohibited to export imported function Imported function cannot have this parameter
274
275
276 277
278
279
280
281
282
283
284 285
286
287 288 289 290 291 293 294 295 296 297 298
301
(prohibited to pass a pointer, class or structure containing a dynamic array, pointer, class, etc.) 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 Must be a class #import was not closed Initialize sequence expected Type missmatch Extern variable is already initialized No exported function or entry point found Explicit constructor call is not allowed Method was not declared as constant Method was not declared as constant Incorrect size of the resource file Incorrect resource name Resource file opening error Resource file reading error Unknown resource type Incorrect path to the resource file
302
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 ERR_SUCCESS 0 Code Description The operation successfully completed
4001 4002
Unexpected internal error Wrong parameter in the inner call of the client terminal function Wrong parameter when calling the system function Not enough memory to perform the system function The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes Array of a wrong type, wrong size, or a damaged object of a dynamic array Not enough memory for the relocation of an array, or an attempt to change the size of a static array Not enough memory for the relocation of string Not initialized string Invalid date and/or time Requested array size exceeds 2 GB Wrong pointer Wrong type of pointer System function is not allowed to call
ERR_INVALID_PARAMETER
4003
ERR_NOT_ENOUGH_MEMORY
4004
ERR_STRUCT_WITHOBJECTS_ ORCLASS
4005
ERR_INVALID_ARRAY
4006
ERR_ARRAY_RESIZE_ERROR
4007
ERR_STRING_RESIZE_ERROR
4008
4101 4102
303
ERR_CHART_NOT_FOUND ERR_CHART_NO_EXPERT
4103 4104
Chart not found No Expert Advisor in the chart that could handle the event Chart opening error Failed to change chart symbol and period Wrong parameter for timer
ERR_CHART_CANNOT_OPEN ERR_CHART_CANNOT_CHANG E ERR_CHART_WRONG_TIMER_ PARAMETER ERR_CHART_CANNOT_CREATE _TIMER ERR_CHART_WRONG_PROPER TY ERR_CHART_SCREENSHOT_FA ILED ERR_CHART_NAVIGATE_FAILE D ERR_CHART_TEMPLATE_FAILE D ERR_CHART_WINDOW_NOT_F OUND ERR_CHART_INDICATOR_CAN NOT_ADD ERR_CHART_INDICATOR_CAN NOT_DEL ERR_CHART_INDICATOR_NOT _FOUND Graphical Objects ERR_OBJECT_ERROR
4105 4106
4107
4108
4109
4110
4111
4112
4113
the
4114
Error adding an indicator to chart Error deleting an from the chart indicator
4115
4116
4201
Error working with a graphical object Graphical object was not found Wrong ID of a graphical object property Unable to get date corresponding to the value Unable to get value corresponding to the date
4202 4203
4204
4205
4301
Unknown symbol
304
ERR_MARKET_SELECT_ERROR
4302
in
ERR_MARKET_WRONG_PROPE RTY ERR_MARKET_LASTTIME_UNK NOWN History Access ERR_HISTORY_NOT_FOUND ERR_HISTORY_WRONG_PROPE RTY Global_Variables ERR_GLOBALVARIABLE_NOT_F OUND ERR_GLOBALVARIABLE_EXISTS
4303
Wrong identifier of a symbol property Time of the last tick is not known (no ticks)
4304
4401 4402
4501
Global variable of the client terminal is not found Global variable of the client terminal with the same name already exists Email sending failed Sound playing failed Wrong identifier program property Wrong identifier terminal property of the
4502
ERR_MAIL_SEND_FAILED ERR_PLAY_SOUND_FAILED ERR_MQL5_WRONG_PROPERT Y ERR_TERMINAL_WRONG_PROP ERTY ERR_FTP_SEND_FAILED Custom Indicator Buffers ERR_BUFFERS_NO_MEMORY
4513
of
the
4514
4601
Not enough memory for the distribution of indicator buffers Wrong indicator buffer index
ERR_BUFFERS_WRONG_INDEX Custom Indicator Properties ERR_CUSTOM_WRONG_PROPE RTY Account ERR_ACCOUNT_WRONG_PROP ERTY ERR_TRADE_WRONG_PROPER TY ERR_TRADE_DISABLED
4602
4603
custom
4701
4751
4752
305
ERR_TRADE_POSITION_NOT_F OUND ERR_TRADE_ORDER_NOT_FOU ND ERR_TRADE_DEAL_NOT_FOUN D ERR_TRADE_SEND_FAILED Indicators ERR_INDICATOR_UNKNOWN_S YMBOL ERR_INDICATOR_CANNOT_CRE ATE ERR_INDICATOR_NO_MEMORY
4753
4754
4755
4756
4801
Unknown symbol
4802
4803
Not enough memory to add the indicator The indicator cannot be applied to another indicator Error applying an indicator to chart Requested data not found
ERR_INDICATOR_CANNOT_APP LY ERR_INDICATOR_CANNOT_AD D ERR_INDICATOR_DATA_NOT_F OUND ERR_INDICATOR_WRONG_HAN DLE ERR_INDICATOR_WRONG_PAR AMETERS ERR_INDICATOR_PARAMETERS _MISSING ERR_INDICATOR_CUSTOM_NA ME
4804
4805
4806
4807
4808
Wrong number of parameters when creating an indicator No parameters when creating an indicator The first parameter in the array must be the name of the custom indicator Invalid parameter type in the array when creating an indicator Wrong index of the requested indicator buffer
4809
4810
ERR_INDICATOR_PARAMETER_ TYPE
4811
4812
4901
Depth Of Market can not be added Depth Of Market can not be removed
ERR_BOOKS_CANNOT_DELETE
4902
306
ERR_BOOKS_CANNOT_GET
4903
The data from Depth Of Market can not be obtained Error in subscribing to receive new data from Depth Of Market
ERR_BOOKS_CANNOT_SUBSCRI BE
4904
File Operations ERR_TOO_MANY_FILES 5001 More than 64 files cannot be opened at the same time Invalid file name Too long file name File opening error Not enough memory for cache to read File deleting error A file with this handle was closed, or was not opening at all Wrong file handle The file must be opened for writing The file must be opened for reading The file must be opened as a binary one The file must be opened as a text The file must be opened as a text or CSV The file must be opened as CSV File reading error String size must be specified, because the file is opened as binary A text file must be for string arrays, for other arrays binary This is not a file, this is a directory
5006 5007
ERR_WRONG_FILEHANDLE ERR_FILE_NOTTOWRITE
5008 5009
ERR_FILE_NOTTOREAD
5010
ERR_FILE_NOTBIN
5011
ERR_FILE_NOTTXT
5012
ERR_FILE_NOTTXTORCSV
5013
ERR_FILE_NOTCSV
5014
ERR_FILE_READERROR ERR_FILE_BINSTRINGSIZE
5015 5016
ERR_INCOMPATIBLE_FILE
5017
ERR_FILE_IS_DIRECTORY
5018
307
File does not exist File can not be rewritten Wrong directory name
Directory does not exist This is a file, not a directory The directory removed cannot be
5025
Failed to clear the directory (probably one or more files are blocked and removal operation failed)
String Casting ERR_NO_STRING_DATE ERR_WRONG_STRING_DATE ERR_WRONG_STRING_TIME ERR_STRING_TIME_ERROR ERR_STRING_OUT_OF_MEMOR Y ERR_STRING_SMALL_LEN 5030 5031 5032 5033 5034 No date in the string Wrong date in the string Wrong time in the string Error converting string to date Not enough memory for the string The string length is less than expected Too large number, more than ULONG_MAX Invalid format string Amount of format specifiers more than the parameters Amount of parameters more than the format specifiers Damaged parameter of string type Position outside the string
5035
5036
5037 5038
5039
5040
5041
5042
0 added to the string end, a useless operation Unknown data type converting to a string Damaged string object when
ERR_STRING_UNKNOWNTYPE
5043
ERR_WRONG_STRING_OBJECT
5044
308
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 The receiving array is declared as AS_SERIES, and it is of insufficient size Too small array, the starting position is outside the array An array of zero length Must be a numeric array Must be a one-dimensional array Timeseries cannot be used Must be an array of type double Must be an array of type float Must be an array of type long Must be an array of type int Must be an array of type short Must be an array of type char
ERR_SMALL_ASSERIES_ARRAY
5051
ERR_SMALL_ARRAY
5052
ERR_SERIES_ARRAY ERR_DOUBLE_ARRAY_ONLY
5056 5057
65536
309
310
FILE_WRITE
FILE_BIN
FILE_CSV
FILE_TXT
16
FILE_ANSI
32
FILE_UNICODE
64
FILE_SHARE_READ
128
FILE_SHARE_WRITE
256
FILE_REWRITE
512
FILE_COMMON
4096
311
Standard Constants, Enumerations and Structures 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 suze. 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
312
313
CP_OEMCP
The current system OEM code page. 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. The Windows ANSI code page for the current thread. Symbol code page UTF-7 code page. UTF-8 code page.
CP_MACCP
CP_THREAD_ACP
42 65000 65001
314
IDABORT
button
has
been
IDRETRY
button
has
been
IDIGNORE
button
has
been
6 7 10
"Yes" button has been pressed "No" button has been pressed "Try Again" button has been pressed "Continue" button has been pressed
IDCONTINUE
11
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 MB_OK Value 0x00000000 Description Message window contains only one button: OK. Default Message window contains two buttons: OK and Cancel Message window contains three buttons: Abort, Retry and Ignore Message window contains three buttons: Yes, No and Cancel Message window contains two buttons: Yes and No
MB_OKCANCEL
0x00000001
MB_ABORTRETRYIGNORE
0x00000002
MB_YESNOCANCEL
0x00000003
MB_YESNO
0x00000004
315
MB_RETRYCANCEL
0x00000005
Message window contains two buttons: Retry and Cancel Message window contains three buttons: Cancel, Try Again, Continue
MB_CANCELTRYCONTINUE
0x00000006
To display an icon in the message window it is necessary to specify additional flags: Constant MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND MB_ICONQUESTION MB_ICONEXCLAMATION, MB_ICONWARNING MB_ICONINFORMATION, MB_ICONASTERISK Value 0x00000010 Description The STOP sign icon
0x00000020 0x00000030
The question sign icon The exclamation/warning sign icon The encircled i sign
0x00000040
Default buttons are defined by the following flags: Constant MB_DEFBUTTON1 Value 0x00000000 Description The first button MB_DEFBUTTON1 - is default, if the other buttons MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 are not specified The second button is default The third button is default The fourth button is default
316
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 he following sections: Program running order of calling predefined event-handlers; 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 obtaining 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 by selecting "Expert Advisors - Remove" in chart context menu. Operation of Expert Advisors is also affected by the state of the button "Enable/disable Expert Advisors". 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 starts. Scripts are executed once and are deleted automatically upon operation completion or change of the current chart state, or upon client terminal shutdown. After the restart of the client terminal scripts are not started, because the information about them is not saved. Maximum one Expert Advisor, one script and unlimited number of indicators can operate in one chart.
317
MQL5 programs
Program Running
Right after a program is attached to a chart, it is uploaded to the client terminal memory, as well as global variable are initialized. If some global variable of the class type has a constructor, this constructor will be called during initialization of global variables. After that the program is waiting for an event from the client terminal. Each mql5-program should has at least one event-handler, otherwise the loaded program will not be executed. Event handlers have predefined names, parameters and return types. Type int Function name OnInit Parameters none Application Expert Advisors and indicators Comment Init event handler. It allows to use the void return type. Deinit handler. Start handler. event
void
OnDeinit
void
OnStart
none
event
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[] const int rates_total, const int prev_calculated, const int begin, const double &price[]
indicators
int
OnCalculate
indicators
Calculate event handler on the single data array. Indicator cannot have two event handlers simultaneously.
318
MQL5 programs
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. Timer handler. Trade handler. Tester handler. event
void
OnTimer
none
void
OnTrade
none
event
double
OnTester
none
Expert Advisors
event
void
OnChartEvent
const int id, const long &lparam, const double &dparam, const string &sparam const string &symbol_name
void
OnBookEvent
Expert Advisors
Client terminal adds appearing events to the events queue. So events are processed one after another in accordance to the order they were received. There is an exception for the NewTick event. If the queue already has such an event or this event is being processed, the new NewTick event is not enqueued. Queue of events is limited in size. At queue overflow, old events are removed without being processed in order to allow the receipt of new events. Therefore, it is recommended to write efficient event handlers, and it is not recommended to use infinite loops (there is an exception of scripts, which handle the Start event only). Libraries do not handle any events.
319
MQL5 programs 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.
320
MQL5 programs complete their operation. OnInit() and OnDeinit() are not called for scripts. When a program is unloaded (deleted from a chart) the client terminal performs deinitialization of global variables and deletes the events queue. In this case deinitialization means reset of all the string-type variables, deallocation of dynamical array objects and call of their destructors if they are available. For a better understanding of the Expert Advisor operation we recommend to compile the code of the following Expert Advisor and perform actions of load/unload, template change, symbol change, timeframe change etc: Example:
//+------------------------------------------------------------------+ //| //| //| TestExpert.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version class CTestClass { public: CTestClass() { Print("CTestClass constructor"); } ~CTestClass() { Print("CTestClass destructor"); } }; CTestClass global; //+------------------------------------------------------------------+ //| Expert initialization function int OnInit() { //--Print("Initialisation"); //--return(0); } //+------------------------------------------------------------------+ //| Expert deinitialization function void OnDeinit(const int reason) { //--Print("Deinitialisation with reason",reason); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+ "http://www.mql5.com" "1.00"
321
MQL5 programs
void OnTick() { //--} //+------------------------------------------------------------------+
322
MQL5 programs
323
MQL5 programs 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). Tester The Tester event is generated after testing of an Expert Advisor on history data is over. The event is handled by the OnTester() function. ChartEvent The ChartEvent event is generated by the client terminal when a user is working with a chart: keyboard press, when the chart window is focused; 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, will receive it. That's why it is necessary to analyse the symbol name, which is passed to a handler as a parameter. See also
324
325
MQL5 programs
326
MQL5 programs caller (in our case it is a mql5-program) puts parameters to the stack in a reverse order, from right to left - in this order an imported function reads parameters passed to it; parameters are passed by value, except those explicitly passed by reference (in our case lines) an imported function cleans the stack independently by reading parameters passed to it. When describing the prototype of an imported function, default parameters can be used. If the corresponding library is unable to load, or there is a prohibition on the DLL use, or the imported function is not found - the Expert Advisor stops its operation with the appropriate message "Expert Advisor stopped" in the Journal (log file). In this case the Expert Advisor will not run until it is reinitialized. An Expert Advisor can be reinitialized as a result of recompilation or after the table of its properties is opened and OK is pressed.
Passing Parameters
All parameters of simple types are passed by values unless it is explicitly indicated that they are passed by reference. When a string is passed, the address of the buffer of the copied string is passed; if a string is passed by reference, the address of the buffer of this string without copying it is passed to the function imported from DLL. Structures that contain dynamic arrays, strings, classes, other complex structures, as well as static or dynamic arrays of the enumerated objects, can't be passed as a parameter to an imported function. When passing an array to DLL, the address of the beginning of the data buffer is always passed (irrespective of the AS_SERIES flag). A function inside a DLL knows nothing about the AS_SERIES flag, the passed array is a static array of an undefined length; an additional parameter should be used for specifying the array size.
327
MQL5 programs
Runtime Errors
The executing subsystem of the client terminal has an opportunity to save the error code in case any occurs during a mql5-program run. There is a a predefined variable _LastError for each executable mql5 program. Before starting the OnInit function, the _LastError variable is reset. In case an erroneous situations occurs during calculations or in the process of internal function calls, the _LastError variable accepts a corresponding error code. The value stored in this variable can be obtained by using the GetLastError () function. There are several critical errors, appearing which a program is terminated immediately : division by zero; going beyond array ranges; using an incorrect object pointer;
328
Predefined Variables
Libraries are used by variables of the program they were called by.
329
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.
330
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.
331
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.
332
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
333
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.
334
Predefined Variables
string _Symbol
The _Symbol variable contains the symbol name of the current chart. You may also use the Symbol() function.
335
Predefined Variables
int _UninitReason
The _UninitReason variable contains the code of the program uninitialization reason. Usually, this code is obtained by UninitializeReason()the function.
336
Common Functions
Common Functions
General-purpose functions not included into any specialized group are listed here. Function Alert CheckPointer Comment Action Displays a message in a separate window Returns the type of the object pointer Outputs a comment in the left top corner of the chart Program breakpoint in debugging Stops expert advisor and unloads it from the chart Returns the object pointer Returns the number of milliseconds that have elapsed since the system was started Creates, displays a message box and manages it Returns the number of seconds in the period Plays a sound file Displays a message in the log Formats and prints the sets of symbols and values in a log file in accordance with a preset format Sets the value of a predetermined variable _LastError to zero Sends a file at the address specified in the settings window of the "Publisher" tab Sends an email at the address specified in the settings window of the "Mailbox" tab Suspends execution of the current Expert Advisor or script within a specified interval Commands the terminal to complete operation Resets a variable passed to it by reference. The variable can be of any type, except for classes and structures that have constructors.
DebugBreak ExpertRemove
GetPointer GetTickCount
MessageBox
ResetLastError
SendFTP
SendMail
Sleep
TerminalClose ZeroMemory
337
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 separate the information output in several lines you can use the line feed character "\n" or "\r\n". The number of parameters can not exceed 64. Return Value No return value. Note Arrays can't be passed to the Alert() function. Arrays should be output elementwise. Data of the double type are output with 8 digits after the decimal point, data of the float type are displayed with 5 digits after the decimal point. To derive the real numbers with a different precision or in a scientific format, use DoubleToString(). Data of bool the type are output as "true" or "false" strings. Dates are output as YYYY.MM.DD HH: MI:SS. To display a date in another format use TimeToString(). Data of the color type are output either as an R,G,B string or as a color name, if the color is present in a color set.
338
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:
//+------------------------------------------------------------------+ //| delete list by deleting its elements | //+------------------------------------------------------------------+ void CMyList::Destroy() { //--- service pointer for working in the loop CItem* item; //--- go through loop and try to delete dynamic pointers while(CheckPointer(m_items)!=POINTER_INVALID) { item=m_items; m_items=m_items.Next(); if(CheckPointer(item)==POINTER_DYNAMIC) { Print("Dynamyc object ",item.Identifier()," to be deleted"); delete (item); } else Print("Non-dynamic object ",item.Identifier()," cannot be deleted"); } //--}
339
Common Functions
See also Object Pointers, Checking the Object Pointer, Object Delete Operator delete
340
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 shown with the accuracy of up to 16 digits after a decimal point, and can be output either in traditional or in scientific format, depending on what entry will be more compact. Data of float type are output with 5 digits after a decimal point. To output real numbers with another accuracy or in a predefined format, use the DoubleToString() function. Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS. To show data in another format, use TimeToString(). Data of color type are returned either as R,G, B line or as a color name, if this color is present in the color set. The Comment function can't be called from a custom indicator, because a custom indicator can't access chart, to which it is attached. 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)); }
341
Common Functions
DebugBreak
It is a program breakpoint in debugging.
void DebugBreak();
Return Value No return value. Note Execution of an mql5 program is broken only if a program is started in a debugging mode. The function can be used for viewing values fo variables and/or for further step-by-step execution.
342
Common Functions
ExpertRemove
The function stops an Expert Advisor and unloads it from a chart.
void ExpertRemove();
Returned value No return value. Note The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag to stop the EA operation is set. That is, any next event won't be processed, OnDeinit() will be called and the Expert Advisor will be unloaded and removed from the chart. Example:
//+------------------------------------------------------------------+ //| //| //| Test_ExpertRemove.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "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) { | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
343
Common Functions
ExpertRemove(); Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded"); } Print("tick_counter =",tick_counter); //--} //+------------------------------------------------------------------+
344
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 of an error. An attempt to call an incorrect pointer causes the critical termination of a program. That's why the CheckPointer() function should be called prior to using a pointer. A pointer can be incorrect in the following cases: 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. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00"
345
Common Functions
class CItem { int string CItem* public: CItem() { m_id=0; m_comment=NULL; m_next=NULL; } ~CItem() { Print("Destructor of ",m_id, (CheckPointer(GetPointer(this))==POINTER_DYNAMIC)? "dynamic":"non-dynamic"); } void void int CItem* void }; //+------------------------------------------------------------------+ //| simplest class of the list | //+------------------------------------------------------------------+ class CMyList { CItem* public: CMyList() { m_items=NULL; } ~CMyList() { Destroy(); } bool void }; //+------------------------------------------------------------------+ //| inserting list element at the beginning | //+------------------------------------------------------------------+ bool CMyList::InsertToBegin(CItem* item) { if(CheckPointer(item)==POINTER_INVALID) return(false); //--item.Next(m_items); m_items=item; //--return(true); } //+------------------------------------------------------------------+ //| deleting the list by deleting elements | //+------------------------------------------------------------------+ void CMyList::Destroy() { //--- service pointer to work in a loop CItem* item; //--- go through the loop and try to delete dynamic pointers InsertToBegin(CItem* item); Destroy(); m_items; Initialize(int id,string comm) { m_id=id; m_comment=comm; } PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); } Identifier() { return(m_id); } Next() {return(m_next); } Next(CItem *item) { m_next=item; } m_id; m_comment; m_next;
346
Common Functions
while(CheckPointer(m_items)!=POINTER_INVALID) { item=m_items; m_items=m_items.Next(); if(CheckPointer(item)==POINTER_DYNAMIC) { Print("Dynamyc object ",item.Identifier()," to be deleted"); delete (item); } else Print("Non-dynamic object ",item.Identifier()," cannot be deleted"); } //--} //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { CMyList list; CItem CItem* items[10]; 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();
347
Common Functions
//--- all the list elements will be deleted after the script is over //--- see the Experts tab in the terminal }
See also Object Pointers, Checking the Object Pointer, Object Delete Operator delete
348
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 if a computer works uninterruptedly.
349
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, string caption=NULL, int ); flags=0 // message text // box header // defines set of buttons in the box
Parameters text [in] Text, containing message to output. caption=NULL [in] Optional text to be displayed in the box header. If the parameter is empty, Expert Advisor name is shown in the box header. flags=0 [in] Optional flags defining appearance and behavior of a message box. Flags can be a combination of a special group of flags. Return Value If the function is successfully performed, the returned value is one of values of MessageBox() return codes. Note The function can't be called from custom indicators, because indicators are executed in the interface thread and shouldn't slow down it.
350
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
351
Common Functions
PlaySound
It plays a sound file.
bool PlaySound( string filename ); // file name
Parameters filename [in] Path to a sound file. Return Value true if the file is found, otherwise - false. Note The file must be located in terminal_directory\Sounds ot its sub-directory. Only WAV files are played.
352
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. Number of parameters can't exceed 64. Note Arrays cannot be passed to the Print() function. Arrays must be input element-by-element. Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be output either in traditional or in scientific format, depending on what entry will be more compact. Data of float type are output with 5 digits after a decimal point. To output real numbers with another accuracy or in a predefined format, use the DoubleToString() function. Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS. To show data in another format, use TimeToString(). Data of color type are returned either as R,G, B line or as a color name, if this color is present in the color set. Example:
Print("Time of the last received quote ",TimeCurrent());
353
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 line // values of simple types
Parameters format_string [in] A format line consists of simple symbols, and if the format line is followed by arguments, it also contains format specifications. ... [in] Any values of simple types separated by commas. Total number of parameters can't exceed 64 including the format line. Return Value String. Note Instead of PrintFormat() you can use printf(). If the format line is followed by parameters, this line must contain format specifications that denote output format of these parameters. Specification of format always starts with the percent sign (%). A format line is read from left to right. When the first format specification is met (if there is any), the value of the first parameter after the format line is transformed and output according to the preset specification. The second format specification calls transformation and output of the second parameter, and so on till the format line end. If there are more parameters than format specifications, these additional parameters are ignored. 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 line, use the format specification %%.
flags
Flag (minus) Description Left justification within the Default Behavior Right justification
354
Common Functions
set width + (plus) Output of the + or - sign for values of sign types 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. A space is shown before an output value, if it is a sign and positive value If used together with the format o, x or X, then before the output value 0, 0x or 0X is added respectively. If used together with the format e, E, a or A, value is always shown with a decimal point. 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. The sign is shown only of the value is negative Nothing is added
0 (zero)
space
Nothing is added
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 set width, the corresponding number of spaces is added from the left or right depending on the alignment (flag ). If there is flag zero (0), the corresponding number of zeroes is added before the output value. If the number of output values is larger than the the preset width, the output value is never cut off. If an asterisk (*) is specified as width, value of int type must be indicated in the corresponding place of the list of passed parameters. It will be used for specifying width of the output value.
precision
A non-negative decimal number that sets the output accuracy - number of digits after a decimal
355
Common Functions 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 a, A Description Accuracy specification sets the number of digits after a decimal point. Not used 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 th specified accuracy. Sets number of output digits after a decimal point. The last digit is rounded off. Default accuracy 1. Default Behavior Default accuracy 6.
c, C d, i, u, o, x, X
e, E, f
Default accuracy 6. If set accuracy is 0 or decimal part is absent, the decimal point is not shown. 6 meaningful numbers are output. The whole line is output.
g, G
of
s, S
Sets number of output symbols of a line. If the line length exceeds the accuracy, the line is cut off.
h | l | ll | I32 | I64
Specification of data sizes, passed as a parameter. Parameter Type int uint long short ushort int uint Used Prefix l (lower case L) l (lower case L) ll (two lower case L) h h I32 I32 Joint Specifier of Type d, i, o, x, or X o, u, x, or X d, i, o, x, or X d, i, o, x, or X o, u, x, or X d, i, o, x, or X o, u, x, or X
356
Common Functions
long ulong
I64 I64
d, i, o, x, or X o, u, x, or X
type
Type specifier is the only obligatory field for formatted output. Symbol c Type int Output Format Symbol of (Unicode) short type
C d i o u x
Symbol of char type (ANSI) Sign decimal integer Sign decimal integer Unsigned octal integer Unsigned decimal integer Unsigned hexadecimal integer, using "abcdef" Unsigned hexadecimal integer, using "ABCDEF" 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 Similar to the format of e, except that the sign of exponent is output by upper case letter (E instead of e) 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.
int
double
double
double
357
Common Functions
double
A real value output in f or e format depending on what output is more compact. A real value output in F or E format depending on what output is more compact. 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 A real number in format [] 0xh.hhhh Pdd, where h.hhhh mantissa in the form of hexadecimal digits, using "ABSDEF", dd - One or more digits of exponent. Number of decimal places is determined by the accuracy specification Line output
double
double
double
string
358
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 _LastError variable. Usually ResetLastError() is called befor function call, after which error appearance is checked.
359
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 */ }
360
Common Functions
SendFTP
Sends a file at the address, specified in the setting window of the "Publisher" tab.
bool SendFTP( string filename, string ftp_path=NULL ); // file to send by ftp // file to upload on ftp server
Parameters filename [in] Name of sent file. ftp_path=NULL [in] FTP catalog. If a directory is not specified, directory described in settings is usesd. Return Value 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.
361
Common Functions
SendMail
Sends an email at the address specified in the settings window of the "Mailbox" tab.
bool SendMail( string subject, string some_text ); // header // 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 not specified. For the error information call GetLastError().
362
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.
363
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 input int input int datetime int tiks_before=500; // number of ticks till termination pips_to_go=15; seconds_st=50; launch_time; tick_counter=0; | // distance in pips // number of seconds given to the Expert Advisor
//--- globals
//+------------------------------------------------------------------+ //| 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; | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
364
Common Functions
MqlTick double //--SymbolInfoTick(_Symbol,tick); tick_counter++; if(first_bid==0.0) { launch_time=tick.time; first_bid=tick.bid; Print("first_bid =",first_bid); return; } //--- price distance in pips distance=(tick.bid-first_bid)/_Point; //--- show a notification to track the EA operation string comm="From the moment of start:\r\n\x25CF elapsed seconds: "+ IntegerToString(tick.time-launch_time)+" ;"+ "\r\n\x25CF ticks received: "+(string)tick_counter+" ;"+ "\r\n\x25CF price went in points: "+StringFormat("%G",distance); Comment(comm); //--- section for checking condition to close the terminal if(tick_counter>=tiks_before) TerminalClose(0); if(distance>pips_to_go) TerminalClose(1); TerminalClose(-1); TerminalClose(100); //--} // go up by the number of pips equal to pips_to_go // go down by the number of pips equal to pips_to_go // termination by timeout if(distance<-pips_to_go) if(tick.time-launch_time>seconds_st) // exit by tick counter tick; distance;
365
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.
366
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.
367
Array Functions
ArrayCopy ArrayFree
ArrayGetAsSeries ArrayInitialize
ArrayResize
Sets the new size in the first dimension of the array Sets the direction of array indexing Returns the number of elements in the array Sorting of numeric arrays by the first dimension
368
Array Functions
ArrayBsearch
The function searches for a specified value in a one-dimension numeric array. For searching in an array of double type
int ArrayBsearch( double double ); array[], searched_value // array for search // what is searched for
Parameters array[] [in] Numeric array for search. searched_value [in] Value for search.
369
Array Functions
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.
370
Array Functions
ArrayCopy
It copies an array into another one.
int ArrayCopy( void dst_array[], void src_array[], int int int ); dst_start=0, src_start=0, cnt=WHOLE_ARRAY // destination array // source array // index starting from which write into destination array // first index of a source array // number of elements
Parameters dst_array[] [out] Destination array src_array[] [in] Source array dst_start=0 [in] Starting index fro the destination array. By default, start index is 0. src_start=0 [in] Starting index for the source array. By default, start index is 0. cnt=-1 [in] Number of elements that should be copied. By default, the whole array is copied (cnt=WHOLE_ARRAY). Return Value It returns the number of copied elements. Note If cnt<0 or cnt>src_size-src_start, all the remaining array part is copied. Arrays are copied from left to right. For series arrays, the starting position is correctly defined adjusted for copying from left to right. If an array is copied to itself, the result is undefined. If arrays are of different types, during copying it tries to transform each element of a source array into the type of the destination array. A string array can be copied into a string array only. Array of classes and structures containing objects that require initialization aren't copied. An array of structures can be copied into an array of the same type only.
371
Array Functions
ArrayFree
It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.
void ArrayFree( void array[] ); // array
372
Array Functions
ArrayGetAsSeries
It checks direction of an array index.
bool ArrayGetAsSeries( void array ); // array for checking
Parameters array [in] Checked array. Return Value Returns true, if the specified array has the AS_SERIES flag set, i.e. access to the array is performed back to front as in timeseries. A timeseries differs from a usual array in that the indexing of timeseries elements is performed from its end to beginning (from the newest data to old). Note To check whether an array belongs to timeseries, use the ArrayIsSeries() function. Arrays of price data passed as input parameters into the OnCalculate() function do not obligatorily have the indexing direction the same as in timeseries. The necessary indexing direction can be set using the ArraySetAsSeries() function. See also Access to timeseries, ArraySetAsSeries
373
Array Functions
ArrayInitialize
The function initializes a numeric array by a preset value.
void ArrayInitialize( double array[], double value ); // initialized array // value that will be set
Parameters array[] [out] Numeric array that should be initialized. value [in] New value that should be set to all array elements. Return Value No return value. Note The ArrayResize() function allows to set size of an array with a reserve for further expansion without the physical relocation of memory. It is implemented for the better performance, because the operations of memory relocation are reasonably slow. Initialization of the array using ArrayInitialize(array, init_val) doesn't mean the initialization with the same value of reserve elements allocated for this array. At further expanding of the array using the ArrayResize() function, the elements will be added at the end of the array, their values will be undefined and in most cases will not be equal to init_value. Example:
void OnStart() { //--- dynamic array double array[]; //--- let's set the array size for 100 elements and reserve a buffer for another 10 elements ArrayResize(array,100,10); //--- initialize the array elements with EMPTY_VALUE=DBL_MAX value ArrayInitialize(array,EMPTY_VALUE); Print("Values of 10 last elements after initialization"); for(int i=90;i<100;i++) printf("array[%d] = %G",i,array[i]); //--- expand the array by 5 elements ArrayResize(array,105); Print("Values of 10 last elements after ArrayResize(array,105)"); //--- values of 5 last elements are obtained from reserve buffer for(int i=95;i<105;i++) printf("array[%d] = %G",i,array[i]); }
374
Array Functions
ArrayIsDynamic
The function checks whether an array is dynamic.
bool ArrayIsDynamic( void array[] ); // checked array
Parameters array[] [in] Checked array. Return Value It returns true if the selected array is dynamic, otherwise it returns false. See also Access to timeseries and indicators
375
Array Functions
ArrayIsSeries
The function checks whether an array is a timeseries.
bool ArrayIsSeries( void array[] ); // checked array
Parameters array[] [in] Checked array. Return Value It returns true, if a checked array is an array timeseries, otherwise it returns false. Arrays passed as a parameter to the OnCalculate() function must be checked for the order of accessing the array elements by ArrayGetAsSeries(). Example:
#property indicator_chart_window #property indicator_buffers 1 #property indicator_plots //---- plot Label1 #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- indicator buffers double Label1Buffer[]; | //+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA); //--} //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "Label1" DRAW_LINE Red STYLE_SOLID 1 1
376
Array Functions
const long &tick_volume[], const long &volume[], const int &spread[]) { //--if(ArrayIsSeries(open)) { Print("open[] is timeseries"); } else { { Print("open[] is not timeseries!!!"); } } //--- return value of prev_calculated for next call return(rates_total); }
377
Array Functions
ArrayMaximum
The function searches a maximal element in a one-dimension numeric array.
int ArrayMaximum( double array[], int int ); start=0 count=WHOLE_ARRAY, // array for search // index to start checking with // number of checked elements
Parameters array[] [in] A numeric array, in which search is made. start=0 [in] Index to start checking with. count=WHOLE_ARRAY [in] Number of elements for search. By default, searches in the entire array (cnt=WHOLE_ARRAY ). Return Value The function returns an index of a found element taking into account the array serial. In case of failure it returns -1.
378
Array Functions
ArrayMinimum
The function searches a minimal element in a one-dimension numeric array.
int ArrayMinimum( double array[], int int ); start=0 count=WHOLE_ARRAY, // array for search // index to start checking with // number of checked elements
Parameters array[] [in] A numeric array, in which search is made. start=0 [in] Index to start checking with. count=WHOLE_ARRAY [in] Number of elements for search. By default, searches in the entire array (cnt=WHOLE_ARRAY ). Return Value The function returns an index of a found element taking into account the array serial. In case of failure it returns -1.
379
Array Functions
ArrayRange
The function returns the number of elements in a selected array dimension.
int ArrayRange( void array[], int ); rank_index // array for check // number of dimension
Parameters array[] [in] Checked array. rank_index [in] Index of dimension. Return Value Number of elements in a selected array dimension. Note Since indexes are zero-based, the size of dimension is 1 greater than the largest index.
380
Array Functions
ArrayResize
The function sets a new size for the first dimension
int ArrayResize( void array[], int int ); new_size, allocated_size=0 // array passed by reference // new array size // reserve size value (excess)
Parameters array[] [out] Array for changing sizes. new_size [in] New size for the first dimension. allocated_size=0 [in] Distributed size to get reserve. Return Value If executed successfully, it returns count of all elements contained in the array after resizing, otherwise, returns -1, and array is not resized. Note During memory allocation the allocated_size parameter is taken into account. If this parameter is specified, it sets the size of additional memory for the array. Re-calls of ArrayResize do not result in physical re-allocation of memory, only the first array dimension is resized within the reserved memory. The function can be applied only to dynamic arrays. Please note that you can't change the size for dynamic arrays set as indicator buffers by the function SetIndexBuffer(). For indicator buffers, all operations of size changes are performed by the executing sub-system of the terminal. See also ArrayInitialize
381
Array Functions
ArraySetAsSeries
The function sets the AS_SERIES flag to a selected object of a dynamic array, and elements will be indexed like in timeseries.
bool ArraySetAsSeries( void array[], bool set ); // array by reference // true denotes reverse order of indexing
Parameters array[] [in][out] Numeric array to set. set [in] Array indexing direction. Return Value The function returns true on success, otherwise - false. Note The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays (arrays, whose size in square brackets is preset already on the compilation stage). Indexing in timeseries differs from a common array in that the elements of timeseries are indexed from the end toeards the beginning (from the newest to oldest data). Example: Indicator that shows bar number
//+------------------------------------------------------------------+ //| //| //| BarNumber.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
382
Array Functions
#property link #property version "http://www.mql5.com" "1.00"
#property indicator_chart_window #property indicator_buffers 1 #property indicator_plots //---- plot Numeration #property indicator_label1 #property indicator_type1 #property indicator_color1 //--- indicator buffers double NumerationBuffer[]; | //+------------------------------------------------------------------+ //| Custom indicator initialization function int OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,NumerationBuffer,INDICATOR_DATA); //--- set indexing for the buffer like in timeseries ArraySetAsSeries(NumerationBuffer,true); //--- set accuracy of showing in DataWindow IndicatorSetInteger(INDICATOR_DIGITS,0); //--- how the name of the indicator arry is displayed in DataWindow PlotIndexSetString(0,PLOT_LABEL,"Bar #"); //--return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--we'll store the time of the current zero bar opening static datetime currentBarTimeOpen=0; //--- revert access to array time[] - do it like in timeseries ArraySetAsSeries(time,true); //--- If time of zero bar differs from the stored one if(currentBarTimeOpen!=time[0]) { | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "Numeration" DRAW_LINE CLR_NONE 1
383
Array Functions
//--- enumerate all bars fromthe current to the chart depth for(int i=rates_total-1;i>=0;i--) NumerationBuffer[i]=i; currentBarTimeOpen=time[0]; } //--- return value of prev_calculated for next call return(rates_total); }
384
Array Functions
ArraySize
The function returns the number of elements of a selected array.
int ArraySize( void array[] ); // checked array
Parameters array[] [in] Array of any type. Return Value Value of int type. Note For a one-dimensional array, the value to be returned by the ArraySize is equal to that of ArrayRange(array,0).
385
Array Functions
ArraySort
The function sorts numeric arrays in ascending order from left to right.
bool ArraySort( number& array[] ); // array for sorting
Parameters array[] [in][out] Numeric array for sorting. Return Value The function returns true on success, otherwise - false. Note An array marked by the AS_SERIES flag is sorted in descending order.
386
Conversion Functions
Conversion Functions
This is a group of functions that provide conversion of data from one format into another. The NormalizeDouble() function must be specially noted as it provides the necessary accuracy of the price presentation. In trading operations, no unnormalized prices may be used if their accuracy even a digit exceeds that required by the trade server. Function CharToString Action Converting a symbol code into a one-character string Converting a numeric value to a text line with a specified accuracy Converting an enumeration value of any type to string Rounding of a floating point number to a specified accuracy Converting a string containing a symbol representation of number into number of double type Converting a string containing a symbol representation of number into number of int type Converting a string containing time or date in "yyyy.mm.dd [hh:mi]" format into datetime type Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy. mm.dd hh:mi" format Converting int into a string of preset length Converting symbol code (unicode) into onesymbol string Copying array part into a string Symbol-wise copying a string to a selected part of array of ushort type Converting symbol code (ansi) into one-symbol array Symbol-wise copying a string converted from Unicode to ANSI, to a selected place of array of uchar type Converting color value into string as "R,G,B"
DoubleToString
EnumToString
NormalizeDouble
StringToDouble
StringToInteger
StringToTime
TimeToString
IntegerToString ShortToString
ShortArrayToString StringToShortArray
CharArrayToString
StringToCharArray
ColorToString
387
Conversion Functions
StringToColor
Converting "R,G,B" string or string with color name into color type value Converting number into string according to preset format
StringFormat
388
Conversion Functions
CharToString
Converting a symbol code into a one-character string.
string CharToString( uchar char_code ); // numeric code of symbol
Parameters char_code [in] Code of ANSI symbol. Return Value String with a ANSI symbol.
389
Conversion Functions
CharArrayToString
It copies and converts part of array of uchar type into a returned string.
string CharArrayToString( uchar array[], int int uint ); start=0, count=-1 codepage=CP_ACP // array // starting position in the array // number of sumbols // code page
Parameters array[] [in] Array of uchar type. start=0 [in] Position from which copying starts. by default 0 is used. count=-1 [in] Number of array elements for copying. Defines the length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0. codepage=CP_ACP [in] The value of the code page. For the most-used code pages provide appropriate constants. Return Value String. See also Use of a Codepage
390
Conversion Functions
ColorToString
It converts color value into string of "R,G,B" form.
string ColorToString( color color_value, bool ); color_name // color value // show color name or not
Parameters color_value [in] Color value in color type variable. color_name [in] Sign of the necessity to return color name, if color name is identical to one of predefined color constants. Return Value String presentation of color as "R,G,B", where R, G and B are decimal constants from 0 to 255 converted into a string. If the color_name=true parameter is set, it will try to convert color value into color name. Example:
string clr=ColorToString(C'0,255,0'); // green color Print(clr); clr=ColorToString(C'0,255,0',true); Print(clr); // get color constant
391
Conversion Functions
DoubleToString
Converting numeric value into text string.
string DoubleToString( double value, int ); digits=8 // number // number of digits after decimal point
Parameters value [in] Value with a floating point. digits [in] Accuracy format. If the digits value is in the range between 0 and 16, a string presentation of a number with the specified number of digits after the point will be obtained. If the digits value is in the range between -1 and -16, a string representation of a number in the scientific format with the specified number of digits after the decimal point will be obtained. In all other cases the string value will contain 8 digits after the decimal point. Return Value String containing a symbol representation of a number with the specified accuracy. Example:
Print("DoubleToString(120.0 + M_PI) : ",DoubleToString(120.0+M_PI)); Print("DoubleToString(120.0 + M_PI,16) : ",DoubleToString(120.0+M_PI,16)); Print("DoubleToString(120.0 + M_PI,-16) : ",DoubleToString(120.0+M_PI,-16)); Print("DoubleToString(120.0 + M_PI,-1) : ",DoubleToString(120.0+M_PI,-1)); Print("DoubleToString(120.0 + M_PI,-20) : ",DoubleToString(120.0+M_PI,-20));
392
Conversion Functions
EnumToString
Converting an enumeration value of any type to a text form.
string EnumToString( any_enum value ); // any type enumeration value
Parameters value [in] Any type enumeration value. Return Value A string with a text representation of the enumeration. To get the error message call the GetLastError() function. Note The function can set the following error values in the _LastError variable: ERR_INTERNAL_ERROR error of the execution environment ERR_NOT_ENOUGH_MEMORY not enough memory to complete the operation ERR_INVALID_PARAMETER can't allow the name of the enumeration value Example:
393
Conversion Functions
enum interval // enumeration of named constants { month=1, // one-month interval two_months, // two months quarter, // three months - a quarter halfyear=6, // half a year year=12, // a year - 12 months }; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- set the time interval equal to one month interval period=month; Print(EnumToString(period)+"="+IntegerToString(period)); //--- set the time interval equal to a quarter (three months) period=quarter; Print(EnumToString(period)+"="+IntegerToString(period)); //--- set the time interval equal to one year (12 months)) period=year; Print(EnumToString(period)+"="+IntegerToString(period)); //--- check how the order type is shown ENUM_ORDER_TYPE type=ORDER_TYPE_BUY; Print(EnumToString(type)+"="+IntegerToString(type)); //--- check how incorrect values are shown type=WRONG_VALUE; Print(EnumToString(type)+"="+IntegerToString(type)); // Result: // month=1 // quarter=3 // year=12 // ORDER_TYPE_BUY=0 // ENUM_ORDER_TYPE::-1=-1 }
394
Conversion Functions
IntegerToString
This function converting value of integer type into a string of a specified length and returns the obtained string.
string IntegerToString( long int number, str_len=0, // number // length of result string // filler
Parameters number [in] Number for conversion. str_len=0 [in] String length. If the resulting string length is larger than the specified one, the string is not cut off. If it is smaller, filler symbols will be added to the left. fill_symbol=' ' [in] Filler symbol. By default it is a space. Return Value String.
395
Conversion Functions
ShortToString
It converts the symbol code (unicode) into one-symbol string and returns resulting string.
string ShortToString( ushort symbol_code ); // symbol
Parameters symbol_code [in] Symbol code. Instead of a symbol code you can use literal string containing a symbol or a literal string with 2-byte hexadecimal code corresponding to the symbol from the Unicode table. Return Value String.
396
Conversion Functions
ShortArrayToString
It copies part of array into a returned string.
string ShortArrayToString( ushort array[], int int ); start=0, count=-1 // array // starting position in the array // number of symbols
Parameters array[] [in] Array of ushort type (analog of wchar_t type). start=0 [in] Position, from which copying starts, Default - 0. count=-1 [in] Number of array elements to copy. Defines the length of a resulting string. Default value is 1, which means copying up to the array end, or till terminal 0. Return Value String.
397
Conversion Functions
TimeToString
Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy.mm.dd hh:mi" format.
string TimeToString( datetime value, int ); mode=TIME_DATE|TIME_MINUTES // number // output format
Parameters value [in] Time in seconds from 00:00 1970/01/01. mode=TIME_DATE|TIME_MINUTES [in] Additional data input mode. Can be one or combined flag: TIME_DATE gets result as "yyyy. mm.dd", TIME_MINUTES gets result as "hh:mi", TIME_SECONDS gets results as "hh:mi:ss". Return Value String.
398
Conversion Functions
NormalizeDouble
Rounding floating point number to a specified accuracy.
double NormalizeDouble( double value, int ); digits // normalized number // number of digits after decimal point
Parameters value [in] Value with a floating point. digits [in] Accuracy format, number of digits after point (0-8). Return Value Value of double type with preset accuracy. Note Calculated values of StopLoss, TakeProfit, and values of open prices for pending orders must be normalized with the accuracy, the value of which can be obtained by Digits(). Example:
double pi=M_PI; Print("pi = ",DoubleToString(pi,16)); double pi_3=NormalizeDouble(M_PI,3); Print("NormalizeDouble(pi,3) = ",DoubleToString(pi_3,16)) ; double pi_8=NormalizeDouble(M_PI,8); Print("NormalizeDouble(pi,8) = ",DoubleToString(pi_8,16)); double pi_0=NormalizeDouble(M_PI,0); Print("NormalizeDouble(pi,0) = ",DoubleToString(pi_0,16)); /* Result: pi= 3.1415926535897931 NormalizeDouble(pi,3)= 3.1419999999999999 NormalizeDouble(pi,8)= 3.1415926499999998 NormalizeDouble(pi,0)= 3.0000000000000000 */
399
Conversion Functions
StringToCharArray
Symbol-wise copies a string converted from Unicode to ANSI, to a selected place of array of uchar type. It returns the number of copied elements.
int StringToCharArray( string text_string, uchar& int int uint ); array[], start=0, count=-1 codepage=CP_ACP // source string // array // starting position in the array // number of symbols // code page
Parameters text_string [in] String to copy. array[] [out] Array of uchar type. start=0 [in] Position from which copying starts. Default - 0. count=-1 [in] Number of array elements to copy. Defines length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0. Terminal 0 will also be copied to the recipient array, in this case the size of a dynamic array can be increased if necessary to the size of the string. If the size of the dynamic array exceeds the length of the line, the size of the array will not be reduced. codepage=CP_ACP [in] The value of the code page. For the most-used code pages provide appropriate constants. Return Value Number of copied elements. See also Use of a Codepage
400
Conversion Functions
StringToColor
Converting "R,G,B" string or string with color name into color type value.
color StringToColor( string color_string ); // string representation of color
Parameters color_string [in] String representation of a color of "R,G,B" type or name of one of predefined Web-colors. Return Value Color value. Example:
color str_color=StringToColor("0,127,0"); Print(str_color); Print((string)str_color); //--- change color a little str_color=StringToColor("0,128,0"); Print(str_color); Print((string)str_color);
401
Conversion Functions
StringToDouble
The function converts string containing a symbol representation of number into number of double type.
double StringToDouble( string value ); // string
Parameters value [in] String containing a symbol representation of a number. Return Value Value of double type.
402
Conversion Functions
StringToInteger
The function converts string containing a symbol representation of number into number of int (integer) type.
long StringToInteger( string value ); // string
Parameters value [in] String containing a number. Return Value Value of long type.
403
Conversion Functions
StringToShortArray
The function symbol-wise copies a string into a specified place of an array of ushort type. It returns the number of copied elements.
int StringToShortArray( string text_string, ushort& array[], int int ); start=0, count=-1 // source string // array // starting position in the array // number of symbols
Parameters text_string [in] String to copy array[] [out] Array of ushort type (analog of wchar_t type). start=0 [in] Position, from which copying starts. Default - 0. count=-1 [in] Number of array elements to copy. Defines length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0.Terminal 0 will also be copied to the recipient array, in this case the size of a dynamic array can be increased if necessary to the size of the string. If the size of the dynamic array exceeds the length of the line, the size of the array will not be reduced. Return Value Number of copied elements.
404
Conversion Functions
StringToTime
The function converts a string containing time or date in "yyyy.mm.dd [hh:mi]" format into datetime type.
datetime StringToTime( string value ); // date string
Parameters value [in] String in " yyyy.mm.dd hh:mi " format. Return Value Value of datetime type containing total number of seconds that elapsed since 01.01.1970.
405
Conversion Functions
StringFormat
The function formats obtained parameters and returns a string.
string StringFormat( string format, ... ); ... // string with format description // parameters
Parameters format [in] String containing method of formatting. Formatting rules are the same as for the PrintFormat function. ... [in] Parameters, separated by a comma. Return Value String.
406
Math Functions
Mathematical Functions
A set of mathematical and trigonometric functions. Function MathAbs Action Returns absolute value specified numeric value (modulus) of the
Returns the arc cosine of x in radians Returns the arc sine of x in radians Returns the arc tangent of x in radians Returns integer numeric value closest from above Returns the cosine of a number Returns exponent of a number Returns integer numeric value closest from below Returns natural logarithm Returns the maximal value of the two numeric values Returns the minimal value of the two numeric values Returns the real remainder after the division of two numbers Raises the base to the specified power Returns a pseudorandom value within the range of 0 to 32767 Rounds of a value to the nearest integer Returns the sine of a number Returns a square root Sets the starting point for generating a series of pseudorandom integers Returns the tangent of a number Checks the correctness of a real number
MathLog MathMax
MathMin
MathMod
MathPow MathRand
MathTan MathIsValidNumber
407
Math Functions
MathAbs
The function returns the absolute value (modulus) of the specified numeric value.
double MathAbs( double value ); // numeric value
Parameters value [in] Numeric value. Return Value Value of double type more than or equal to zero. Note Instead the MathAbs() function you can use fabs().
408
Math Functions
MathArccos
The function returns the arccosine of x within the range 0 to
double MathArccos( double val ); // -1<val<1
in radians.
Parameters val [in] The val value between -1 and 1, the arc cosine of which is to be calculated. Return Value Arc cosine of a number in radians. If val is less than -1 or more than 1, the function returns NaN (indeterminate value). Note Instead of the MathArccos() function you can use acos(). See also Real types (double, float)
409
Math Functions
MathArcsin
The function the arc sine of x within the range of - /2 to /2 radians.
double MathArcsin( double val ); // -1<value<1
Parameters val [in] The val value between -1 and 1, the arc sine of which is to be calculated. Return Value Arc sine of the val number in radians within the range of - /2 to or more than 1, the function returns NaN (indeterminate value). Note Instead of the MathArcsin() function you can use asin(). See also Real types (double, float) /2 radians. If val is less than -1
410
Math Functions
MathArctan
The function returns the arc tangent of x. If x is equal to 0, the function returns 0.
double MathArctan( double value ); // tangent
Parameters value [in] A number representing a tangent. Return Value MathArctan returns a value within the range of - /2 to /2 radians. Note Instead of the MathArctan() function you can use atan().
411
Math Functions
MathCeil
The function returns integer numeric value closest from above.
double MathCeil( double val ); // number
Parameters val [in] Numeric value. Return Value Numeric value representing the smallest integer that exceeds or equals to val. Note instead of the MathCeil() function you can use ceil().
412
Math Functions
MathCos
The function returns the cosine of an angle.
double MathCos( double value ); // number
Parameters value [in] Angle in radians. Return Value Value of double type within the range of -1 to 1. Note Instead of MathCos() you can use cos().
413
Math Functions
MathExp
The function returns the value of e raised to the power of d.
double MathExp( double value ); // power for the number e
Parameters value [in] A number specifying the power. Return Value A number of double type. At overflow, the function returns INF (infinity), in case of order loss MathExp returns 0. Note Instead of MathExp() you can use exp(). See also Real types (double, float)
414
Math Functions
MathFloor
The function returns integer numeric value closest from below.
double MathFloor( double val ); // number
Parameters val [in] Numeric value. Return Value A numeric value representing the largest integer that is less than or equal to val. Note Instead of MathFloor() you can use floor().
415
Math Functions
MathLog
The function returns a natural logarithm.
double MathLog( double val ); // value to take the logarithm
Parameters val [in] Value logarithm of which is to be found. Return Value The natural logarithm of val in case of success. If val is negative, the function returns NaN (undetermined value). If val is equal to 0, the function returns INF (infinity). Note Instead of MathLog() you can use log(). See also Real types (double, float)
416
Math Functions
MathLog
Returns the logarithm of a number by base 10.
double MathLog10( double val ); // number to take logarithm
Parameters val [in] Numeric value the common logarithm of which is to be calculated. Return Value The common logarithm in case of success. If val is negative, the function returns NaN (undetermined value). If val is equal to 0, the function returns INF (infinity). Note Instead of MathLog10() you can use log10(). See also Real types (double, float)
417
Math Functions
MathMax
The function returns the maximal value of two values.
double MathMax( double value1, double value2 ); // first value // second value
Parameters value1 [in] First numeric value. value2 [in] Second numeric value. Return Value The largest of the two values. Note Instead of MathMax() you can use fmax(). Functions fmax(), fmin(), MathMax(), MathMin() can work with integer types without typecasting them to the type of double. If parameters of different types are passed into a function, the parameter of the minor type is automatically cast to the major type. The type of the return value corresponds to the major type. If data of the same type are passed, no casting is performed.
418
Math Functions
MathMin
The function returns the minimal value of two values.
double MathMin( double value1, double value2 ); // first value // second value
Parameters value1 [in] First numeric value. value2 [in] Second numeric value. Return Value The smallest of the two values. Note Instead of MathMin() you can use fmin(). Functions fmax(), fmin(), MathMax(), MathMin() can work with integer types without typecasting them to the type of double. If parameters of different types are passed into a function, the parameter of the minor type is automatically cast to the major type. The type of the return value corresponds to the major type. If data of the same type are passed, no casting is performed.
419
Math Functions
MathMod
The function returns the real remainder of division of two numbers.
double MathMod( double value, double value2 ); // divident value // divisor value
Parameters value [in] Dividend value. value2 [in] Divisor value. Return Value The MathMod function calsulates the real value of f of val / y such that val = i * y + f , where i is an integer, f has the same sign as val, and the absolute value of f is less than the absolute value of y. Note Instead of MathMod() you can use fmod().
420
Math Functions
MathPow
The function raises a base to a specified power.
double MathPow( double base, double exponent ); // base // exponent value
Parameters base [in] Base. exponent [in] Exponent value. Return Value Value of base raised to the specified power. Note Instead of MathPow() you can use pow().
421
Math Functions
MathRand
Returns a pseudorandom integer within the range of 0 to 32767.
int MathRand();
Return Value Integer value within the range of 0 to 32767. Note Before the first call of the function, it's necessary to call MathSrand to set the generator of pseudorandom numbers to the initial state. Note Instead of MathRand() you can use rand().
422
Math Functions
MathRound
The function returns a value rounded off to the nearest integer of the specified numeric value.
double MathRound( double value ); // value to be rounded
Parameters value [in] Numeric value before rounding. Return Value Value rounded till to the nearest integer. Note Instead of MathRound() you can use round().
423
Math Functions
MathSin
Returns the sine of a specified angle.
double MathSin( double value ); // argument in radians
Parameters value [in] Angle in radians. Return Value Sine of an angle measured in radians. Returns value within the range of -1 to 1. Note Instead of MathSin() you can use sin().
424
Math Functions
MathSqrt
Returns the square root of a number.
double MathSqrt( double value ); // positive number
Parameters value [in] Positive numeric value. Return Value Square root of value. Of value is negative, MathSqrt returns NaN (indeterminate value). Note Instead of MathSqrt() you can use sqrt(). See also Real types (double, float)
425
Math Functions
MathSrand
Sets the starting point for generating a series of pseudorandom integers.
void MathSrand( int seed ); // initializing number
Parameters seed [in] Starting number for the row of random numbers. Return Value No return value. Note To re-initialize the generator (i.e. set generator into previous initial state), it's necessary to use value 1 as the initializing parameter. Any other value for the initial number sets the generator to the random starting point. MathRand returns pseudorandom numbers that are generated in succession. Calling MathRand before any call to MathSrand generates the same sequence as calling MathSrand with parameter 1. Instead of MathSrand() you can use srand().
426
Math Functions
MathTan
The function returns a tangent of a number.
double MathTan( double rad ); // argument in radians
Parameters rad [in] Angle in radians. Return Value Tangent of rad. If rad is greater than or equal to 263, or less than or equal to -263, a loss of significance in the result occurs, in which case the function returns an indefinite. Note Instead of MathTan() you can use tan(). See also Real types (double, float)
427
Math Functions
MathIsValidNumber
It checks the correctness of a real number.
bool MathIsValidNumber( double number ); // number to check
Parameters number [in] Checked numeric value. Return Value It returns true, if the checked value is an acceptable real number. If the checked value is a plus or minus infinity, or "not a number" (NaN), the function returns false. Example:
double abnormal=MathArcsin(2.0); if(!MathIsValidNumber(abnormal)) Print("Attention! MathArcsin(2.0) = ",abnormal);
428
String Functions
String Functions
This is a group of functions intended for working with data of the string type. Function StringAdd StringBufferLen Action Adds a string at the place of indicated substring Returns the size of buffer distributed for the string Compares two strings and returns 1 if the first string is greater than the second; 0 - if the strings are equal; -1 (minus 1) - if the first string is less than the second one Forms a string of parameters passed Fills out a specified string by selected symbols Search for a substring in a string Returns the value of a number located in the specified string position Initializes string by specified symbols and provides the specified string length Returns the number of symbols in a string Replaces all the found substrings of a string by a set sequence of symbols. Returns a copy of a string with a changed value of a symbol in a specified position Extracts a substring from a text string starting from a specified position Transforms all symbols of a selected string to lowercase by location Transforms all symbols of a selected string into capitals by location Cuts line feed characters, spaces and tabs in the left part of the string Cuts line feed characters, spaces and tabs in the right part of the string
StringCompare
StringInit
StringLen StringReplace
StringSetCharacter
StringSubstr
StringToLower
StringToUpper
StringTrimLeft
StringTrimRight
429
String Functions
StringAdd
The function adds a substring to the end of a string.
bool StringAdd( string& string_var, string ); add_substring // string, to which we add // string, which is added
Parameters string_var [in][out] String, to which another one is added. add_substring [in] String that is added ti the end of a source string. Return Value In case of success returns true, otherwise false. In order to get an error code, the GetLastError() function should be called. Note The StringAdd() add functions is faster and memory saving, as compared to binding strings using addition operations. Example:
void OnStart() { string a="a",b="b",c; //--- first method int start=GetTickCount(),stop; long i; for(i=0;i<length;i++) { c=a+b; } stop=GetTickCount(); Print("time for 'c = a + b' = ",(stop-start)," milliseconds, i = ",i); //--- second method start=GetTickCount(); for(i=0;i<length;i++) { StringAdd(a,b); } stop=GetTickCount(); Print("time for 'StringAdd(a,b)' = ",(stop-start)," milliseconds, i = ",i); //--- third method
430
String Functions
start=GetTickCount(); a="a"; // re-initialize variable a for(i=0;i<length;i++) { int k=StringConcatenate(c,a,b); } stop=GetTickCount(); Print("time for 'StringConcatenate(c,a,b)' = ",(stop-start)," milliseconds, i = ",i); }
431
String Functions
StringBufferLen
The function returns the size of buffer distributed for the string.
int StringBufferLen( string string_var ) // string
Parameters string_var [in] String. Return Value The value 0 means that the string is constant and buffer size can't be changed. -1 means that the string belongs to the client terminal, and modification of the buffer contents can have indeterminate results. Note Minimal buffer size is equal to 16. Example:
void OnStart() { long length=1000; string a="a",b="b"; //--long i; Print("before: StringBufferLen(a) = ",StringBufferLen(a), " { StringAdd(a,b); } Print("after: StringBufferLen(a) = ",StringBufferLen(a), " } StringLen(a) = ",StringLen(a)); StringLen(a) = ",StringLen(a)); for(i=0;i<length;i++)
432
String Functions
StringCompare
The function compares two strings and returns the comparison result in form of an integer.
int StringCompare( const string& string1, const string& string2, bool ); case_sensitive=true // the first string in the comparison // the second string in the comparison // case sensitivity mode selection for the comparison
Parameters string1 [in] The first string. string2 [in] The second string. case_sensitive=true [in] Case sensitivity mode selection. If it is true, then "A">"a". If it is false, then "A"="a". By default the value is equal to true. Return Value -1 (minus one), if string1<string2 0 (zero), if string1=string2 1 (one), if string1>string2 Note The strings are compared symbol by symbol, the symbols are compared in the alphabetic order in accordance with the current code page. Example:
433
String Functions
void OnStart() { //--- what is larger - apple or home? string s1="Apple"; string s2="home"; //--- compare case sensitive int result1=StringCompare(s1,s2); if(result1>0) PrintFormat("Case sensitive comparison: %s > %s",s1,s2); else { if(result1<0)PrintFormat("Case sensitive comparison: %s < %s",s1,s2); else PrintFormat("Case sensitive comparison: %s = %s",s1,s2); } //--- compare case-insensitive int result2=StringCompare(s1,s2,false); if(result2>0) PrintFormat("Case insensitive comparison: %s > %s",s1,s2); else { if(result2<0)PrintFormat("Case insensitive comparison: %s < %s",s1,s2); else PrintFormat("Case insensitive comparison: %s = %s",s1,s2); } /* Result: Case-sensitive comparison: Apple < home Case insensitive comparison: Apple < home */ }
See also String Type, CharToString(), ShortToString(), StringToCharArray(), StringToShortArray(), StringGetCharacter(), Use of a Codepage
434
String Functions
StringConcatenate
The function forms a string of passed parameters and returns the size of the formed string. Parameters can be of any type. Number of parameters can't be less than 2 or more than 64.
int StringConcatenate( string& string_var, void argument1 void argument2 ... ); // string to form // first parameter of any simple type // second parameter of any simple type // next parameter of any simple type
Parameters string_var [in][out] String that will be formed as a result of concatenation. argumentN [in] Any comma separated values. From 2 to 63 parameters of any simple type. Return Value Returns the string length, formed by concatenation of parameters transformed into string type. Parameters are transformed into strings according to the sane rules as in Print() and Comment(). Note StringConcatenate() is faster and memory saving, as compared to binding strings using addition operations, because they don't use temporary variables of string type.
435
String Functions
StringFill
It fills out a selected string by specified symbols.
bool StringFill( string& ushort ); string_var, character // string to fill // symbol that will fill the string
Parameters string_var [in][out] String, that will be filled out by the selected symbol. character [in] Symbol, by which the string will be filled out. Return Value In case of success returns true, otherwise - false. To get the error code call GetLastError(). Note Filling out a string at place means that symbols are inserted directly to the string without transitional operations of new string creation or copying. This allows to save the operation time. Example:
void OnStart() { string str; StringInit(str,20,'_'); Print("str = ",str); StringFill(str,0); Print("str = ",str,": StringBufferLen(str) = ", StringBufferLen(str)); } // Result // // // str = ____________________ str = : StringBufferLen(str) = 20
436
String Functions
StringFind
Search for a substring in a string.
int StringFind( string string_value, string match_substring, int ); start_pos=0 // string in which search is made // what is searched // from what position search starts
Parameters string_value [in] String, in which search is made. match_substring [in] Searched substring. start_pos=0 [in] Position in the string from which search is started. Return Value Returns position number in a string, from which the searched substring starts, or -1, if the substring is not found.
437
String Functions
StringGetCharacter
Returns value of a symbol, located in the specified position of a string.
ushort StringGetCharacter( string string_value, int ); pos // string // symbol position in the string
Parameters string_value [in] String. pos [in] Position of a symbol in the string. Can be from 0 to StringLen(text) -1. Return Value Symbol code or 0 in case of an error. To get the error code call GetLastError().
438
String Functions
StringInit
Initializes a string by specified symbols and provides the specified string size.
bool StringInit( string& int ushort ); string_var, new_len=0, character=0 // string to initialize // required string length after initialization // symbol, by which the string will be filled
Parameters string_var [in][out] String that should be initialized and deinitialized. new_len=0 [in] String length after initialization. If length=0, it deinitializes the string, i.e. the string buffer is cleared and the buffer address is zeroed. character=0 [in] Symbol to fill the string. Return Value In case of success returns true, otherwise - false. To get the error code call GetLastError(). Note If character=0 and the length new_len>0, the buffer of the string of indicated length will be distributed and filled by zeroes. The string length will be equal to zero, because the whole buffer is filled out by string terminators. Example:
void OnStart() { //--string str; StringInit(str,200,0); Print("str = ",str,": StringBufferLen(str) = ", StringBufferLen(str)," } /* */ Result StringLen(str) = 0 str = : StringBufferLen(str) = 200 StringLen(str) = ",StringLen(str));
439
String Functions
StringLen
Returns the number of symbols in a string.
int StringLen( string string_value ); // string
Parameters string_value [in] String to calculate length. Return Value Number of symbols in a string without the ending zero.
440
String Functions
StringReplace
It replaces all the found substrings of a string by a set sequence of symbols.
int StringReplace( string& const string const string ); str, find, replacement // the string in which substrings will be replaced // the searched substring // the substring that will be inserted to the found positions
Parameters str [in][out] The string in which you are going to replace substrings. find [in] The desired substring to replace. replacement [in] The string that will be inserted instead of the found one. Return Value The function returns the number of replacements in case of success, otherwise -1. To get an error code call the GetLastError() function. Note If the function has run successfully but no replacements have been made (the substring to replace was not found), it returns 0. The error can result from incorrect str or find parameters (empty or non-initialized string, see StringInit() ). Besides, the error occurs if there is not enough memory to complete the replacement. Example:
string text="The quick brown fox jumped over the lazy dog."; int replaced=StringReplace(text,"quick","slow"); replaced+=StringReplace(text,"brown","black"); replaced+=StringReplace(text,"fox","bear"); Print("Replaced: ", replaced,". Result=",text); // // // Result Replaced: 3. Result=The slow black bear jumped over the lazy dog.
441
String Functions
StringSetCharacter
Returns copy of a string with a changed character in a specified position.
bool StringSetCharacter( string& string_var, int ushort ); pos, character // string // position // character
Parameters string_var [in][out] String. pos [in] Position of a character in a string. Can be from 0 to StringLen(text). character [in] Symbol code Unicode. Note If pos is less than string length and the symbol code value = 0, the string is cut off (but the buffer size, distributed for the stringremains unchanged). The string length becomes equal to pos. If pos is equal to string length, the specified symbol is added at the string end, and the length is enlarged by one. Example:
void OnStart() { string str="0123456789"; Print("before: str = ",str,",StringBufferLen(str) = ", StringBufferLen(str)," StringSetCharacter(str,6,0); Print(" after: str = ",str,",StringBufferLen(str) = ", StringLen(str) = ",StringLen(str)); StringBufferLen(str)," //--- add symbol at the end int size=StringLen(str); StringSetCharacter(str,size,'+'); Print("addition: str = ",str,",StringBufferLen(str) = ", StringBufferLen(str)," } /* Result before: str = 0123456789 ,StringBufferLen(str) = 0 after: str = 012345 ,StringBufferLen(str) = 16 */ addition: str = 012345+ ,StringBufferLen(str) = 16 StringLen(str) = 10 StringLen(str) = 7 StringLen(str) = 6 StringLen(str) = ",StringLen(str)); StringLen(str) = ",StringLen(str)); //--- add zero value in the middle
442
String Functions
443
String Functions
StringSubstr
Extracts a substring from a text string starting from the specified position.
string StringSubstr( string string_value, int int ); start_pos, length=-1 // string // position to start with // length of extracted string
Parameters string_value [in] String to extract a substring from. start_pos [in] Initial position of a substring. Can be from 0 to StringLen(text) -1. length=-1 [in] Length of an extracted substring. If the parameter value is equal to -1 or parameter isn't set, the substring will be extracted from the indicated position till the string end. Return Value Copy of a extracted substring, if possible. Otherwise returns an empty string.
444
String Functions
StringToLower
Transforms all all symbols of a selected string into lowercase by location.
bool StringToLower( string& string_var ); // string to process
Parameters string_var [in][out] String. Return Value In case of success returns true, otherwise - false. To get the error code call GetLastError().
445
String Functions
StringToUpper
Transforms all all symbols of a selected string into capitals by location.
bool StringToUpper( string& string_var ); // string to process
Parameters string_var [in][out] String. Return Value In case of success returns true, otherwise - false. To get the error code call GetLastError().
446
String Functions
StringTrimLeft
The function cuts line feed characters, spaces and tabs in the left part of the string till the first meaningful symbol. The string is modified at place.
int StringTrimLeft( string& string_var ); // string to cut
Parameters string_var [in][out] String that will be cut from the left. Return Value Returns the number of cut symbols.
447
String Functions
StringTrimRight
The function cuts line feed characters, spaces and tabs in the right part of the string after the last meaningful symbol. The string is modified at place.
int StringTrimRight( string& string_var ); ); // string to cut
Parameters string_var [in][out] String that will be cut from the right. Return Value Returns the number of cut symbols.
448
TimeTradeServer
TimeLocal
TimeGMT
TimeDaylightSavings TimeGMTOffset
TimeToStruct
StructToTime
449
TimeCurrent
Returns the last known server time server, time of the last quote receipt for one of the symbols selected in the "Market Watch" window. In the OnTick() handler, this function returns the time of the received handled tick. In other cases (for example, call in handlers OnInit(), OnDeinit(), OnTimer() and so on) this is the time of the last quote receipt for any symbol available in the "Market Watch" window, the time shown in the title of this window. The time value is formed on a trade server and does not depend on the time settings on your computer. There are 2 variants of the function. Call without parameters
datetime TimeCurrent();
Parameters dt_struct [out] MqlDateTime structure type variable. Return Value Value of datetime type Note If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
450
TimeTradeServer
Returns the calculated current time of the trade server. Unlike TimeCurrent(), the calculation of the time value is performed in the client terminal and depends on the time settings on your computer. There are 2 variants of the function. Call without parameters
datetime TimeTradeServer();
Parameters dt_struct [out] Variable of structure type MqlDateTime. Return Value Value of datetime type Note If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
451
TimeLocal
Returns the local time of a computer, where the client terminal is running. There are 2 variants of the function. Call without parameters
datetime TimeLocal();
Parameters dt_struct [out] Variable of structure type MqlDateTime. Return Value Value of datetime type Note If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
452
TimeGMT
Returns the GMT, which is calculated taking into account the DST switch by the local time on the computer where the client terminal is running. There are 2 variants of the function. Call without parameters
datetime TimeGMT();
Parameters dt_struct [out] Variable of structure type MqlDateTime. Return Value Value of datetime type Note If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
453
TimeDaylightSavings
Returns correction for daylight saving time in seconds, switch to summer time has been made. It depends on the time settings of your computer.
int TimeDaylightSavings();
Return Value If switch to winter (standard) time has been made, it returns 0.
454
TimeGMTOffset
Returns the current difference between GMT time and the local computer time in seconds, taking into account switch to winter or summer time. Depends on the time settings of your computer.
int TimeGMTOffset();
Return Value The value of int type, representing the current difference between the local time of the computer and GMT time in seconds.
455
TimeToStruct
Converts a value of datetime type (number of seconds since 01.01.1970) into a structure variable MqlDateTime.
void TimeToStruct( datetime dt, // date and time // structure for the adoption of values MqlDateTime& dt_struct );
Parameters dt [in] Date value to convert. dt_struct [out] Variable of structure type MqlDateTime. Return Value No return value.
456
StructToTime
Converts a structure variable MqlDateTime into a value of datetime type and returns the resulting value.
datetime StructToTime( MqlDateTime$ dt_struct ); // structure of the date and time
Parameters dt_struct [in] Variable of structure type MqlDateTime. Return Value The value of datetime type containing the number of seconds since 01.01.1970.
457
Account Information
Account Information
Functions that return parameters of the current account. Function AccountInfoDouble Action Returns a value of double type corresponding account property of the
AccountInfoInteger
Returns a value of integer type (bool, int or long) of the corresponding account property Returns a value string type corresponding account property
AccountInfoString
458
Account Information
AccountInfoDouble
Returns the value of the corresponding account property.
double AccountInfoDouble( int property_id ); // identifier of the property
Parameters property_id [in] Identifier of the property. ENUM_ACCOUNT_INFO_DOUBLE. Return Value Value of double type. Example:
void OnStart() { //--- show all the information available from the function AccountInfoDouble() printf("ACCOUNT_BALANCE = printf("ACCOUNT_CREDIT = printf("ACCOUNT_PROFIT = printf("ACCOUNT_EQUITY = printf("ACCOUNT_MARGIN = %G",AccountInfoDouble(ACCOUNT_BALANCE)); %G",AccountInfoDouble(ACCOUNT_CREDIT)); %G",AccountInfoDouble(ACCOUNT_PROFIT)); %G",AccountInfoDouble(ACCOUNT_EQUITY)); %G",AccountInfoDouble(ACCOUNT_MARGIN)); %G",AccountInfoDouble(ACCOUNT_FREEMARGIN)); %G",AccountInfoDouble(ACCOUNT_MARGIN_LEVEL));
The
value
can
be
one
of
the
values
of
printf("ACCOUNT_FREEMARGIN =
printf("ACCOUNT_MARGIN_LEVEL =
459
Account Information
AccountInfoInteger
Returns the value of the properties of the account.
long AccountInfoInteger( int property_id ); // Identifier of the property
Parameters property_id [in] Identifier of the property. ENUM_ACCOUNT_INFO_INTEGER. Return Value Value of long type. Note The property must be one of the bool, int or long types. Example:
void OnStart() { //--- show all the information available from the function AccountInfoInteger() printf("ACCOUNT_LOGIN = %d",AccountInfoInteger(ACCOUNT_LOGIN)); %d",AccountInfoInteger(ACCOUNT_LEVERAGE)); printf("ACCOUNT_LEVERAGE =
The
value
can
be
one
of
the
values
of
bool thisAccountTradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_ALLOWED); bool EATradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_EXPERT); ENUM_ACCOUNT_TRADE_MODE tradeMode=AccountInfoInteger(ACCOUNT_TRADE_MODE); ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE); //--- Inform about the possibility to perform a trade operation if(thisAccountTradeAllowed) Print("Trade for this account is permitted"); else Print("Trade for this account is prohibited!"); //--- Find out if it is possible to trade on this account by Expert Advisors if(EATradeAllowed) Print("Trade by Expert Advisors is permitted for this account"); else Print("Trade by Expert Advisors is prohibited for this account!"); //--- Find out the account type switch(tradeMode) { case(ACCOUNT_TRADE_MODE_DEMO): Print("This is a demo account"); break;
460
Account Information
case(ACCOUNT_TRADE_MODE_CONTEST): Print("This is a competition account"); break; default:Print("This is a real account!"); } //--- Find out the StopOut level setting mode switch(stopOutMode) { case(ACCOUNT_STOPOUT_MODE_PERCENT): Print("The StopOut level is specified percentage"); break; default:Print("The StopOut level is specified in monetary terms"); } }
461
Account Information
AccountInfoString
Returns the value of the corresponding account property.
string AccountInfoString( int property_id ); // Identifier of the property
Parameters property_id [in] Identifier of the property. ENUM_ACCOUNT_INFO_STRING. Return Value Value of string type. Example:
void OnStart() { //--- Show all the information available from the function AccountInfoString() Print("The name of the broker = ",AccountInfoString(ACCOUNT_COMPANY)); Print("Deposit currency = ",AccountInfoString(ACCOUNT_CURRENCY)); Print("Client name = ",AccountInfoString(ACCOUNT_NAME)); Print("The name of the trade server = ",AccountInfoString(ACCOUNT_SERVER)); }
The
value
can
be
one
of
the
values
of
462
Checkup
State Checking
Functions that return parameters of the current state of the client terminal Function GetLastError IsStopped Action Returns the last error Returns true, if an mql5 program has been commanded to stop its operation Returns the code deinitialization of the reason for
UninitializeReason
TerminalInfoInteger
Returns an integer value of a corresponding property of the mql5 program environment Returns a string value of a corresponding property of the mql5 program environment Returns an integer value of a corresponding property of a running mql5 program Returns a string value of a corresponding property of a running mql5 program Returns the name of a symbol of the current chart Returns the current chart timeframe Returns the number of decimal digits determining the accuracy of the price value of the current chart symbol Returns the point size of the the current symbol in the quote currency
TerminalInfoString
MQL5InfoInteger
MQL5InfoString
Symbol
Period Digits
Point
463
Checkup
GetLastError
Returns the contents of the system variable _LastError.
int GetLastError();
Return Value Returns the value of the last error that occurred during the execution of an mql5 program. Note After the function call, the contents of _LastError are not reset. To reset this variable, you need to call ResetLastError().
464
Checkup
IsStopped
Checks the forced shutdown of an mql5 program.
bool IsStopped();
Return Value Returns true, if the _StopFlag system variable contains a value other than 0. A nonzero value is written into _StopFlag, if a mql5 program has been commanded to complete its operation. In this case, you must immediately terminate the program, otherwise the program will be completed forcibly from the outside after 3 seconds.
465
Checkup
UninitializeReason
Returns the code of a reason for deinitialization.
int UninitializeReason();
Return Value Returns the value of _UninitReason which is formed before OnDeinit() is called. Value depends on the reasons that led to deinitialization.
466
Checkup
TerminalInfoInteger
Returns the value of a corresponding property of the mql5 program environment.
int TerminalInfoInteger( int property_id ); // identifier of a property
Parameters property_id [in] Identifier of a property. Can be one one of the values ENUM_TERMINAL_INFO_INTEGER. Return Value Value of int type. of the enumeration
467
Checkup
TerminalInfoString
the function returns the value of a corresponding property of the mql5 program environment. The property must be of string type.
string TerminalInfoString( int property_id ); // identifier of a property
Parameters property_id [in] Identifier of a property. ENUM_TERMINAL_INFO_STRING. Return Value Value of string type. Perhaps one of the values of the enumeration
468
Checkup
MQL5InfoInteger
Returns the value of a corresponding property of a running mql5 program.
int MQL5InfoInteger( int property_id ); // identifier of a property
Parameters property_id [in] Identifier of a property. Cam be one of values of the ENUM_MQL5_INFO_INTEGER enumeration. Return Value Value of int type.
469
Checkup
MQL5InfoString
Returns the value of a corresponding property of a running mql5 program.
string MQL5InfoString( int property_id ); // Identifier of a property
Parameters property_id [in] Identifier of a property. Can be one of the ENUM_MQL5_INFO_STRING enumeration. Return Value Value of string type.
470
Checkup
Symbol
Returns the name of a symbol of the current chart.
string Symbol();
Return Value Value of the _Symbol system variable, which stores the name of the current chart symbol.
471
Checkup
Period
Returns the current chart timeframe.
ENUM_TIMEFRAMES Period();
Return Value The contents of the _Period variable that contains the value of the current chart timeframe. The value can be one of the values of the ENUM_TIMEFRAMES enumeration. See also PeriodSeconds, Chart timeframes, Date and Time, Visibility of objects
472
Checkup
Digits
Returns the number of decimal digits determining the accuracy of price of the current chart symbol.
int Digits();
Return Value The value of the _Digits variable which stores the number of decimal digits determining the accuracy of price of the current chart symbol.
473
Checkup
Point
Returns the point size of the current symbol in the quote currency.
double Point();
Return Value The value of the _Point variable which stores the point size of the current symbol in the quote currency.
474
Market Info
SymbolName SymbolSelect
SymbolIsSynchronized
SymbolInfoDouble
SymbolInfoInteger
SymbolInfoString
SymbolInfoTick
SymbolInfoSessionQuote
SymbolInfoSessionTrade
MarketBookAdd
MarketBookRelease
MarketBookGet
475
Market Info
SymbolsTotal
Returns the number of available (selected in Market Watch or all) symbols.
int SymbolsTotal( bool selected ); // True - only symbols in MarketWatch
Parameters selected [in] Request mode. Can be true or false. Return Value If the 'selected' parameter is true, the function returns the number of symbols selected in MarketWatch. If the value is false, it returns the total number of all symbols.
476
Market Info
SymbolName
Returns the name of a symbol.
string SymbolName( int pos, // number in the list // true - only symbols in MarketWatch bool selected );
Parameters pos [in] Order number of a symbol. selected [in] Request mode. If the value is true, the symbol is taken from the list of symbols selected in MarketWatch. If the value is false, the symbol is taken from the general list. Return Value Value of string type with the symbol name.
477
Market Info
SymbolSelect
Selects a symbol in the Market Watch window or removes a symbol from the window.
bool SymbolSelect( string name, bool ); select // symbol name // add or remove
Parameters name [in] Symbol name. select [in] Switch. If the value is false, a symbol should be removed from MarketWatch, otherwise a symbol should be selected in this window. A symbol can't be removed if the symbol chart is open, or there are open positions for this symbol. Return Value In case of failure returns false.
478
Market Info
SymbolIsSynchronized
The function checks whether data of a selected symbol in the terminal are synchronized with data on the trade server.
bool SymbolIsSynchronized( string name, ); // symbol name
Parameters name [in] Symbol name. Return value If data are synchronized, returns 'true'; otherwise returns 'false'. See also SymbolInfoInteger, Organizing Data Access
479
Market Info
SymbolInfoDouble
Returns the corresponding property of a specified symbol. There are 2 variants of the function. 1. Immediately returns the property value.
double SymbolInfoDouble( string name, int ); prop_id // symbol // identifier of the property
2. Returns true or false depending on whether a function is successfully performed. In case of success, the value of the property is placed into a recipient variable, passed by reference by the last parameter.
bool SymbolInfoDouble( string int name, prop_id, // symbol // identifier of the property
Parameters name [in] Symbol name. prop_id [in] Identifier of a symbol property. The value can be one of the values ENUM_SYMBOL_INFO_DOUBLE enumeration. double_var [out] Variable of double type receiving the value of the requested property. Return Value The value of double type. Example:
void OnTick() { //--- obtain spread from the symbol properties bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT); string comm=StringFormat("Spread %s = %I64d points\r\n", spreadfloat?"floating":"fixed", SymbolInfoInteger(Symbol(),SYMBOL_SPREAD)); //--- now let's calculate the spread by ourselves double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK); double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID); double spread=ask-bid; int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT)); comm=comm+"Calculated spread = "+(string)spread_points+" points";
of the
480
Market Info
Comment(comm); }
481
Market Info
SymbolInfoInteger
Returns the corresponding property of a specified symbol. There are 2 variants of the function. 1. Immediately returns the property value.
long SymbolInfoInteger( string name, int ); prop_id // symbol // identifier of a property
2. Returns true or false depending on whether a function is successfully performed. In case of success, the value of the property is placed into a recipient variable, passed by reference by the last parameter.
bool SymbolInfoInteger( string name, int long& ); prop_id, long_var // symbol // identifier of a property // here we assume the property value
Parameters name [in] Symbol name. prop_id [in] Identifier of a symbol property. The value can be one of the values ENUM_SYMBOL_INFO_INTEGER enumeration. long_var [out] Variable of the long type receiving the value of the requested property. Return Value The value of int type. Example:
void OnTick() { //--- obtain spread from the symbol properties bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT); string comm=StringFormat("Spread %s = %I64d points\r\n", spreadfloat?"floating":"fixed", SymbolInfoInteger(Symbol(),SYMBOL_SPREAD)); //--- now let's calculate the spread by ourselves double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK); double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID); double spread=ask-bid; int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
of the
482
Market Info
comm=comm+"Calculated spread = "+(string)spread_points+" points"; Comment(comm); }
483
Market Info
SymbolInfoString
Returns the corresponding property of a specified symbol. There are 2 variants of the function. 1. Immediately returns the property value.
string SymbolInfoString( string name, int ); prop_id // Symbol // Identifier properties
2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.
bool SymbolInfoString( string name, int prop_id, // Symbol // Identifier properties // Here we assume the property value
string&string_var );
Parameters name [in] Symbol name. prop_id [in] Identifier of a symbol property. The value can be one of the values ENUM_SYMBOL_INFO_STRING enumeration. string_var [out] Variable of the string type receiving the value of the requested property. Return Value The value of string type. of the
484
Market Info
SymbolInfoTick
The function returns current prices of a specified symbol in a variable of the MqlTick type.
bool SymbolInfoTick( string symbol, // symbol name // reference to a structure MqlTick& tick );
Parameters symbol [in] Symbol name. book[] [out] Link to the structure of the MqlTick type, to which the current prices and time of the last price update will be placed. Return Value The function returns true if successful, otherwise returns false.
485
Market Info
SymbolInfoSessionQuote
Allows receiving time of beginning and end of the specified quoting sessions for a specified symbol and weekday..
bool SymbolInfoSessionQuote( string name, // symbol name // day of the week // session index // time of the session beginning // time of the session end ENUM_DAY_OF_WEEK day_of_week, uint datetime& datetime& ); session_index, from, to
Parameters name [in] Symbol name. ENUM_DAY_OF_WEEK [in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK. uint [in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of sessions starts with 0. from [out] Session beginning time in seconds from 00 hours 00 minutes, in the returned value date should be ignored. to [out] Session end time in seconds from 00 hours 00 minutes, in the returned value date should be ignored. Return Value If data for the specified session, symbol and day of the week are received, returns true, otherwise returns false. See also Symbol Properties, TimeToStruct, Data Structures
486
Market Info
SymbolInfoSessionTrade
Allows receiving time of beginning and end of the specified trading sessions for a specified symbol and weekday..
bool SymbolInfoSessionTrade( string name, // symbol name // day of the week // session index // session beginning time // session end time ENUM_DAY_OF_WEEK day_of_week, uint datetime& datetime& ); session_index, from, to
Parameters name [in] Symbol name. ENUM_DAY_OF_WEEK [in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK. uint [in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of sessions starts with 0. from [out] Session beginning time in seconds from 00 hours 00 minutes, in the returned value date should be ignored. to [out] Session end time in seconds from 00 hours 00 minutes, in the returned value date should be ignored. Return value If data for the specified session, symbol and day of the week are received, returns true, otherwise returns false. See also Symbol Properties, TimeToStruct, Data Structures
487
Market Info
MarketBookAdd
Provides opening of Depth of Market for a selected symbol, and subscribes for receiving notifications of the DOM changes.
bool MarketBookAdd( string symbol ); // symbol
Parameters symbol [in] The name of a symbol, whose Depth of Market is to be used in the Expert Advisor or script. Return Value The true value if opened successfully, otherwise false. Note Normally, this function must be called from the OnInit() function or in the class constructor. To handle incoming alerts, in the Expert Advisor program must contain the function void OnBookEvent (string& symbol). See also Structure of Depth of Market, Structures and Classes
488
Market Info
MarketBookRelease
Provides closing of Depth of Market for a selected symbol, and cancels the subscription for receiving notifications of the DOM changes.
bool MarketBookRelease( string symbol ); // symbol
Parameters symbol [in] Symbol name. Return Value The true value if closed successfully, otherwise false. Note Normally, this function must be called from the OnDeinit() function, if the corresponding MarketBookAdd() function has been called in the OnInit() function. Or it must be called from the class destructor, if the corresponding MarketBookAdd() function has been called from the class constructor. See also Structure of Depth of Market, Structures and Classes
489
Market Info
MarketBookGet
Returns a structure array MqlBookInfo containing records of the Depth of Market of a specified symbol.
bool MarketBookGet( string symbol, // symbol // reference to an array MqlBookInfo& book[] );
Parameters symbol [in] Symbol name. book[] [in] Reference to an array of Depth of Market records. The array can be pre-allocated for a sufficient number of records. If a dynamic array hasn't been pre-allocated in the operating memory, the client terminal will distribute the array itself. Return Value Returns true in case of success, otherwise false. Note The Depth of Market must be pre-opened by the MarketBookAdd() function. Example:
MqlBookInfo priceArray[]; bool getBook=MarketBookGet(NULL,priceArray); if(getBook) { int size=ArraySize(priceArray); Print("MarketBookInfo for ",Symbol()); for(int i=0;i<size;i++) { Print(i+":",priceArray[i].price +" Volume = "+priceArray[i].volume, " type = ",priceArray[i].type); } } else { Print("Could not get contents of the symbol DOM ",Symbol()); }
490
It is historically accepted that an access to the price data in an array is performed from the end of the data. Physically, the new data are always written at the array end, but the index of the array is always
491
Timeseries and Indicators Access equal to zero. The 0 index in the timeseries array denotes data of the current bar, i.e. the bar that corresponds to the unfinished time interval in this timeframe. A timeframe is the time period, during which a single price bar is formed. There are 21 predefined standard timeframes. Function SeriesInfoInteger Action Returns information historical data. about the state of
Bars
Returns the number of bars the history for a specified symbol and period. Returns the number of calculated data in an indicator buffer or -1 in the case of error (data hasn't been calculated yet). Remove the indicator handle and release the calculation block of the indicator, if it no one else enjoys. Returns the handle to the specified technical indicator created by an array of type parameters MqlParam. Gets data of a specified buffer from a specified indicator into an array. Gets history data of the Rates structure for a specified symbol and period into an array. Gets history data on bar opening time for a specified symbol and period into an array. Gets history data on bar opening price for a specified symbol and period into an array. Gets history data on maximal bar price for a specified symbol and period into an array. Gets history data on minimal bar price for a specified symbol and period into an array. Gets history data on bar closing price for a specified symbol and period into an array. Gets history data on tick volumes for a specified symbol and period into an array. Gets history data on trade volumes for a specified symbol and period into an array. Gets history data on spreads for a specified symbol and period into an array.
BarsCalculated
IndicatorRelease
IndicatorCreate
CopyBuffer
CopyRates
CopyTime
CopyOpen
CopyHigh
CopyLow
CopyClose
CopyTickVolume
CopyRealVolume
CopySpread
492
Timeseries and Indicators Access Despite the fact that by using the ArraySetAsSeries() function it is possible to set up in arrays access to elements like that in timeseries, it should be remembered that the array elements are physically stored in one and the same order - only indexing direction changes. To demonstrate this fact let's perform an example:
datetime TimeAsSeries[]; //--- set access to the array like to a timeseries ArraySetAsSeries(TimeAsSeries,true); ResetLastError(); int copied=CopyTime(NULL,0,0,10,TimeAsSeries); if(copied<=0) { Print("The copy operation of the open time values for last 10 bars has failed"); return; } Print("TimeCurrent =",TimeCurrent()); Print("ArraySize(Time) =",ArraySize(TimeAsSeries)); int size=ArraySize(TimeAsSeries); for(int i=0;i<size;i++) { Print("TimeAsSeries["+i+"] =",TimeAsSeries[i]); } datetime ArrayNotSeries[]; ArraySetAsSeries(ArrayNotSeries,false); ResetLastError(); copied=CopyTime(NULL,0,0,10,ArrayNotSeries); if(copied<=0) { Print("The copy operation of the open time values for last 10 bars has failed"); return; } size=ArraySize(ArrayNotSeries); for(int i=size-1;i>=0;i--) { Print("ArrayNotSeries["+i+"] =",ArrayNotSeries[i]); }
493
As we see from the output, as the index of TimeAsSeries array increases, the time value of the index decreases, i.e. we move from the present to the past. For the common array ArrayNotSeries the result is different - as index grows, we move from past to present. See Also ArrayIsDynamic, ArrayGetAsSeries, ArraySetAsSeries, ArrayIsSeries
494
495
Timeseries and Indicators Access Default indexing direction of all arrays in Expert Advisors, indicators and scripts is left-to-right. If necessary, in any mql5 program you can request timeseries values on any symbol and timeframe, as well as values of indicators calculated on any symbol and timeframe. Use functions Copy...() for these purposes: CopyBuffer copy values of an indicator buffer to an array of double type; CopyRates copy price history to an array of structures MqlRates; CopyTime copy Time values to an array of datetime type; CopyOpen copy Open values to an array of double type; CopyHigh copy High values to an array of double type; CopyLow copy Low values to an array of double type; CopyClose copy Close values to an array of double type; CopyTickVolume copy tick volumes to an array of long type; CopyRealVolume copy equity volumes to a long type array; CopySpread copy the spread history to an array of int type;
All these functions work in a similar way. Let's consider the data obtaining mechanism on the example of CopyBuffer(). It is implied that the indexing direction of requested data is that of timeseries, and the position with index 0 (zero) stores data of the current yet uncompleted bar. In order to get access to these data we need to copy the necessary volume of data into the recipient array, e.g. into array buffer.
When copying we need to specify the starting position in the source array, starting from which data will be copied to the recipient array. In case of success, the specified number of elements will be copied to the recipient array from the source array (from the indicator buffer in this case). Irrespective of the indexing value set in the recipient array, copying is always performed as is shown in the above figure. Example:
input int per=10; // period of the exponent int ma_handle; // indicator handle | //+------------------------------------------------------------------+ //| Expert initialization function int OnInit() //+------------------------------------------------------------------+
496
497
498
Timeseries and Indicators Access When setting a large value of this parameter, it should be remembered, that if deep history price data for small timeframes are available, memory used for storing timeseries and indicator buffers can become hundreds of megabytes and reach the RAM restriction for the client terminal program (2Gb for 32-bit applications of MS Windows). Change of the "Max bars in charts" comes into effect after the client terminal is restarted. Change of this parameter causes neither automatic referring to a server for additional data, nor forming of additional bars of timeseries. Additional price data are requested from the server, and timeseries are updated taking into account the new limitation, in case of either chart scroll to the area with no data, or when data are requested by a mql5 program. Volume of data requested from the server corresponds to the required number of bars of this timeframe with the "Max bars in charts" parameter taken into account. The restriction set by this parameter is not strict, and in some cases the number of available bars for a timeframe can be a little more than the current parameter value.
Data Availability
Presence of data on HCC format or even in the prepared for using HC format does not always denote the absolute availability if these data to be shown in a chart or used in mql5 programs. When accessing to price data or indicator values from a mql5 program it should be remembered that their availability in a certain moment of time or starting from a certain moment of time is not guaranteed. It is connected with the fact that with the purpose of saving resources, the full copy of data necessary for a mql5 program isn't stored in MetaTrader 5; only direct access to the terminal data base is given. The price history for all timeframes is built from common data of HCC format, and any update of data from a server leads to the update of data for all timeframes and to the recalculation of indicators. Due to this access to data can be closed, even if these data were available a moment ago.
499
Timeseries and Indicators Access server as packed one minute data, from which any predefined timeseries is constructed then. Write all actions concerning data receipt as a separate function CheckLoadHistory(symbol, timeframe, start_date):
int CheckLoadHistory(string symbol,ENUM_TIMEFRAMES period,datetime start_date) { }
The CheckLoadHistory() function is designed as a universal function that can be called from any program (Expert Advisor, script or indicator); and therefore it requires three input parameters: symbol name, period and start date to indicate the beginning of price history you need. Insert necessary checks into the function code before requesting the missing history. First of all, we should make sure that the symbol name and period value are correct:
if(symbol==NULL || symbol=="") symbol=Symbol(); if(period==PERIOD_CURRENT) period=Period();
Then let's make sure that the symbol is available in the MarketWatch window, i.e., the history for the symbol will be available when sending a request to a trade server. If there is no such a symbol in MarketWatch, add it using the SymbolSelect() function.
if(!SymbolInfoInteger(symbol,SYMBOL_SELECT)) { if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1); SymbolSelect(symbol,true); }
Now we should receive the start date of the available history for the indicated symbol/period pair. Perhaps, the value of the input parameter startdate, passed to CheckLoadHistory(), is within the available history; then request to a trade server is not needed. In order to obtain the very first date for the symbol-period as of the moment, the SeriesInfoInteger() function with the SERIES_FIRSTDATE modifier is used.
SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date); if(first_date>0 && first_date<=start_date) return(1);
The next important check is checking the type of the program, from which the function is called. Note, sending request to update the timeseries with the same period as that of the indicator, that calls the update, is undesirable. The undesirability of requesting data on the same symbol-period as that of the indicator is conditioned by the fact that update of history data is performed in the same thread where the indicator operates. So the possibility of clinch occurrence is high. To check this use the MQL5InfoInteger() function with the MQL5_PROGRAM_TYPE modifier.
If all the checks have been passed successfully, make the last attempt to d without referring to the trade server. First let's find out the start date, for which minute data in HCC format are available. Request this value using the SeriesInfoInteger() function with the SERIES_TERMINAL_FIRSTDATE modifier and again compare it to the value of the start_date parameter.
500
If after all the checks the execution thread is still in the body of the CheckLoadHistory() function, it means there is a necessity to request the missing price data from a trade server. First, return the value of "Max bars in chart" using the TerminalInfoInteger() function:
int max_bars=TerminalInfoInteger(TERMINAL_MAXBARS);
We'll need it to prevent requesting extra data. Then find the very first date in the symbol history on the trade server (regardless of the period) using already known function SeriesInfoInteger() with the SERIES_SERVER_FIRSTDATE modifier.
Since the request is an asynchronous operation, the function is called in the cycle with a small delay of 5 milliseconds until the first_server_date variable receives a value, or the cycle execution is terminated by a user (IsStopped() will return true in this case). Let's indicate a correct value of the start date, starting from which we request price data from a trade server.
if(first_server_date>start_date) start_date=first_server_date; if(first_date>0 && first_date<first_server_date) Print("Warning: first server date ",first_server_date," for ", symbol," does not match to first series date ",first_date);
If the start date first_server_date of the server is lower than the start date first_date of the symbol in HCC format, the corresponding entry will be output in the journal. Now we are ready to make a request to a trade server asking for missing price data. Make the request in the form of a cycle and start filling out its body:
while(!IsStopped()) { //1. wait for synchronization between the re-built timeseries and intermediate history as HHC //2. receive the current number of bars n this timeseries // if bars is larger than Max_bars_in_chart, we can exit, work is over //3. obtain the start date first_date in the re-built timeseries and compare it to start_date // if first_date is lower than start_date, we can exit, work is over //4. request from a server a new part of history - 100 bars starting from last available bar }
501
The last fourth point is left - requesting history. We can't refer to a server directly, but any Copyfunction automatically initiates request sending to a server, if the history in HCC format is not enough. Since the time of the very first start date in the first_date variable is the simple and natural criterion to evaluate the request execution degree, then the easiest way is to use the CopyTime() function. When calling functions that copy any data from timeseries, it should be noted that the start parameter (number of the bar, starting from which price data should be coped) must always be within the available terminal history. If you have only 100 bars, it meaningless to try copying 300 bars starting from the bar with the index 500. Such a request will be understood as an erroneous and won't be handled, i.e. no additional history will be loaded from a trade server. That's why we'll copy by 100 bars starting from the bar with the bars index. This will provide the smooth loading of missing history from a trade server. Actually a little more than the requested 100 bars will be loaded, while server sends oversized history.
int copied=CopyTime(symbol,period,bars,100,times);
After the copying operation, we should analyze the number of copied elements. If the attempt fails, then value of the copied will be equal to null and the value of the fail_cnt counter will be increased by 1. After 100 failing attempts, the operation of the function will be stopped.
int fail_cnt=0;
502
So, not only correct handling of the current situation at each moment of execution is implemented in the function, but also the termination code is returned, that can be handled after calling the CheckLoadHistory() function for getting additional information. For example, this way:
int res=CheckLoadHistory(InpLoadedSymbol,InpLoadedPeriod,InpStartDate); switch(res) { case -1 : Print("Unknown symbol ",InpLoadedSymbol); case -2 : Print("More requested bars than can be drawn in the chart"); case -3 : Print("Execution stopped by user"); case -4 : Print("Indicator mustn't load its own data"); case -5 : Print("Loading failed"); case 0 : Print("All data loaded"); case 1 : Print("Already available data in timeseries are enough"); case 2 : Print("Timeseries is built from available terminal data"); default : Print("Execution result undefined"); }
The full code of the function can be found in the example of a script that shows the correct organization of access to any data with the handling of request results. Code:
//+------------------------------------------------------------------+ //| //| //| TestLoadHistory.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.02"
#property script_show_inputs //--- input parameters input string input datetime InpLoadedSymbol="NZDUSD"; // Symbol to be load // Period to be load input ENUM_TIMEFRAMES InpLoadedPeriod=PERIOD_H1;
503
504
505
case PERIOD_M10: return("M10"); case PERIOD_M12: return("M12"); case PERIOD_M15: return("M15"); case PERIOD_M20: return("M20"); case PERIOD_M30: return("M30"); case PERIOD_H1: case PERIOD_H2: case PERIOD_H3: case PERIOD_H4: case PERIOD_H6: case PERIOD_H8: case PERIOD_D1: case PERIOD_W1: } //--return("unknown period"); } return("H1"); return("H2"); return("H3"); return("H4"); return("H6"); return("H8"); return("Daily"); return("Weekly");
506
SeriesInfoInteger
Returns information about the state of historical data. There are 2 variants of function calls. Directly returns the property value.
long SeriesInfoInteger( string ENUM_TIMEFRAMES ENUM_SERIES_INFO_INTEGER ); symbol_name, timeframe, prop_id, // symbol name // period // property identifier
Parameters symbol_name [in] Symbol name. timeframe [in] Period. prop_id [in] Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER enumeration. long_var [out] Variable to which the value of the requested property is placed. Return Value In the first case, it returns value of the long type. For the second case, it returns true, if the specified property is available and it's value has been placed into long_var variable, otherwise it returns false. For more details about an error, call GetLastError(). Example:
void OnStart() { //--Print("Total number of bars for the symbol-period at this moment = ", SeriesInfoInteger(Symbol(),0,SERIES_BARS_COUNT)); Print("The first date for the symbol-period at this moment = ", (datetime)SeriesInfoInteger(Symbol(),0,SERIES_FIRSTDATE));
507
Print("The first date in the history for the symbol-period on the server = ", (datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE)); Print("Symbol data are synchronized = ", (bool)SeriesInfoInteger(Symbol(),0,SERIES_SYNCRONIZED)); }
508
Bars
Returns the number of bars count in the history for a specified symbol and period. There are 2 variants of functions calls. Request all of the history bars
int Bars( string symbol_name, // symbol name // period ENUM_TIMEFRAMES timeframe );
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_time [in] Bar time corresponding to the first element. stop_time [in] Bar time corresponding to the last element. Return Value If the start_time and stop_time parameters are defined, the function returns the number of bars in the specified time interval, otherwise it returns the total number of bars. Note If data for the timeseries with specified parameters are not formed in the terminal by the time of the Bars() function call, or data of the timeseries are not synchronized with a trade server by the moment of the function call, the function returns a zero value. Sample:
509
int bars=Bars(_Symbol,_Period); if(bars>0) { Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars); } else //no available bars { //--- data on the symbol might be not synchronized with data on the server bool synchronized=false; //--- loop counter int attempts=0; // make 5 attempts to wait for synchronization while(attempts<5) { if(SeriesInfoInteger(Symbol(),0,SERIES_SYNCRONIZED)) { //--- synchronization done, exit synchronized=true; break; } //--- increase the counter attempts++; //--- wait 10 milliseconds till the nest iteration Sleep(10); } //--- exit the loop after synchronization if(synchronized) { Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars Print("The first date in the terminal history for the symbol-period at the moment = ", (datetime)SeriesInfoInteger(Symbol(),0,SERIES_FIRSTDATE)); Print("The first date in the history for the symbol on the server = ", (datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE)); } //--- synchronization of data didn't happen else { Print("Failed to get number of bars for ",_Symbol); } }
510
BarsCalculated
Returns the number of calculated data for the specified indicator.
int BarsCalculated( int ); indicator_handle, // indicator handle
Parameters indicator_handle [in] The indicator handle, returned by the corresponding indicator function. Return Value Returns the amount of calculated data in the indicator buffer or -1 in the case of error (data not calculated yet) Note The function is useful when it's necessary to get the indicator data immediately after its creation (indicator handle is available). Example:
void OnStart() { double Ups[]; //--- set timeseries ordering for the the arrays ArraySetAsSeries(Ups,true); //--- create handle for the Fractal Indicator int FractalsHandle=iFractals(NULL,0); //--- reset the error code ResetLastError(); //--- try to copy the indicator values int i,copied=CopyBuffer(FractalsHandle,0,0,1000,Ups); if(copied<=0) { Sleep(50); for(i=0;i<100;i++) { if(BarsCalculated(FractalsHandle)>0) break; Sleep(50); } copied=CopyBuffer(FractalsHandle,0,0,1000,Ups); if(copied<=0) { Print("Failed to copy upper fractals. Error = ",GetLastError(), "i = ",i," return; } copied = ",copied);
511
512
IndicatorCreate
The function returns the handle of a specified technical indicator created based on the array of parameters of MqlParam type.
int IndicatorCreate( string symbol, // symbol name // timeframe ENUM_TIMEFRAMES period, ENUM_INDICATOR indicator_id, int const MqlParam& ); parameters_cnt=0, parameters_array[]=NULL,
// indicator type from the enumeration ENUM_ // number of parameters // array of parameters
Parameters symbol [in] Name of a symbol, on data of which the indicator is calculated. NULL means the current symbol. period [in] The value of the timeframe can be one of values of the ENUM_TIMEFRAMES enumeration, 0 means the current timeframe. indicator_id [in] Indicator type, can be one of values of the ENUM_INDICATOR enumeration. parameters_cnt [in] The number of parameters passed in the parameters_array[] array. The array elements have a special structure type MqlParam. By default, zero - parameters are not passed. If you specify a non-zero number of parameters, the parameter parameters_array is obligatory. You can pass no more than 256 parameters. parameters_array[]=NULL [in] An array of MqlParam type, whose elements contain the type and value of each input parameter of a technical indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. Note If the indicator handle of IND_CUSTOM type is created, the type field of the first element of the array of input parameters parameters_array must have the TYPE_STRING value of the ENUM_DATATYPE enumeration, and the string_value field of the first element must contain the name of the custom indicator. The custom indicator must be compiled (file with EX5 extension) and located in the directory MQL5/Indicators of the client terminal or in a subdirectory. If the first form of the call is used in a custom indicator, you can additionally indicate as the last parameter on what data it will be calculated when passing input parameters. If the "Apply to" parameter is not specified explicitly, the default calculation is based on the PRICE_CLOSE values. Example:
513
514
IndicatorRelease
The function removes an indicator handle and release the calculation block of the indicator, if it's not used by anyone else.
bool IndicatorRelease( int ); indicator_handle, // indicator handle
Returned value Returns true in case of success, otherwise returns false. Note The function allows removing an indicator handle, if it's no longer needed, thus saving memory. The handle is removed immediately, the calculation block is deleted in some time (if it's not called anymore). Example:
//+------------------------------------------------------------------+ //| //| //| Test_IndicatorRelease.mq5 | Copyright 2010, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2010, MetaQuotes Software Corp." #property link #property version input int input int input ENUM_MA_METHOD "http://www.mql5.com" "1.00" MA_Period=15; MA_shift=0; MA_smooth=MODE_SMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE; //--- will store indicator handle int MA_handle=INVALID_HANDLE; //+------------------------------------------------------------------+ //| Expert initialization function int OnInit() { //--- create indicator handle MA_handle=iMA(Symbol(),0,MA_Period,MA_shift,MA_smooth,PRICE_CLOSE); //--- delete global variable if(GlobalVariableCheck("MA_value")) GlobalVariableDel("MA_value"); //--return(0); } //+------------------------------------------------------------------+ //| Expert tick function | | //+------------------------------------------------------------------+
515
516
CopyBuffer
Gets data of a specified buffer of a certain indicator in the necessary quantity.
Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting position is performed from the present to the past, i.e., starting position of 0 means the current bar (indicator value for the current bar). When copying the yet unknown amount of data, it is recommended to use a dynamic array as a buffer [] recipient buffer, because the CopyBuffer() function tries to allocate the size of the receiving array to the size of the copied data. If an indicator buffer (array that is pre-allocated for storing indicator values by the SetIndexBufer() function) is used as the buffer[] recipient array, partial copying is allowed. An example can be found in the Awesome_Oscillator.mql5 custom indicator in the standard terminal package. If you need to make a partial copy of the indicator values into another array (non-indicator buffer), you should use an intermediate array, to which the desired number is copied. After that conduct the element-wise copying of the required number of values into the required places if a receiving array from this intermediate one. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyBuffer( int int int int double ); indicator_handle, buffer_num, start_pos, count, buffer[] // indicator handle // indicator buffer number // start position // amount to copy // target array to copy
517
Parameters indicator_handle [in] The indicator handle, returned by the corresponding indicator function. buffer_num [in] The indicator buffer number. start_pos [in] The position of the first element to copy. count [in] Data count to copy. start_time [in] Bar time, corresponding to the first element. stop_time [in] Bar time, corresponding to the last element. buffer[] [out] Array of double type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be
518
Timeseries and Indicators Access initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval. Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. Example:
//+------------------------------------------------------------------+ //| //| //| TestCopyBuffer3.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00"
#property indicator_separate_window #property indicator_buffers 1 #property indicator_plots //---- plot MA #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- input parameters input bool input int input ENUM_MA_METHOD input int //--- indicator buffers double int MABuffer[]; ma_handle; | AsSeries=true; period=15; smootMode=MODE_EMA; shift=0; "MA" DRAW_LINE Red STYLE_SOLID 1 1
519
The above example illustrates how an indicator buffer is filled out with the values of another indicator
520
Timeseries and Indicators Access buffer from the indicator on the same symbol/period. See also Properties of Custom Indicators, SetIndexBuffer
521
CopyRates
Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the rates_array array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyRates( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy ENUM_TIMEFRAMES timeframe, int int MqlRates ); start_pos, count, rates_array[]
522
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_time [in] Bar time for the first element to copy. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. stop_time [in] Bar time, corresponding to the last element to copy. rates_array[] [out] Array of MqlRates type. Return Value Returns the number of copied elements or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
523
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. Example:
void OnStart() { //--MqlRates rates[]; ArraySetAsSeries(rates,true); int copied=CopyRates(Symbol(),0,0,100,rates); if(copied>0) { Print("Bars copied: "+copied); string format="open = %G, high = %G, low = %G, close = %G, volume = %d"; string out; int size=fmin(copied,10); for(int i=0;i<size;i++) { out=i+":"+TimeToString(rates[i].time); out=out+" "+StringFormat(format, rates[i].open, rates[i].high, rates[i].low, rates[i].close, rates[i].tick_volume); Print(out); } } else Print("Failed to get history data for the symbol ",Symbol()); }
524
CopyTime
The function gets to time_array history data of bar opening time for the specified symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyTime( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy open times ENUM_TIMEFRAMES timeframe, int int datetime ); start_pos, count, time_array[]
525
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time corresponding to the last element to copy. time_array[] [out] Array of datetime type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
526
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1.
527
CopyOpen
The function gets into open_array the history data of bar open prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyOpen( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy open prices ENUM_TIMEFRAMES timeframe, int int double ); start_pos, count, open_array[]
528
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] The start time for the last element to copy. open_array[] [out] Array of double type. Return Value Returns the number of element in the array or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
529
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1.
530
CopyHigh
The function gets into high_array the history data of highest bar prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyHigh( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy ENUM_TIMEFRAMES timeframe, int int double ); start_pos, count, high_array[]
531
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy. high_array[] [out] Array of double type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
532
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. Example:
#property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00"
#property description "An example for output of the High[i] and Low[i]" #property description "for a random chosen bars" double High[],Low[]; //+------------------------------------------------------------------+ //| Get Low for specified bar index double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index) { double low=0; ArraySetAsSeries(Low,true); int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low); if(copied>0 && index<copied) low=Low[index]; return(low); } //+------------------------------------------------------------------+ //| Get the High for specified bar index double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index) { double high=0; ArraySetAsSeries(High,true); int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High); if(copied>0 && index<copied) high=High[index]; return(high); } //+------------------------------------------------------------------+ //| Expert tick function void OnTick() { //--- at each tick we output the High and Low values for the bar with index, //--- equal of the tick second datetime t=TimeCurrent(); int sec=t%60; printf("High[%d] = %G Low[%d] = %G", | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
533
534
CopyLow
The function gets into low_array the history data of minimal bar prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyLow( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy ENUM_TIMEFRAMES timeframe, int int double ); start_pos, count, low_array[]
535
Parameters symbol_name [in] Symbol. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] Bar time, corresponding to the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy. low_array[] [out] Array of double type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
536
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. See also CopyHigh
537
CopyClose
The function gets into close_array the history data of bar close prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyClose( string symbol_name, // symbol name // period // start position // data count to copy // target array to copy ENUM_TIMEFRAMES timeframe, int int double ); start_pos, count, close_array[]
538
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy. close_array[] [out] Array of double type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
539
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1.
540
CopyTickVolume
The function gets into volume_array the history data of tick volumes for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyTickVolume( string symbol_name, // symbol name // period // start position // data count to copy // target array for tick volumes ENUM_TIMEFRAMES timeframe, int int long ); start_pos, count, volume_array[]
541
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy.. volume_array[] [out] Array of long type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
542
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. Example:
#property indicator_separate_window #property indicator_buffers 1 #property indicator_plots //---- plot TickVolume #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- input parameters input int double bars=3000; TickVolumeBuffer[]; | //--- indicator buffers //+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,TickVolumeBuffer,INDICATOR_DATA); IndicatorSetInteger(INDICATOR_DIGITS,0); //--} //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--if(prev_calculated==0) { | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "TickVolume" DRAW_HISTOGRAM C'143,188,139' STYLE_SOLID 1 1
543
544
CopyRealVolume
The function gets into volume_array the history data of trade volumes for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopyRealVolume( string symbol_name, // symbol name // period // start position // data count to copy // target array for volumes values ENUM_TIMEFRAMES timeframe, int int long ); start_pos, count, volume_array[]
545
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy. volume_array[] [out] Array of long type. Return Value Returns the copied data count or -1 in the case of error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
546
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1.
547
CopySpread
The function gets into spread_array the history data of spread values for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely. If you know the amount of data you need to copy, it should better be done to a statically allocated buffer, in order to prevent the allocation of excessive memory. No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls. Call by the first position and the number of required elements
int CopySpread( string symbol_name, // symbol name // period // start position // data count to copy // target array for spread values ENUM_TIMEFRAMES timeframe, int int int ); start_pos, count, spread_array[]
548
Parameters symbol_name [in] Symbol name. timeframe [in] Period. start_pos [in] The start position for the first element to copy. count [in] Data count to copy. start_time [in] The start time for the first element to copy. stop_time [in] Bar time, corresponding to the last element to copy. spread_array[] [out] Array of int type. Return Value Returns the copied data count or -1 in case of an error. Note If the whole interval of requested data is out of the available data on the server, the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on the chart) is requested, the function will also return -1. When requesting data from the indicator, if requested timeseries are not yet built or they need to be downloaded from the server, the function will immediately return -1, but the process of downloading/building will be initiated. When requesting data from an Expert Advisor or script, downloading from the server will be initiated, if the terminal does not have these data locally, or building of a required timeseries will start, if data can be built from the local history but they are not ready yet. The function will return the amount of data that will be ready by the moment of timeout expiration, but history downloading will continue, and at the next similar request the function will return more data. When requesting data in a specified range of dates, only data from this interval will be returned. The interval is set and counted up to seconds. It means, the open time of any bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time Time) is always within the requested interval.
549
Timeseries and Indicators Access Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open time on a week timeframe is always Sunday, but one week bar does not fall into the specified interval. If you need to return value corresponding to the current uncompleted bar, you can use the first form of call specifying start_pos=0 and count=1. Example:
#property indicator_separate_window #property indicator_buffers 1 #property indicator_plots //---- plot Spread #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- input parameters input int double bars=3000; SpreadBuffer[]; | //--- indicator buffers //+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,SpreadBuffer,INDICATOR_DATA); IndicatorSetInteger(INDICATOR_DIGITS,0); //--} //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--if(prev_calculated==0) { | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "Spread" DRAW_HISTOGRAM Red STYLE_SOLID 1 1
550
551
Chart Operations
Chart Operations
These are functions for working with charts. All chart operations are allowed in Expert Advisors and scripts only. Function ChartApplyTemplate Action Applies a specific template from a specified file to the chart Returns the number of a subwindow where an indicator is drawn Opens a new chart with the specified symbol and period Closes the specified chart Returns the ID of the first chart of the client terminal Returns the chart ID of the chart next to the specified one Returns the symbol name of the specified chart Returns the period value of the specified chart Calls a forced redrawing of a specified chart Sets the double value for a corresponding property of the specified chart Sets the integer value (datetime, int, color, bool or char) for a corresponding property of the specified chart Sets the string value for a corresponding property of the specified chart Returns the double value property of the specified chart Returns the integer value property of the specified chart Returns the string value property of the specified chart Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart Returns the ID of the current chart. Adds an indicator with the specified handle into a specified chart window.
ChartWindowFind
ChartOpen
ChartClose ChartFirst
ChartNext
ChartSetInteger
ChartSetString
ChartGetDouble
ChartGetInteger
ChartGetString
ChartNavigate
ChartID ChartIndicatorAdd
552
Chart Operations
ChartIndicatorDelete
Removes an indicator with a specified name from the specified chart window. Returns the short name of the indicator by the number in the indicators list on the specified chart window. Returns the number of all indicators applied to the specified chart window. Returns the number (index) of the chart subwindow, the Expert Advisor or script has been dropped to Returns the price coordinate of the chart point, the Expert Advisor or script has been dropped to Returns the time coordinate of the chart point, the Expert Advisor or script has been dropped to Returns the X coordinate of the chart point, the Expert Advisor or script has been dropped to Returns the Y coordinate of the chart point, the Expert Advisor or script has been dropped to Changes the symbol value and a period of the specified chart. Provides a screenshot of the chart of its current state in a gif format
ChartIndicatorName
ChartIndicatorsTotal
ChartWindowOnDropped
ChartPriceOnDropped
ChartTimeOnDropped
ChartXOnDropped
ChartYOnDropped
ChartSetSymbolPeriod
ChartScreenShot
553
Chart Operations
ChartApplyTemplate
Applies a specific template from a specified file to the chart.
bool ChartApplyTemplate( long chart_id, // Chart ID // Template file name const string filename );
Parameters chart_id [in] Chart ID. 0 means the current chart. filename [in] The name of the file containing the template. The file is searched in "MQL5\Files" folder. Return Value If a template is applied successfully, the function returns true, otherwise false. To get an information about the error, call the GetLastError() function. Note The Expert Advisor will be unloaded and won't be able to continue operating in case of successful loading of a new template to the chart it is attached to. Example:
//+------------------------------------------------------------------+ //| Script program start function void OnStart() { //--- Let's open and try to apply 'my_template.tpl' template if(!ChartApplyTemplate(0,"my_template")) { //--- If unable to apply template, then Print("Unable to apply 'my_template', error ",GetLastError()); ResetLastError(); //--- Let's search just 'my_template' file, without 'tpl' extension if(FileIsExist("my_template")) Print("File 'my_template' exists, but 'my_template.tpl' file is needed"); else Print("'my_template.tpl' file is not found in " +TerminalInfoString(TERMINAL_PATH) +"\\MQL5\\Files"); //--- Now let's return correct filename with 'tpl' extension if(ChartApplyTemplate(0,"my_template.tpl")) Print("'my_template.tpl' successfully applied "); else | //+------------------------------------------------------------------+
554
Chart Operations
Print("Unable to apply 'my_template.tpl', error ",GetLastError()); } else { //--- Template is stored in file without extension Print("'my_template' successfully applied - file without extension"); } }
555
Chart Operations
ChartWindowFind
The function returns the number of a subwindow where an indicator is drawn. There are 2 variants of the function. 1. The function searches in the indicated chart for the subwindow with the specified "short name" of the indicator (the short name is displayed in the left top part of the subwindow), and it returns the subwindow number in case of success.
int ChartWindowFind( long string chart_id, indicator_shortname // chart identifier // short indicator name, see INDICATOR_SHORTNAME
2. The function must be called from a custom indicator. It returns the number of the subwindow where the indicator is working.
int ChartWindowFind();
Parameters chart_id [in] Chart ID. 0 denotes the current chart. indicator_shortname [in] Short name of the indicator. Return Value Subwindow number in case of success. In case of failure the function returns -1. Note If the second variant of the function (without parameters) is called from a script or Expert Advisor, the function returns -1. Don't mix up the short name of an indicator and a file name, which is specified when an indicator is created using iCustom() and IndicatorCreate() functions. If the indicator's short name is not set explicitly, then the name of the file containing the source code of the indicator, is specified in it during compilation. It is important to correctly form the short name of an indicator, which is recorded in the INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that the short name contains values of the indicator's input parameters, because the indicator deleted from a chart in the ChartIndicatorDelete() function is identified by its short name. Exapmle:
#property script_show_inputs //--- input parameters input string //| shortname="MACD(12,26,9)"; | //+------------------------------------------------------------------+ returns number of the chart window with this indicator //+------------------------------------------------------------------+ int GetIndicatorSubWindowNumber(long chartID=0,string short_name="")
556
Chart Operations
{ int window=-1; //--if((ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR) { //--- the function is called from the indicator, name is not required window=ChartWindowFind(); } else { //--- the function is called from an Expert Advisor or script window=ChartWindowFind(0,short_name); if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError()); } //--return(window); } //+------------------------------------------------------------------+ //| Script program start function void OnStart() { //--int window=GetIndicatorSubWindowNumber(0,shortname); if(window!=-1) Print("Indicator "+shortname+" is in the window #"+(string)window); else Print("Indicator "+shortname+" is not found. window = "+(string)window); } | //+------------------------------------------------------------------+
557
Chart Operations
ChartOpen
Opens a new chart with the specified symbol and period.
long ChartOpen( string symbol, // Symbol name // Period ENUM_TIMEFRAMES period );
Parameters symbol [in] Chart symbol. NULL means the symbol of the current chart (the Expert Advisor is attached to). period [in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period. Return Value If successful, it returns the opened chart ID. Otherwise returns 0. Note The maximum possible number of simultaneously open charts in the terminal can't exceed the CHARTS_MAX value.
558
Chart Operations
ChartFirst
Returns the ID of the first chart of the client terminal.
long ChartFirst();
559
Chart Operations
ChartNext
Returns the chart ID of the chart next to the specified one.
long ChartNext( long chart_id ); // Chart ID
Parameters chart_id [in] Chart ID. 0 does not mean the current chart. 0 means "return the first chart ID". Return Value Chart ID. If this is the end of the chart list, it returns -1. Example:
//--- variables for chart ID long currChart,prevChart=ChartFirst(); int i=0,limit=100; Print("ChartFirst =",ChartSymbol(prevChart)," ID =",prevChart); while(i<limit)// We have certainly not more than 100 open charts { currChart=ChartNext(prevChart); // Get the new chart ID by using the previous chart ID if(currChart<0) break; // Have reached the end of the chart list Print(i,ChartSymbol(currChart)," ID =",currChart); prevChart=currChart;// let's save the current chart ID for the ChartNext() i++;// Do not forget to increase the counter }
560
Chart Operations
ChartClose
Closes the specified chart.
bool ChartClose( long chart_id=0 ); // Chart ID
Parameters chart_id=0 [in] Chart ID. 0 means the current chart. Return Value If successful, returns true, otherwise false.
561
Chart Operations
ChartSymbol
Returns the symbol name for the specified chart.
string ChartSymbol( long chart_id=0 ); // Chart ID
Parameters chart_id=0 [in] Chart ID. 0 means the current chart. Return Value If chart does not exist, the result will be an empty string. See also ChartSetSymbolPeriod
562
Chart Operations
ChartPeriod
Returns the timeframe period of specified chart.
ENUM_TIMEFRAMES ChartPeriod( long chart_id=0 ); // Chart ID
Parameters chart_id=0 [in] Chart ID. 0 means the current chart. Return Value The function returns one of the ENUM_TIMEFRAMES values. If chart does not exist, it returns 0.
563
Chart Operations
ChartRedraw
This function calls a forced redrawing of a specified chart.
void ChartRedraw( long chart_id=0 ); // Chart ID
Parameters chart_id=0 [in] Chart ID. 0 means the current chart. Note Usually it is used after changing the object properties. See also Objects functions
564
Chart Operations
ChartSetDouble
Sets a value for a corresponding property of the specified chart. Chart property should be of a double type.
bool ChartSetDouble( long int chart_id, prop_id, // Chart ID // Property ID // Value
double value );
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. Can be one of the ENUM_CHART_PROPERTY_DOUBLE values (except the read-only properties). value [in] Property value. Return Value Returns true if successful, otherwise returns false.
565
Chart Operations
ChartSetInteger
Sets a value for a corresponding property of the specified chart. Chart property must be datetime,int,color,boolorchar.
bool ChartSetInteger( long int long ); chart_id, prop_id, value // Chart ID // Property ID // Value
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. It can be one of the ENUM_CHART_PROPERTY_INTEGER value (except the read-only properties). value [in] Property value. Return Value Returns true if successful, otherwise returns false.
566
Chart Operations
ChartSetString
Sets a value for a corresponding property of the specified chart. Chart property must be of the string type.
bool ChartSetString( long chart_id, int prop_id, str_value // Chart ID // Property ID // Value
string );
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. It's value can be one of the ENUM_CHART_PROPERTY_STRING values (except the read-only properties). str_value [in] Property value string. String length cannot exceed 2045 characters (extra characters will be truncated). Return Value Returns true if successful, otherwise false. Note ChartSetString can be used for a comment output on the chart instead of the Comment function. Example:
void OnTick() { //--double Ask,Bid; int Spread; Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK); Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID); Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD); string comment=StringFormat("Printing prices:\nAsk = %G\nBid = %G\nSpread = %d", Ask,Bid,Spread); ChartSetString(0,CHART_COMMENT,comment); }
567
Chart Operations
ChartGetDouble
Returns the value of a corresponding property of the specified chart. Chart property must be of double type. There are 2 variants of th efunction calls. 1. Returns the property value directly.
double ChartGetDouble( long chart_id, int int ); prop_id, sub_window=0 // Chart ID // Property ID // subwindow number, if necessary
2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable double_var passed by reference.
bool ChartGetDouble( long int int chart_id, prop_id, sub_window, // Chart ID // Property ID // Subwindow number // Target variable for the chart property
double&double_var );
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_DOUBLE values. sub_window [in] Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number. double_var [out] Target variable of double type for the requested property. Return Value The value of double type. For the second call case it returns true if the specified property is available and its value has been placed into double_var variable, otherwise returns false. To get an additional information about the error, it is necessary to call the function GetLastError(). Example:
void OnStart() { double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,0); double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,0); Print("CHART_PRICE_MIN =",priceMin);
568
Chart Operations
Print("CHART_PRICE_MAX =",priceMax); }
569
Chart Operations
ChartGetInteger
Returns the value of a corresponding property of the specified chart. Chart property must be of datetime,intorbool type. There are 2 variants of the function calls. 1. Returns the property value directly.
long ChartGetInteger( long chart_id, int int ); prop_id, sub_window=0 // Chart ID // Property ID // subwindow number, if necessary
2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable long_var passed by reference.
bool ChartGetInteger( long int int long& ); chart_id, prop_id, sub_window, long_var // Chart ID // Property ID // subwindow number // Target variable for the property
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_INTEGER values. sub_window [in] Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number. long_var [out] Target variable of long type for the requested property. Return Value The value of long type. For the second call case it returns true if specified property is available and its value has been stored into long_var variable, otherwise returns false. To get additional information about the error , it is necessary to call the function GetLastError(). Example:
void OnStart() { int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0); int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0); Print("CHART_HEIGHT_IN_PIXELS =",height,"pixels");
570
Chart Operations
Print("CHART_WIDTH_IN_PIXELS =",width,"pixels"); }
571
Chart Operations
ChartGetString
Returns the value of a corresponding property of the specified chart. Chart property must be of string type. There are 2 variants of the function call. 1. Returns the property value directly.
string ChartGetString( long chart_id, int ); prop_id // Chart ID // Property ID
2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable string_var passed by reference.
bool ChartGetString( long int chart_id, prop_id, // Chart ID // Property ID // Target variable for the property
string&string_var );
Parameters chart_id [in] Chart ID. 0 means the current chart. prop_id [in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_STRING values. string_var [out] Target variable of string type for the requested property. Return Value The value of string type. For the second call case it returns true if the specified property is available and its value has been stored into string_var variable, otherwise returns false. To get additional information about the error, it is necessary to call the function GetLastError(). Note ChartGetString can be used for reading comments plotted on the chart using the Comment or ChartSetString functions. Example:
void OnStart() { ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!"); ChartRedraw(); Sleep(1000); string comm=ChartGetString(0,CHART_COMMENT); Print(comm);
572
Chart Operations
}
573
Chart Operations
ChartNavigate
Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart.
bool ChartNavigate( long chart_id, int int ); position, shift=0 // Chart ID // Position // Shift value
Parameters chart_id [in] Chart ID. 0 means the current chart. position [in] Chart position to perform a shift. Can be one of the ENUM_CHART_POSITION values. shift=0 [in] Number of bars to shift the chart. The positive value means the right shift (to the end if the chart), the negative value means the left shift (to the chart begin). The zero shift can be used to navigate to chart beginning or end. Return Value Returns true if successful, otherwise returns false.
574
Chart Operations
ChartID
Returns the ID of the current chart.
long ChartID();
575
Chart Operations
ChartIndicatorAdd
Adds an indicator with the specified handle into a specified chart window.
bool ChartIndicatorAdd( long chart_id, int int ); sub_window indicator_handle // chart ID // number of the sub-window // handle of the indicator
Parameters chart_id [in] Chart ID. 0 means the current chart. sub_window [in] The number of the chart sub-window. 0 means the main chart window. if the number of a not-existing window is specified, a new window will be created. indicator_handle [in] The handle of the indicator. Return Value The function returns true in case of success, otherwise it returns false. In order to obtain information about the error, call the GetLastError() function. See Also ChartIndicatorDelete(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate()
576
Chart Operations
ChartIndicatorDelete
Removes an indicator with a specified name from the specified chart window.
bool ChartIndicatorDelete( long int const string ); chart_id, sub_window ind_shortname // chart id // number of the subwindow // short name of the indicator
Parameters chart_id [in] Chart ID. 0 denotes the current chart. sub_window [in] Number of the chart subwindow. 0 denotes the main chart subwindow. const ind_shortname [in] The short name of the indicator which is set in the INDICATOR_SHORTNAME property with the IndicatorSetString() function. To get the short name of an indicator use the ChartIndicatorName() function. Return Value Returns true in case of successful deletion of the indicator. Otherwise it returns false. To get error details use the GetLastError() function. Note If two indicators with identical short names exist in the chart subwindow, the first one in a row will be deleted. If other indicators on this chart are based on the values of the indicator that is being deleted, such indicators will also be deleted. Do not confuse the indicator short name and the file name that is specified when creating an indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not set explicitly, then the name of the file containing the source code of the indicator will be specified during compilation. Deletion of an indicator from a chart doesn't mean that its calculation part will be deleted from the terminal memory. To release the indicator handle use the IndicatorRelease() function. The indicator's short name should be formed correctly. It will be written to the INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that the short name should contain values of all the input parameters of the indicator, because the indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the short name. See also ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(), IndicatorSetString()
577
Chart Operations
ChartIndicatorName
Returns the short name of the indicator by the number in the indicators list on the specified chart window.
string ChartIndicatorName( long chart_id, int int ); sub_window index // chart id // number of the subwindow
// index of the indicator in the list of indicators added to the chat subwi
Parameters chart_id [in] Chart ID. 0 denotes the current chart. sub_window [in] Number of the chart subwindow. 0 denotes the main chart subwindow. index [in] the index of the indicator in the list of indicators. The numeration of indicators start with zero, i.e. the first indicator in the list has the 0 index. To obtain the number of indicators in the list use the ChartIndicatorsTotal() function. Return Value The short name of the indicator which is set in the INDICATOR_SHORTNAME property with the IndicatorSetString() function. To get error details use the GetLastError() function. Note Do not confuse the indicator short name and the file name that is specified when creating an indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not set explicitly, then the name of the file containing the source code of the indicator will be specified during compilation. The indicator's short name should be formed correctly. It will be written to the INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is recommended that the short name should contain values of all the input parameters of the indicator, because the indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the short name. See also ChartIndicatorAdd(), ChartIndicatorDelete(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(), IndicatorSetString()
578
Chart Operations
ChartIndicatorsTotal
Returns the number of all indicators applied to the specified chart window.
int ChartIndicatorsTotal( long chart_id, int ); sub_window // chart id // number of the subwindow
Parameters chart_id [in] Chart ID. 0 denotes the current chart. sub_window [in] Number of the chart subwindow. 0 denotes the main chart subwindow. Return Value The number of indicators in the specified chart window. To get error details use the GetLastError() function. Note The function allows going searching through all the indicators attached to the chart. The number of all the windows of the chart can be obtained from the CHART_WINDOWS_TOTAL property using the ChartGetInteger() function. See also ChartIndicatorAdd(), ChartIndicatorDelete(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(), IndicatorSetString()
579
Chart Operations
ChartWindowOnDropped
Returns the number (index) of the chart subwindow, the Expert Advisor or script has been dropped to. 0 means the main chart window.
int ChartWindowOnDropped();
580
Chart Operations
ChartPriceOnDropped
Returns the price coordinate corresponding to the chart point, an Expert Advisor or script has been dropped to.
double ChartPriceOnDropped();
581
Chart Operations
ChartTimeOnDropped
Returns the time coordinate corresponding to the chart point, an Expert Advisor or script has been dropped to.
datetime ChartTimeOnDropped();
582
Chart Operations
ChartXOnDropped
Returns the X coordinate of the chart point, an Expert Advisor or script has been dropped to.
int ChartXOnDropped();
Return Value The X coordinate value. Note X axis direction from left to right. Example:
int X=ChartXOnDropped(); int Y=ChartYOnDropped(); Print("(X,Y) = ("+X+","+Y+")");
583
Chart Operations
ChartYOnDropped
Returns the Y coordinateof the chart point, an Expert Advisor or script has been dropped to.
int ChartYOnDropped();
Return Value The Y coordinate value. Note Y axis direction from top to bottom. See also ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped
584
Chart Operations
ChartSetSymbolPeriod
Changes the symbol and period of the specified chart. The function is asynchronous, i.e. it sends the command and does not wait for its execution completion.
bool ChartSetSymbolPeriod( long string chart_id, symbol, // Chart ID // Symbol name // Period
ENUM_TIMEFRAMES period );
Parameters chart_id [in] Chart ID. 0 means the current chart. symbol [in] Chart symbol. NULL value means the current chart symbol (Expert Advisor is attached to) period [in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period. Return Value Returns true if successful, otherwise false. Note The symbol/period change leads to the re-initialization of the Expert Advisor, attached to a chart. See also ChartSymbol, ChartPeriod
585
Chart Operations
ChartScreenShot
The function provides a screenshot of the chart in its current state in a gif format.
bool ChartScreenShot( long string int int chart_id, filename, width, height, // Chart ID // Symbol name // Width // Height // Alignment type
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT );
Parameters chart_id [in] Chart ID. 0 means the current chart. filename [in] Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in the directory \ Files. width [in] Screenshot width in pixels. height [in] Screenshot height in pixels. align_mode=ALIGN_RIGHT [in] Output mode of a narrow screenshot. ALIGN_RIGHT means align to the right margin (the output from the end). ALIGN_LEFT means Left justify. Return Value Returns true if successful, otherwise false. Note If you need to take a screenshot from a chart from a certain position, first it's necessary to position the graph using the ChartNavigate() function. If the horizontal size of the screenshot is smaller than the chart window, either the right part of the chart window, or its left part is output, depending on the align_mode settings.
586
Trade Functions
Trade Functions
This is the group of functions intended for managing trading activities. Trading functions can be used in Expert Advisors and scripts. Trading functions can be called only if in the properties of the Expert Advisor or script the "Allow live trading" checkbox is enabled. Function OrderCalcMargin Action Calculates the margin required for the specified order type, in the deposit currency Calculates the profit based on the parameters passed, in the deposit currency Checks if there are enough funds to execute the required trade operation. Sends trade requests to a server Returns the number of open positions Returns the symbol corresponding to the open position Chooses an open position for further working with it Returns the requested property of an open position (double) Returns the requested property of an open position (datetime or int) Returns the requested property of an open position (string) Returns the number of orders Return the ticket of a corresponding order Selects a order for further working with it Returns the requested property of the order (double) Returns the requested property of the order (datetime or int) Returns the requested property of the order (string) Retrieves the history of transactions and orders for the specified period of the server time Requests the history of deals with a specified position identifier. Selects an order in the history for further
OrderCalcProfit
OrderCheck
PositionSelect
PositionGetDouble
PositionGetInteger
PositionGetString
OrderGetInteger
OrderGetString
HistorySelect
HistorySelectByPosition
HistoryOrderSelect
587
Trade Functions
working with it HistoryOrdersTotal HistoryOrderGetTicket Returns the number of orders in the history Return order ticket of a corresponding order in the history Returns the requested property of an order in the history of (double) Returns the requested property of an order in the history (datetime or int) Returns the requested property of an order in the history of (string) Selects a deal in the history for further calling it through appropriate functions Returns the number of deals in the history Returns a ticket of a corresponding deal in the history Returns the requested property of a deal in the history (double) Returns the requested property of a deal in the history (datetime or int) Returns the requested property of a deal in the history (string)
HistoryOrderGetDouble
HistoryOrderGetInteger
HistoryOrderGetString
HistoryDealSelect
HistoryDealsTotal HistoryDealGetTicket
HistoryDealGetDouble
HistoryDealGetInteger
HistoryDealGetString
588
Trade Functions
OrderCalcMargin
The function calculates the margin required for the specified order type, on the current account, in the current market environment not taking into account current pending orders and open positions. It allows the evaluation of margin for the trade operation planned. The value is returned in the account currency.
bool OrderCalcMargin( ENUM_ORDER_TYPE string double double double& ); action, symbol, volume, price, margin // type of order // symbol name // volume // open price // value for obtaining the margin value
Parameters action [in] The order type, can be one of the valued of the ENUM_ORDER_TYPE enumeration. symbol [in] Symbol name. volume [in] Volume of the trade operation. price [in] Open price. margin [out] The variable, to which the value of the required margin will be written in case the function is successfully executed. The calculation is performed as if there were no pending orders and open positions on the current account. The margin value depends on many factors, and can differ in different market environments. Return Value The function returns true in case of success; otherwise it returns false. In order to obtain information about the error, call the GetLastError() function. See also OrderSend(), Order Properties, Trade Operation Types
589
Trade Functions
OrderCalcProfit
The function calculates the profit for the current account, in the current market conditions, based on the parameters passed. The function is used for pre-evaluation of the result of a trade operation. The value is returned in the account currency.
bool OrderCalcProfit( ENUM_ORDER_TYPE string double double double double& ); action, symbol, volume, price_open, price_close, profit // symbol name // volume // open price // close price // variable for obtaining the profit value
Parameters action [in] Type of the order, can be one of the two values of the ENUM_ORDER_TYPE enumeration: ORDER_TYPE_BUY or ORDER_TYPE_SELL. symbol [in] Symbol name. volume [in] Volume of the trade operation. price_open [in] Open price. price_close [in] Close price. profit [out] The variable, to which the calculated value of the profit will be written in case the function is successfully executed. The estimated profit value depends on many factors, and can differ in different market environments. Return Value The function returns true in case of success; otherwise it returns false. If an invalid order type is specified, the function will return false. In order to obtain information about the error, call GetLastError(). See also OrderSend(), Order Properties, Trade Operation Types
590
Trade Functions
OrderCheck
The OrderCheck() function checks if there are enough money to execute a required trade operation. The check results are placed tothe fields of the MqlTradeCheckResult structure.
bool OrderCheck( MqlTradeRequest& request, // request structure // result structure MqlTradeCheckResult& result );
Parameters request [in] Pointer to the structure of the MqlTradeRequest type, which describes the required trade action. result [in,out] Pointer to the structure of the MqlTradeCheckResult type, to which the check result will be placed. Return Value If funds are not enough for the operation, or parameters are filled out incorrectly, the function returns false. In case of a successful basic check of structures (check of pointers), it returns true this is not an indication that the requested trade operation is sure to be successfully executed. For a more detailed description of the function execution result, analyze the fields of the result structure. In order to obtain information about the error, call the GetLastError() function. See also OrderSend(), Trade Operation Types, Trade Request Structure, Structure of Request Check Results, Structure of a Trade Request Result
591
Trade Functions
OrderSend
The OrderSend() function is used for executing trade operations by sending requests to a trade server.
bool OrderSend( MqlTradeRequest& request, MqlTradeResult& result ); // query structure // structure of the answer
Parameters request [in] Pointer to a structure of MqlTradeRequest type describing the trade activity of the client. result [in,out] Pointer to a structure of MqlTradeResult type describing the result of trade operation in case of a successful completion (if true is returned). Return Value In case of a successful basic check of structures (index checking) returns true this is not a sign of successful execution of a trade operation. For a more detailed description of the function execution result, analyze the fields of result structure. Note The trade requests go through several stages of checking on a trade server. First of all, it checks if all the required fields of the request parameter are filled out correctly. If there are no errors, the server accepts the order for further processing. If the order is successfully accepted by the trade server, the OrderSend() function returns true. It is recommended to check the request before sending it to a trade server. To check requests, use the OrderCheck() function. It checks if there are enough funds to execute the trade operation, and returns many useful parameters in the results of trade request checking: return code containing information about errors in the checked request; balance value that will appear after the trade operation is executed; equity value that will appear after the trade operation is executed; floating point value that will appear after the trade operation is executed; margin required for the trade operation; amount of free equity that will remain after the execution of the trade operation; the margin level that will be set after the trade operation is executed; comment to the reply code, error description. It should be noted when placing a market order that the successful completion of the OrderSend() method operation does not always mean a successful deal completion. Check in the returned result structure result the retcode value containing trade server return code, and values of deal or order field depending on the type of operation. Each accepted order is stored on the trade server awaiting processing until one of the conditions for its execution occurs: expiration,
592
Trade Functions appearance of an opposite request, order execution when the execution price appears, a request to cancel the order is received. At the moment of the order processing, the trade server sends to the terminal a message about the occurrence of the Trade event, which can be processed by the OnTrade() function. Example:
//--- value for ORDER_MAGIC input long order_magic=55555; //+------------------------------------------------------------------+ //| Script program start function void OnStart() { //--- make sure that the account is demo if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL) { Alert("Script operation is not allowed on a live account!"); return; } //--- place or delete order if(GetOrdersTotalByMagic(order_magic)==0) { //--- no current orders - place an order int res=SendRandomPendingOrder(order_magic); Print("Return code of the trade server ",res); } else // there are orders - delete orders { DeleteAllOrdersByMagic(order_magic); } } //+------------------------------------------------------------------+ //| receive the current number of orders with specified ORDER_MAGIC int GetOrdersTotalByMagic(long const magic_number) { long order_ticket; int total=0; //--- selection through the entire history HistorySelect(0,TimeCurrent()); //--- go through all pending orders for(int i=0;i<OrdersTotal();i++) if(order_ticket=OrderGetTicket(i)) if(magic_number==OrderGetInteger(ORDER_MAGIC)) total++; //--return(total); } | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
593
Trade Functions
//+------------------------------------------------------------------+ //| deletes all pending orders with specified ORDER_MAGIC void DeleteAllOrdersByMagic(long const magic_number) { long order_ticket; int total=0; //--- selection through the entire history HistorySelect(0,TimeCurrent()); //--- go through all pending orders for(int i=OrdersTotal()-1;i>=0;i--) if(order_ticket=OrderGetTicket(i)) //--- order with appropriate ORDER_MAGIC if(magic_number==OrderGetInteger(ORDER_MAGIC)) { MqlTradeResult result; MqlTradeRequest request; request.order=order_ticket; request.action=TRADE_ACTION_REMOVE; OrderSend(request,result); //--- write the server reply to log Print(__FUNCTION__,": ",result.comment," reply code ",result.retcode); } //--} //+------------------------------------------------------------------+ //| set a pending order in a random way | //+------------------------------------------------------------------+ int SendRandomPendingOrder(long const magic_number) { //--- prepare a request MqlTradeRequest request; request.action=TRADE_ACTION_PENDING; request.magic=magic_number; request.symbol=_Symbol; request.volume=0.1; request.sl=0; request.tp=0; request.deviation=5; //--- form the order type request.type=GetRandomType(); //--- form the price for the pending order request.price=GetRandomPrice(request.type); //--- send a trade request MqlTradeResult result; OrderSend(request,result); //--- write the server reply to log Print(__FUNCTION__,":",result.comment); // open price // order type // setting a pending order // ORDER_MAGIC // symbol // volume in 0.1 lots // Stop Loss is not specified // Take Profit is not specified // deviation in 5 points | //+------------------------------------------------------------------+
594
Trade Functions
if(result.retcode==10016) Print(result.bid,result.ask,result.price); //--- return code of the trade server reply return result.retcode; } //+------------------------------------------------------------------+ //| return type of a pending order in a random way ENUM_ORDER_TYPE GetRandomType() { int t=MathRand()%4; //--{ case(0):return(ORDER_TYPE_BUY_LIMIT); case(1):return(ORDER_TYPE_SELL_LIMIT); case(2):return(ORDER_TYPE_BUY_STOP); case(3):return(ORDER_TYPE_SELL_STOP); } //--- incorrect value return(WRONG_VALUE); //--} //+------------------------------------------------------------------+ //| return price in a random way | //+------------------------------------------------------------------+ double GetRandomPrice(ENUM_ORDER_TYPE type) { int t=(int)type; //--- stop levels for the symbol int distance=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL); //--- receive data of the last tick MqlTick last_tick; SymbolInfoTick(_Symbol,last_tick); //--- calculate price according to the type double price; if(t==2 || t==5) // ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_STOP { price=last_tick.bid; // depart from price Bid price=price-(distance+(MathRand()%10)*5)*_Point; } else { price=last_tick.ask; // depart from price Ask price=price+(distance+(MathRand()%10)*5)*_Point; } return(price); } // ORDER_TYPE_SELL_LIMIT or ORDER_TYPE_BUY_STOP 0<=t<4 switch(t) | //+------------------------------------------------------------------+
See also
595
Trade Functions Trade Operation Types, Trade Request Structure, Structure of Request Check Results, Structure of a Trade Request Result
596
Trade Functions
PositionsTotal
Returns the number of open positions.
int PositionsTotal();
Return Value Value of int type. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. The total number of positions on a trade account cannot exceed the total number of financial instruments. See also PositionGetSymbol(), PositionSelect(), Position Properties
597
Trade Functions
PositionGetSymbol
Returns the symbol corresponding to the open position and automatically selects the position for further working with it using functions PositionGetDouble, PositionGetInteger, PositionGetString.
string PositionGetSymbol( int index ); // Number in the list of positions
Parameters index [in] Number of the position in the list of open positions. Return Value Value of the string type. If the position was not found, an empty string will be returned. To get an error code, call the GetLastError() function. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. The total number of positions on a trade account cannot exceed the total number of financial instruments. See also PositionsTotal(), PositionSelect(), Position Properties
598
Trade Functions
PositionSelect
Chooses an open position for further working with it. Returns true if the function is successfully completed. Returns false in case of failure. To obtain information about the error, call GetLastError().
bool PositionSelect( string symbol ); // Symbol name
Parameters symbol [in] Name of the financial security. Return Value Value of the bool type. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse positions with current pending orders, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. Function PositionSelect() copies data about a position into the program environment, and further calls of PositionGetDouble(), PositionGetInteger() and PositionGetString() return the earlier copied data. This means that the position itself may no longer exist (or it's volume, direction, etc. has changed), but data of this position still can be obtained. To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right before referring to them. See also PositionGetSymbol(), PositionsTotal(), Position Properties
599
Trade Functions
PositionGetDouble
The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect. The position property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double PositionGetDouble( ENUM_POSITION_PROPERTY_DOUBLE property_id ); // Property identifier
2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetDouble( ENUM_POSITION_PROPERTY_DOUBLE property_id, double& ); double_var // Property identifier // Here we accept the property value
Parameters property_id [in] Identifier of a position property. The value can be one of the values of the ENUM_POSITION_PROPERTY_DOUBLE enumeration. double_var [out] Variable of the double type, accepting the value of the requested property. Return Value Value of the double type. If the function fails, 0 is returned. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse positions with current pending orders, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right before referring to them. See also PositionGetSymbol(), PositionSelect(), Position Properties
600
Trade Functions
PositionGetInteger
The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect. The position property should be of datetime, int type. There are 2 variants of the function. 1. Immediately returns the property value.
long PositionGetInteger( ENUM_POSITION_PROPERTY_INTEGER property_id ); // Property identifier
2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetInteger( ENUM_POSITION_PROPERTY_INTEGER property_id, long& ); long_var // Property identifier // Here we accept the property value
Parameters property_id [in] Identifier of a position property. The value can be one of the values of the ENUM_POSITION_PROPERTY_INTEGER enumeration. long_var [out] Variable of the long type accepting the value of the requested property. Return Value Value of the long type. If the function fails, 0 is returned. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse positions with current pending orders, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right before referring to them. See also PositionGetSymbol(), PositionSelect(), Position Properties
601
Trade Functions
PositionGetString
The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect. The position property should be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string PositionGetString( ENUM_POSITION_PROPERTY_STRING property_id ); // Property identifier
2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.
bool PositionGetString( ENUM_POSITION_PROPERTY_STRING property_id, string& ); string_var // Property identifier // Here we accept the property value
Parameters property_id [in] Identifier of a position property. The value can be one of the values of the ENUM_POSITION_PROPERTY_STRING enumeration. string_var [out] Variable of the string type accepting the value of the requested property. Return Value Value of the string type. If the function fails, an empty string is returned. Note For each symbol, at any given moment of time, only one position can be open, which is the result of one or more deals. Do not confuse positions with current pending orders, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. To ensure receipt of fresh data about a position, it is recommended to call PositionSelect() right before referring to them. See also PositionGetSymbol(), PositionSelect(), Position Properties
602
Trade Functions
OrdersTotal
Returns the number of current orders.
int OrdersTotal();
Return Value Value of the int type. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position is a result of one or more deals. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. See also OrderSelect(), OrderGetTicket(), Order Properties
603
Trade Functions
OrderGetTicket
Returns ticket of a corresponding order automatically selects the order for further working with it using functions.
ulong OrderGetTicket( int index ); // Number in the list of orders
Parameters index [in] Number of an order in the list of current orders. Return Value Value of the ulong type. If the function fails, 0 is returned. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position is a result of one or more deals. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. Function OrderGetTicket() copies data about an order into the program environment, and further calls of OrderGetDouble(), OrderGetInteger(), OrderGetString() return the earlier copied data. This means that the order itself may no longer exist (or its open price, Stop Loss/Take Profit levels or expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data about an order, it is recommended to call OrderGetTicket() right before referring to them. Example:
void OnStart() { datetime from=0; datetime to=TimeCurrent(); //--- request the entire history HistorySelect(from,to); //--- variables for returning values from order properties ulong double double string string long long uint ticket; open_price; initial_volume; symbol; type; order_magic; positionID; total=OrdersTotal();
datetime time_setup;
604
Trade Functions
for(uint i=0;i<total;i++) { //--- return order ticket by its position in the list if((ticket=OrderGetTicket(i))>0) { //--- return order properties open_price= time_setup= symbol= order_magic= positionID = initial_volume= OrderGetDouble(ORDER_PRICE_OPEN); OrderGetInteger(ORDER_TIME_SETUP); OrderGetString(ORDER_SYMBOL); OrderGetInteger(ORDER_MAGIC); OrderGetInteger(ORDER_POSITION_ID); OrderGetDouble(ORDER_VOLUME_INITIAL);
type=GetOrderType(OrderGetInteger(ORDER_TYPE)); //--- prepare and show information about the order printf("#ticket %d %s %G %s at %G was set up at %s", ticket, type, initial_volume, symbol, open_price, ); } } //--} //+------------------------------------------------------------------+ //| returns the string name of the order type | //+------------------------------------------------------------------+ string GetOrderType(long type) { string str_type="unknown operation"; switch(type) { case (ORDER_TYPE_BUY): case (ORDER_TYPE_SELL): case (ORDER_TYPE_BUY_LIMIT): case (ORDER_TYPE_SELL_LIMIT): case (ORDER_TYPE_BUY_STOP): case (ORDER_TYPE_SELL_STOP): return("buy"); return("sell"); return("buy limit"); return("sell limit"); return("buy stop"); return("sell stop"); // order ticket // type // placed volume // symbol // specified open price
case (ORDER_TYPE_BUY_STOP_LIMIT): return("buy stop limit"); case (ORDER_TYPE_SELL_STOP_LIMIT):return("sell stop limit"); } return(str_type); }
605
Trade Functions
OrderSelect
Selects an order to work with. Returns true if the function has been successfully completed. Returns false if the function completion has failed. For more information about an error call GetLastError().
bool OrderSelect( ulong ); ticket // Order ticket
Parameters ticket [in] Order ticket. Return Value Value of the bool type. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. Function OrderSelect() copies data about an order into the program environment, and further calls of OrderGetDouble(), OrderGetInteger(), OrderGetString() return the earlier copied data. This means that the order itself may no longer exist (or its open price, Stop Loss/Take Profit levels or expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before referring to them. See also OrderGetInteger(), OrderGetDouble(), OrderGetString(), OrderCalcProfit(), OrderGetTicket(), Order Properties
606
Trade Functions
OrderGetDouble
Returns the requested property of an order, pre-selected using OrderGetTicket or OrderSelect. The order property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double OrderGetDouble( ENUM_ORDER_PROPERTY_DOUBLE property_id ); // Property identifier
2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable passed by reference by the last parameter.
bool OrderGetDouble(
ENUM_ORDER_PROPERTY_DOUBLE property_id,
double& ); double_var
Parameters property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_DOUBLE enumeration. double_var [out] Variable of the double type that accepts the value of the requested property. Return Value Value of the double type. If the function fails, 0 is returned. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before referring to them. See also OrdersTotal(), OrderGetTicket(), Order Properties
607
Trade Functions
OrderGetInteger
Returns the requested order property, pre-selected using OrderGetTicket or OrderSelect. Order property must be of the datetime, int type. There are 2 variants of the function. 1. Immediately returns the property value.
long OrderGetInteger( ENUM_ORDER_PROPERTY_INTEGER property_id ); // Property identifier
2. Returns true or false depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool OrderGetInteger( ENUM_ORDER_PROPERTY_INTEGER property_id, long& ); long_var // Property identifier // Here we accept the property value
Parameters property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_INTEGER enumeration. long_var [out] Variable of the long type that accepts the value of the requested property. Return Value Value of the long type. If the function fails, 0 is returned. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before referring to them. See also OrdersTotal(), OrderGetTicket(), Order Properties
608
Trade Functions
OrderGetString
Returns the requested order property, pre-selected using OrderGetTicket or OrderSelect. The order property must be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string OrderGetString( ENUM_ORDER_PROPERTY_STRING property_id ); // Property identifier
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool OrderGetString( ENUM_ORDER_PROPERTY_STRING property_id, string& ); string_var // Property identifier // Here we accept the property value
Parameters property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_STRING enumeration. string_var [out] Variable of the string type that accepts the value of the requested property. Return Value Value of the string type. Note Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. For each symbol, at any given moment of time, only one position can be open, while there can be several pending orders for the same symbol. To ensure receipt of fresh data about an order, it is recommended to call OrderSelect() right before referring to them. See also OrdersTotal(), OrderGetTicket(), Order Properties
609
Trade Functions
HistorySelect
Retrieves the history of deals and orders for the specified period of server time.
bool HistorySelect( datetime from_date, datetime to_date ); // From date // To date
Parameters from_date [in] Start date of the request. to_date [in] End date of the request request. Return Value It returns true if successful, otherwise returns false. Note HistorySelect() creates a list of orders and a list of trades in a mql5-program, for further referring to the list elements using corresponding functions. The deals list size can be returned using the HistoryDealsTotal() function; the size of the list of orders in the history can be obtained using HistoryOrdersTotal(). Selection in the list of orders should be better performed by HistoryOrderGetTicket(), for items in the list of deals HistoryDealGetTicket() suits better. After using HistoryOrderSelect(), the list of history orders available to the mql5 program is reset and filled again by the found order, if the search of an order by the ticket has been completed successfully. The same applies to the list of deals available to the mql5 program - it is reset by HistoryDealSelect() and filled again in case of a successful receipt of a deal by ticket number. Example:
void OnStart() { color BuyColor =Blue; color SellColor=Red; //--- request trade history HistorySelect(0,TimeCurrent()); //--- create objects string uint ulong double double string long long name; total=HistoryDealsTotal(); ticket=0; price; profit; symbol; type; entry;
datetime time;
610
Trade Functions
for(uint i=0;i<total;i++) { //--- try to get deals ticket if(ticket=HistoryDealGetTicket(i)) { //--- get deals properties price =HistoryDealGetDouble(ticket,DEAL_PRICE); time type =HistoryDealGetInteger(ticket,DEAL_TIME); =HistoryDealGetInteger(ticket,DEAL_TYPE); symbol=HistoryDealGetString(ticket,DEAL_SYMBOL); entry =HistoryDealGetInteger(ticket,DEAL_ENTRY); profit=HistoryDealGetDouble(ticket,DEAL_PROFIT); //--- only for current symbol if(price && time && symbol==Symbol()) { //--- create price object name="TradeHistory_Deal_"+string(ticket); if(entry) ObjectCreate(0,name,OBJ_ARROW_RIGHT_PRICE,0,time,price,0,0); else ObjectCreate(0,name,OBJ_ARROW_LEFT_PRICE,0,time,price,0,0); //--- set object properties ObjectSetInteger(0,name,OBJPROP_SELECTABLE,0); ObjectSetInteger(0,name,OBJPROP_BACK,0); ObjectSetInteger(0,name,OBJPROP_COLOR,type?BuyColor:SellColor); if(profit!=0) ObjectSetString(0,name,OBJPROP_TEXT,"Profit: "+string(profit)); } } } //--- apply on chart ChartRedraw(); }
611
Trade Functions
HistorySelectByPosition
Retrieves the history of deals and orders having the specified position identifier.
bool HistorySelectByPosition( long position_id ); // position identifier - POSITION_IDENTIFIER
Parameters position_id [in] Position identifier that is set to every executed order and every deal. Return Value It returns true if successful, otherwise returns false. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. HistorySelectByPosition() creates in a mql5 program a list of orders and a list of deals with a specified position identifier for further reference to the elements of the list using the appropriate functions. To know the size of the list of deals, use function HistoryDealsTotal(), the size of the list of orders in the history can be obtained using HistoryOrdersTotal(). To run through elements of the orders list, use HistoryOrderGetTicket(), for elements of the deals list - HistoryDealGetTicket(). After using HistoryOrderSelect(), list of history orders available to the mql5 program is reset and filled again with the found order, if search of an order by its ticket was successful. The same refers to the list of deals available to the mql5 program - it is reset by function HistoryDealSelect() and is filled out again if a deal was found successfully by the ticket number. See also HistorySelect(), HistoryOrderGetTicket(), Order Properties
612
Trade Functions
HistoryOrderSelect
Selects an order from the history for further calling it through appropriate functions. It returns true if the function has been successfully completed. Returns false if the function has failed. For more details on error call GetLastError().
bool HistoryOrderSelect( ulong ticket ); // Order ticket
Parameters ticket [in] Order ticket. Return Value Returns true if successful, otherwise false. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. HistoryOrderSelect() clears in a mql5-program the list of orders from a history, available for calls, and copies to it a single order, if the execution of HistoryOrderSelect () has been completed successfully. If you need to go through all deals selected by HistorySelect(), you should better use HistoryOrderGetTicket(). See also HistorySelect(), HistoryOrderGetTicket(), Order Properties
613
Trade Functions
HistoryOrdersTotal
Returns the number of orders in the history. Prior to calling HistoryOrdersTotal(), first it is necessary to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
int HistoryOrdersTotal();
Return Value Value of the int type. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. See also HistorySelect(), HistoryOrderSelect(), HistoryOrderGetTicket(), Order Properties
614
Trade Functions
HistoryOrderGetTicket
Return the ticket of a corresponding order in the history. Prior to calling HistoryOrderGetTicket(), first it is necessary to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
ulong HistoryOrderGetTicket( int index ); // Number in the list of orders
Parameters index [in] Number of the order in the list of orders. Return Value Value of the ulong type. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. Example:
void OnStart() { datetime from=0; datetime to=TimeCurrent(); //--- request the entire history HistorySelect(from,to); //--- variables for returning values from order properties ulong double double ticket; open_price; initial_volume;
datetime time_setup; datetime time_done; string string long long uint symbol; type; order_magic; positionID; total=HistoryOrdersTotal();
//--- number of current pending orders //--- go through orders in a loop for(uint i=0;i<total;i++) { //--- return order ticket by its position in the list if(ticket=HistoryOrderGetTicket(i)) { //--- return order properties
615
Trade Functions
open_price= time_setup= time_done= symbol= order_magic= positionID = initial_volume= HistoryOrderGetDouble(ticket,ORDER_PRICE_OPEN); HistoryOrderGetInteger(ticket,ORDER_TIME_SETUP); HistoryOrderGetInteger(ticket,ORDER_TIME_DONE); HistoryOrderGetString(ticket,ORDER_SYMBOL); HistoryOrderGetInteger(ticket,ORDER_MAGIC); HistoryOrderGetInteger(ticket,ORDER_POSITION_ID); HistoryOrderGetDouble(ticket,ORDER_VOLUME_INITIAL);
type=GetOrderType(HistoryOrderGetInteger(ticket,ORDER_TYPE)); //--- prepare and show information about the order printf("#ticket %d %s %G %s at %G was set up at %s => done at %s, pos ID=%d", ticket, type, initial_volume, symbol, open_price, // order ticket // type // placed volume // symbol // specified open price
TimeToString(time_setup),// time of order placing TimeToString(time_done), // time of order execution or deletion positionID ); } } //--} //+------------------------------------------------------------------+ //| returns the string name of the order type | //+------------------------------------------------------------------+ string GetOrderType(long type) { string str_type="unknown operation"; switch(type) { case (ORDER_TYPE_BUY): case (ORDER_TYPE_SELL): case (ORDER_TYPE_BUY_LIMIT): case (ORDER_TYPE_SELL_LIMIT): case (ORDER_TYPE_BUY_STOP): case (ORDER_TYPE_SELL_STOP): return("buy"); return("sell"); return("buy limit"); return("sell limit"); return("buy stop"); return("sell stop");
case (ORDER_TYPE_BUY_STOP_LIMIT): return("buy stop limit"); case (ORDER_TYPE_SELL_STOP_LIMIT):return("sell stop limit"); } return(str_type); }
616
Trade Functions
HistoryOrderGetDouble
Returns the requested order property. The order property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double HistoryOrderGetDouble( ulong ticket_number, // Ticket // Property identifier ENUM_ORDER_PROPERTY_DOUBLE property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetDouble( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_ORDER_PROPERTY_DOUBLE property_id, double& ); double_var
Parameters ticket_number [in] Order ticket. property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_DOUBLE enumeration. double_var [out] Variable of the double type that accepts the value of the requested property. Return Value Value of the double type. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. See also HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
617
Trade Functions
HistoryOrderGetInteger
Returns the requested property of an order. The order property must be of datetime, int type. There are 2 variants of the function. 1. Immediately returns the property value.
long HistoryOrderGetInteger( ulong ticket_number, // Ticket // Property identifier ENUM_ORDER_PROPERTY_INTEGER property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetInteger( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_ORDER_PROPERTY_INTEGER property_id, long& ); long_var
Parameters ticket_number [in] Order ticket. property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_INTEGER enumeration. long_var [out] Variable of the long type that accepts the value of the requested property. Return Value Value of the long type. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. See also HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
618
Trade Functions
HistoryOrderGetString
Returns the requested property of an order. The order property must be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string HistoryOrderGetString( ulong ticket_number, // Ticket // Property identifier ENUM_ORDER_PROPERTY_STRING property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetString( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_ORDER_PROPERTY_STRING property_id, string& ); string_var
Parameters ticket_number [in] Order ticket. property_id [in] Identifier of the order property. The value can be one of the values of the ENUM_ORDER_PROPERTY_STRING enumeration. string_var [out] Variable of the string type. Return Value Value of the string type. Note Do not confuse orders of a trading history with current pending orders that appear on the "Trade" tab of the "Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be viewed in the "History" tab of "Toolbox" of the client terminal. See also HistorySelect(), HistoryOrdersTotal(), HistoryOrderSelect(), Order Properties
619
Trade Functions
HistoryDealSelect
Selects a deal in the history for further calling it through appropriate functions. It returns true if the function has been successfully completed. Returns false if the function has failed. For more details on error call GetLastError().
bool HistoryDealSelect( ulong ticket ); // Deal ticket
Parameters ticket [in] Deal ticket. Return Value Returns true if successful, otherwise false. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. HistoryDealSelect() clears in a mql5-program the list of deals available for reference, and copies the single deal, if the the execution of HistoryDealSelect() has been completed successfully. If you need to go through all deals selected by the HistorySelect() function, you should better use HistoryDealGetTicket(). See also HistorySelect(), HistoryDealGetTicket(), Deal Properties
620
Trade Functions
HistoryDealsTotal
Returns the number of deal in history. Prior to calling HistoryDealsTotal(), first it is necessary to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
int HistoryDealsTotal();
Return Value Value of the int type. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. See also HistorySelect(), HistoryDealGetTicket(), Deal Properties
621
Trade Functions
HistoryDealGetTicket
The function selects a deal for further processing and returns the deal ticket in history. Prior to calling HistoryDealGetTicket(), first it is necessary to receive the history of deals and orders using the HistorySelect() or HistorySelectByPosition() function.
ulong HistoryDealGetTicket( int index ); // ticket deal
Parameters index [in] Number of a deal in the list of deals Return Value Value of the ulong type. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. Example:
622
Trade Functions
void OnStart() { ulong deal_ticket; // deal ticket ulong order_ticket; // ticket of the order the deal was executed on datetime transaction_time; // time of a deal execution long deal_type ; // type of a trade operation long position_ID; // position ID string deal_description; // operation description double volume; // operation volume string symbol; // symbol of the deal //--- set the start and end date to request the history of deals datetime from_date=0; // from the very beginning datetime to_date=TimeCurrent();// till the current moment //--- request the history of deals in the specified period HistorySelect(from_date,to_date); //--- total number in the list of deals int deals=HistoryDealsTotal(); //--- now process each trade for(int i=0;i<deals;i++) { deal_ticket= HistoryDealGetTicket(i); volume= HistoryDealGetDouble(deal_ticket,DEAL_VOLUME); transaction_time=(datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME); order_ticket= HistoryDealGetInteger(deal_ticket,DEAL_ORDER); deal_type= HistoryDealGetInteger(deal_ticket,DEAL_TYPE); symbol= HistoryDealGetString(deal_ticket,DEAL_SYMBOL); position_ID= HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID); deal_description= GetDealDescription(deal_type,volume,symbol,order_ticket,position_I //--- perform fine formatting for the deal number string print_index=StringFormat("% 3d",i); //--- show information on the deal Print(print_index+": deal #",deal_ticket," at ",transaction_time,deal_description); } } //+------------------------------------------------------------------+ //| returns the string description of the operation | //+------------------------------------------------------------------+ string GetDealDescription(long deal_type,double volume,string symbol,long ticket,long pos_ID) { string descr; //--switch(deal_type) { case DEAL_TYPE_BALANCE: return ("balance"); case DEAL_TYPE_CREDIT: return ("credit"); case DEAL_TYPE_CHARGE: return ("charge"); case DEAL_TYPE_CORRECTION: return ("correction"); case DEAL_TYPE_BUY: descr="buy"; break; case DEAL_TYPE_SELL: descr="sell"; break; } descr=StringFormat("%s %G %s (order #%d, position ID %d)", descr, // current description volume, // deal volume symbol, // deal symbol ticket, // ticket of the order that caused the deal pos_ID // ID of a position, in which the deal is included ); return(descr); //--}
623
Trade Functions
624
Trade Functions
HistoryDealGetDouble
Returns the requested property of a deal. The deal property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double HistoryDealGetDouble( ulong ticket_number, // Ticket // Property identifier ENUM_DEAL_PROPERTY_DOUBLE property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetDouble( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_DEAL_PROPERTY_DOUBLE property_id, double& ); double_var
Parameters ticket_number [in] Deal ticket. property_id [in] Identifier of a deal property. The value can be one of the values ENUM_DEAL_PROPERTY_DOUBLE enumeration. double_var [out] Variable of the double type that accepts the value of the requested property. Return Value Value of the double type. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. See also HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties of the
625
Trade Functions
HistoryDealGetInteger
Returns the requested property of a deal. The deal property must be of the datetime, int type. There are 2 variants of the function. 1. Immediately returns the property value.
long HistoryDealGetInteger( ulong ticket_number, // Ticket // Property identifier ENUM_DEAL_PROPERTY_INTEGER property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetInteger( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_DEAL_PROPERTY_INTEGER property_id, long& ); long_var
Parameters ticket_number [in] Trade ticket. property_id [in] Identifier of the deal property. The value can be one of the values of the ENUM_DEAL_PROPERTY_INTEGER enumeration. long_var [out] Variable of the long type that accepts the value of the requested property. Return Value Value of the long type. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. See also HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
626
Trade Functions
HistoryDealGetString
Returns the requested property of a deal. The deal property must be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string HistoryDealGetString( ulong ticket_number, // Ticket // Property identifier ENUM_DEAL_PROPERTY_STRING property_id );
2. Returns true or false, depending on the success of the function. If successful, the value of the property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetString( ulong ticket_number, // Ticket // Property identifier // Here we accept the property value ENUM_DEAL_PROPERTY_STRING property_id, string& ); string_var
Parameters ticket_number [in] Deal ticket. property_id [in] Identifier of the deal property. The value can be one of the values of the ENUM_DEAL_PROPERTY_STRING enumeration. string_var [out] Variable of the string type that accepts the value of the requested property. Return Value Value of the string type. Note Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each position is the summary result of one or more deals. See also HistorySelect(), HistoryDealsTotal(), HistoryDealSelect(), Deal Properties
627
GlobalVariableTime
GlobalVariableSet GlobalVariablesFlush
GlobalVariableTemp
GlobalVariableSetOnCondition
GlobalVariablesDeleteAll
GlobalVariablesTotal
628
GlobalVariableCheck
Checks the existence of a global variable with the specified name
bool GlobalVariableCheck( string name ); // Global variable name
Parameters name [in] Global variable name. Return Value Returns true, if the global variable exists, otherwise returns false. Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted. See also GlobalVariableTime()
629
GlobalVariableTime
Returns the time when the global variable was last accessed.
datetime GlobalVariableTime( string name ); // name
Parameters name [in] Name of the global variable. Return Value The function returns time of last accessing the specified global variable. Calling a variable to obtain value is also considered as an access to it. In order to obtain error details, call the GetLastError() function. Note Global variables exist in the client terminal during 4 weeks since they were called last. After that they are automatic ally deleted. See also GlobalVariableCheck()
630
GlobalVariableDel
Deletes a global variable from the client terminal.
bool GlobalVariableDel( string name ); // Global variable name
Parameters name [in] Global variable name. Return Value If successful, the function returns true, otherwise it returns false. To obtain an information about the error it is necessary to call the function GetLastError(). Note Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted.
631
GlobalVariableGet
Returns the value of an existing global variable of the client terminal. There are 2 variants of the function. 1. Immediately returns the value of the global variable.
double GlobalVariableGet( string name ); // Global variable name
2. Returns true or false depending on the success of the function run. If successful, the global variable of the client terminal is placed in a variable passed by reference in the second parameter.
bool GlobalVariableGet( string name, double&double_var ); // Global variable name // This variable will contain the value of the global variable
Parameters name [in] Global variable name. double_var [out] Target variable of the double type, which accepts the value stored in a the global variable of the client terminal. Return Value The value of the existing global variable or 0 in case of an error. For more details about the error, call GetLastError(). Note Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted.
632
GlobalVariableName
Returns the name of a global variable by it's ordinal number.
string GlobalVariableName( int index ); // Global variable number in the list of global variables
Parameters index [in] Sequence number in the list of global variables. It should be greater than or equal to 0 and less than GlobalVariablesTotal(). Return Value Global variable name by it's ordinal number in the list of global variables. For more details about the error, call GetLastError(). Note Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted.
633
GlobalVariableSet
Sets a new value for a global variable. If the variable does not exist, the system creates a new global variable.
datetime GlobalVariableSet( string name, double value ); // Global variable name // Value to set
Parameters name [in] Global variable name. value [in] The new numerical value. Return Value If successful, the function returns the last modification time, otherwise 0. For more details about the error, call GetLastError(). Note Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted.
634
GlobalVariablesFlush
Forcibly saves contents of all global variables to a disk.
void GlobalVariablesFlush();
Return Value No return value. Note The terminal writes all the global variables when the work is over, but data can be lost at a sudden computer operation failure. This function allows independently controlling the process of saving global variables in case of contingency.
635
GlobalVariableTemp
The function attempts to create a temporary global variable. If the variable doesn't exist, the system creates a new temporary global variable.
bool GlobalVariableTemp( string name ); // Global variable name
Parameters name [in] The name of a temporary global variable. Return Value If successful, the function returns true, otherwise - false. For details about the error, to call GetLastError(). Note Temporary global variables exist only while the client terminal is running; after the terminal shutdown they are automatically deleted. Note that during the execution of GlobalVariablesFlush() temporary global variables are not written to a disk. After a temporary global variable has been created, it can be accessed and modified the same as global variable of the client terminal.
636
GlobalVariableSetOnCondition
Sets the new value of the existing global variable if the current value equals to the third parameter check_value. If there is no global variable, the function will generate an error ERR_GLOBALVARIABLE_NOT_FOUND (4501) and return false.
bool GlobalVariableSetOnCondition( string name, double value, double check_value ); // Global variable name // New value for variable if condition is true // Check value condition
Parameters name [in] The name of a global variable. value [in] New value. check_value [in] The value to check the current value of the global variable. Return Value If successful, the function returns true, otherwise it returns false. For details about the error call GetLastError(). If the current value of the global variable is different from check_value, the function returns false. Note Function provides atomic access to the global variable, so it can be used for providing of a semaphore at interaction of several Expert Advisors working simultaneously within one client terminal.
637
GlobalVariablesDeleteAll
Deletes global variables of the client terminal.
int GlobalVariablesDeleteAll( string prefix_name=NULL, // All global variables with names beginning with the prefix // All global variables that were changed before this date datetime limit_data=0 );
Parameters prefix_name=NULL [in] Name prefix global variables to remove. If you specify a prefix NULL or empty string, then all variables that meet the data criterion will be deleted. limit_data=0 [in] Date to select global variables by the time of their last modification. The function removes global variables, which were changed before this date. If the parameter is zero, then all variables that meet the first criterion (prefix) are deleted. Return Value The number of deleted variables. Note If both options are equal to zero (prefix_name = NULL and limit_data = 0), then function deletes all global variables of the terminal. If both parameters are specified, then it deletes global variables corresponding to both parameters. Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted.
638
GlobalVariablesTotal
Returns the total number of global variables of the client terminal.
int GlobalVariablesTotal();
Return Value Number of global variables. Note Global variables exist in the client terminal during 4 weeks since their last use, then they are automatically deleted. Call of a global variable is not only setting a new value, but also reading the value of the global variable.
639
File Functions
File Functions
This is a group of functions for working with files. For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. There are two directories (with subdirectories) in which working files can be located: terminal_path\MQL5\FILES\ (in the terminal menu select to view "File" - "Open the data directory"); the common folder for all the terminals installed on a computer - usually located in the directory C: \Documents and Settings\All Users\Application Data\MetaQuotes\Terminal\Common\. There is a program method to obtain names of these catalogs using the TerminalInfoString() function, using the ENUM_TERMINAL_INFO_STRING enumerations:
//--- Folder that stores the terminal data string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH); //--- Common folder for all client terminals string common_data_path=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
Work with files from other directories is prohibited. Function FileFindFirst Action Starts the search of files in a directory in accordance with the specified filter Continues the search FileFindFirst() function Closes search handle Opens a file with a specified name and flag Deletes a specified file Writes to a disk all data remaining in the input/output file buffer Defines the end of a file in the process of reading Defines the end of a line in a text file in the process of reading Closes a previously opened file Checks the existence of a file Copies the original file from a local or shared folder to another file Moves or renames a file Reads arrays of any type except for string from the file of the BIN type started by the
FileFindNext
FileIsEnding
FileIsLineEnding
FileMove FileReadArray
640
File Functions
FileReadBool
Reads from the file of the CSV type a string from the current position till a delimiter (or till the end of a text line) and converts the read string to a value of bool type Reads from the file of the CSV type a string of one of the formats: "YYYY.MM.DD HH:MI:SS", "YYYY.MM.DD" or "HH:MI:SS" - and converts it into a datetime value Reads a double value from the current position of the file pointer Reads a float value from the current position of the file pointer Reads int, short or char value from the current position of the file pointer Reads a long type value from the current position of the file pointer Reads from the file of the CSV type a string from the current position till a delimiter (or til the end of a text line) and converts the read string into double value Reads a string from the current position of a file pointer from a file Reads from a binary file contents into a structure passed as a parameter, from the current position of the file pointer Moves the position of the file pointer by a specified number of bytes relative to the specified position Returns the size of a corresponding open file Returns the current position of the file pointer of a corresponding open file Writes data to a file of CSV or TXT type Writes arrays of any type except for string into a file of BIN type Writes value of the double type from the current position of a file pointer into a binary file Writes value of the float type from the current position of a file pointer into a binary file Writes value of the int type from the current position of a file pointer into a binary file
FileReadDatetime
FileReadDouble
FileReadFloat
FileReadInteger
FileReadLong
FileReadNumber
FileReadString
FileReadStruct
FileSeek
FileSize FileTell
FileWrite FileWriteArray
FileWriteDouble
FileWriteFloat
FileWriteInteger
641
File Functions
FileWriteLong
Writes value of the long type from the current position of a file pointer into a binary file Writes the value of a string parameter into a BIN or TXT file starting from the current position of the file pointer Writes the contents of a structure passed as a parameter into a binary file, starting from the current position of the file pointer
FileWriteString
FileWriteStruct
FolderCreate FolderDelete Removes a selected directory. If the folder is not empty, then it can't be removed Deletes all files in the specified folder
FolderClean
If the file is opened for writing using FileOpen(), all subfolders specified in the path will be created if there are no such ones.
642
File Functions
FileFindFirst
The function starts the search of files in a directory in accordance with the specified filter.
long FileFindFirst( string file_filter, // String - search filter // Name of the file found // Defines the search string& returned_filename, int ); common_flag
Parameters file_filter [in] Search filter. A subdirectory (or sequence of nested subdirectories) relative to the \Files directory, in which files should be searched for, can be specified in the filter. returned_filename [out] The returned parameter, where, in case of success, the name of the first found file is placed. common_flag [in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder. Return Value Returns handle of the object searched, which should be used for further sorting of files by the FileFindNext() function, or INVALID_HANDLE when there is no file corresponding to the filter (in the particular case - when the directory is empty). After searching handle must be closed using the FileFindClose() function. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. Example:
void OnStart() { string filename; //--int found=FileFindFirst("*.*",filename); if(found!=INVALID_HANDLE) Print("FileFindFirst returned ",filename); else { Print("Files not found!!! Continue search in Common"); found=FileFindFirst("*.*",filename,FILE_COMMON); if(found!=INVALID_HANDLE) Print("FileFindFirst in Common returned ",filename); }
643
File Functions
}
644
File Functions
FileFindNext
The function continues the search started by FileFindFirst().
bool FileFindNext( long string& ); search_handle, returned_filename // Search handle // Name of the file found
Parameters search_handle [in] Search handle, retrieved by FileFindFirst(). returned_filename [out] The name of the next file or directory found. Return Value If successful returns true, otherwise false. Example:
void OnStart() { string filename; int i=0; //--int search=FileFindFirst("*.*",filename); if(search!=INVALID_HANDLE) { Print("FileFindFirst returned ",filename); while(FileFindNext(search,filename)) { i++; Print(i,":",filename); } FileFindClose(filename); } else Print("Files not found!!!"); }
645
File Functions
FileFindClose
The function closes the search handle.
void FileFindClose( long search_handle ); // Search handle
Parameters search_handle [in] Search handle, retrieved by FileFindFirst(). Return Value No value returned. Note Function must be called to free up system resources.
646
File Functions
FileIsExist
Checks the existence of a file.
bool FileIsExist( string file_name, int ); common_flag=0 // File name // Search area
Parameters file_name [in] The name of the file being checked common_flag=0 [in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder. Return Value Returns true, if the specified file exists. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. If common_flag = FILE_COMMON, then the function looks for the file in a shared folder for all client terminals, otherwise the function looks for a file in a local folder (MQL5 \ Files or MQL5 \ Tester \ Files in the case of testing).
647
File Functions
FileOpen
The function opens the file with the specified name and flag.
int FileOpen( string file_name, int short uint ); open_flags, delimiter='\t' codepage=CP_ACP // File name // Combination of flags // Delimiter // Code page
Parameters file_name [in] The name of the file can contain subfolders. If the file is opened for writing, these subfolders will be created if there are no such ones. open_flags [in] combination of flags determining the operation mode for the file. The flags are defined as follows: FILE_READ file is opened for reading FILE_WRITE file is opened for writing FILE_BIN binary read-write mode (no conversion from a string and to a string) FILE_CSV file of csv type (all recorded items are converted to the strings of unicode or ansi type, and are separated by a delimiter) FILE_TXT a simple text file (the same as csv, but the delimiter is not taken into account) FILE_ANSI lines of ANSI type (single-byte symbols) FILE_UNICODE lines of UNICODE type (double-byte characters) FILE_SHARE_READ shared reading from several programs FILE_SHARE_WRITE shared writing from several programs FILE_COMMON location of the file in a shared folder for all client terminals delimiter='\t' [in] value to be used as a separator in txt or csv-file. If the csv-file delimiter is not specified, it defaults to a tab. If the txt-file delimiter is not specified, then no separator is used. If the separator is clearly set to 0, then no separator is used. codepage=CP_ACP [in] The value of the code page. For the most-used code pages provide appropriate constants. Return Value If a file has been opened successfully, the function returns the file handle, which is then used to access the file data. In case of failure returns INVALID_HANDLE. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. The file is opened in the folder of the client terminal in the subfolder MQL5\files (or MQL5 \tester\files in case of testing). If FILE_COMMON is specified among flags, the file is opened in a shared folder for all MetaTrader 5 client terminals.
648
649
File Functions
FileClose
Close the file previously opened by FileOpen().
void FileClose( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value No value returned.
650
File Functions
FileCopy
The function copies the original file from a local or shared folder to another file.
bool FileCopy( string src_filename, int common_flag, // Name of a source file // Location // Name of the destination file // Access mode
Parameters src_filename [in] File name to copy. common_flag [in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder. dst_filename [in] Result file name. mode_flags [in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or FILE_COMMON other flags are ignored. If the file already exists, and the FILE_REWRITE flag hasn't been specified, then the file will not be rewritten, and the function will return false. Return Value In case of failure the function returns false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. If the new file already exists, the copy will be made depending on the availability of the FILE_REWRITE flag in the mode_flags parameter.
651
File Functions
FileDelete
Deletes the specified file in a local folder of the client terminal.
bool FileDelete( string file_name int ); // File name to delete common_flag=0 // Location of the file to delete
Parameters file_name [in] File name. common_flag=0 [in] Flag determining the file location. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder. Return Value In case of failure the function returns false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. Deletes the specified file from a local folder of the client terminal (MQL5\files or MQL5\tester\files in case of testing). If common_flag = FILE_COMMON, then the function removes the file from the shared folder for all client terminals.
652
File Functions
FileMove
Moves a file from a local or shared folder to another folder.
bool FileMove( string src_filename, int common_flag, // File name for the move operation // Location // Name of the destination file // Access mode
Parameters src_filename [in] File name to move/rename. common_flag [in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder. dst_filename [in] File name after operation mode_flags [in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or FILE_COMMON other flags are ignored. If the file already exists and the FILE_REWRITE flag isn't specified, the file will not be rewritten, and the function will return false. Return Value In case of failure the function returns false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. If the new file already exists, the copy will be made depending on the availability of the FILE_REWRITE flag in the mode_flags parameter.
653
File Functions
FileFlush
Writes to a disk all data remaining in the input/output file buffer.
void FileFlush( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value No value returned. Note Function FileFlush () must be called between the operations of reading from a file and write to a file.
654
File Functions
FileIsEnding
Defines the end of a file in the process of reading.
bool FileIsEnding( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The function returns true if the file end has been reached in the process of reading or moving of the file pointer.
655
File Functions
FileIsLineEnding
Defines the line end in a text file in the process of reading.
bool FileIsLineEnding( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value Returns true if in the process of reading txt or csv-file reached the end of the line (the characters CR-LF).
656
File Functions
FileReadArray
Reads from a file of BIN type arrays of any type except string (may be an array of structures, not containing strings, and dynamic arrays).
uint FileReadArray( int file_handle void array[], int int ); start_item=0, items_count=WHOLE_ARRAY // File handle // Array to record // start array position to write // count to read
Parameters file_handle [in] File descriptor returned by FileOpen(). array[] [out] An array where the data will be loaded. start_item=0 [in] Start position to write to the array. items_count=WHOLE_ARRAY [in] Number of elements to read. By default, reads the entire array (cnt=WHOLE_ARRAY). Return Value Number of elements read. Note String array can be read only from the file of TXT type. If necessary, the function tries to increase the size of the array. See also Variables
657
File Functions
FileReadBool
Reads from the file of CSV type string from the current position to a delimiter (or till the end of the text line) and converts the read string to a bool type value.
bool FileReadBool( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value Line read may be set to "true", "false" or the symbolic representation of integers "0" or "1". A nonzero value is converted to a logical true. The function returns the converted value. See also Type bool
658
File Functions
FileReadDatetime
Reads from the file of CSV type a string of one of the formats: "YYYY.MM.DD HH:MI:SS", "YYYY.MM. DD" or "HH:MI:SS" - and converts it into a value of datetime type.
datetime FileReadDatetime( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of datetime type. See also Type datetime, StringToTime, TimeToString
659
File Functions
FileReadDouble
Reads a double-precision floating point number (double) from the current position of the binary file.
double FileReadDouble( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of double type. Note For more details about the error, call GetLastError(). See also Real types (double, float), StringToDouble, DoubleToString
660
File Functions
FileReadFloat
Reads the single-precision floating point number (float) from the current position of the binary file.
float FileReadFloat( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of float type. Note For more details about the error, call GetLastError(). See also Real types (double, float), FileReadDouble
661
File Functions
FileReadInteger
The function reads int, short or char value from the current position of the file pointer depending on the length specified in bytes.
int FileReadInteger( int file_handle int size=INT_VALUE ); // File handle // Size of an integer in bytes
Parameters file_handle [in] File descriptor returned by FileOpen(). size=INT_VALUE [in] Number of bytes (up to 4 inclusive), that should be written. The corresponding constants are provided: CHAR_VALUE = 1, SHORT_VALUE = 2 and INT_VALUE = 4, so the function can read the whole value of char, short or int type. Return Value The value of int type. Since the int type value is returned, it can be converted to any integer, signed or unsigned value. File pointer is moved by the number of bytes of the read integer type. See also IntegerToString, StringToInteger, Integer types
662
File Functions
FileReadLong
The function reads an integer of long type (8 bytes) from the current position of the binary file.
long FileReadLong( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of long type. See also Integer types, FileReadInteger
663
File Functions
FileReadNumber
The function reads from the CSV file a string from the current position till a separator (or till the end of a text string) and converts the read string to a value of double type.
double FileReadNumber( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of double type.
664
File Functions
FileReadString
The function reads from a string from the current position of a file pointer in a file.
string FileReadString( int file_handle int size=-1 ); // File handle // Length of the string
Parameters file_handle [in] File descriptor returned by FileOpen(). size=-1 [in] Number of characters to read. Return Value Line read (string). Note When reading from a bin-file. the length of a string to read must be specified. When reading from a txt-file the string length is not required, and the string will be read from the current position to the line feed character "\r\n". When reading from a csv-file, the string length isn't required also, the string will be read from the current position till the nearest delimiter or till the text string end character. If the file is opened with FILE_ANSI flag, then the line read is converted to Unicode. See also Type string, Data Conversion
665
File Functions
FileReadStruct
The function reads contents into a structure passed as a parameter from a bin-file, starting with the current position of the file pointer.
uint FileReadStruct( int file_handle // File handle // target structure to read to // structure size in bytes any_simple_struct str_object, int ); size=-1
Parameters file_handle [in] File descriptor of an open bin-file. str_object [out] The object of this structure. The structure should not contain strings, dynamic arrays or virtual functions. size=-1 [in] Number of bytes that should be read. If size is not specified or the indicated value is greater than the size of the structure, the exact size of the specified structure is used. Return Value If successful the function returns the number of bytes read. File pointer is moved by the same number of bytes. See also Structures and classes
666
File Functions
FileSeek
The function moves the position of the file pointer by a specified number of bytes relative to the specified position.
void FileSeek( int long ENUM_FILE_POSITION ); file_handle offset, origin // File handle // In bytes // Position for reference
Parameters file_handle [in] File descriptor returned by FileOpen(). offset [in] The shift in bytes (may take a negative value). origin [in] The starting point for the displacement. Can be one of values of ENUM_FILE_POSITION. Return Value No value returned. Note If the execution of the FileSeek() function results in a negative shift (going beyond the "level boundary" of the file), the file pointer will be set to the file beginning. If a position is set beyond the "right boundary" of the file (larger than the file size), the next writing to the file will be performed not from the end of the file, but from the position set. In this case indefinite values will be written for the previous file end and the position set.
667
File Functions
FileSize
The function returns the file size in bytes.
ulong FileSize( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value The value of type int. Note To obtain information about the error call GetLastError().
668
File Functions
FileTell
The file returns the current position of the file pointer of an open file.
ulong FileTell( int file_handle ); // File handle
Parameters file_handle [in] File descriptor returned by FileOpen(). Return Value Current position of the file descriptor in bytes from the beginning of the file. Note To obtain information about the error call GetLastError().
669
File Functions
FileWrite
The function is intended for writing of data into a CSV file, delimiter being inserted automatically unless it is equal to 0. After writing into the file, the line end character "\r\n" will be added.
uint FileWrite( int file_handle ... ); // File handle // List of recorded parameters
Parameters file_handle [in] File descriptor returned by FileOpen(). ... [in] The list of parameters separated by commas, to write to the file. The number of written parameters can be up to 63. Return Value Number of bytes written. Note Numbers will be converted into a text at output (see the Print() function). Data of the double type are output with the accuracy of 16 digits after the decimal point, and the data can be displayed either in traditional or in scientific format - depending on which format will be the most compact. The data of the float type are shown with 5 digits after the decimal point. To output real numbers with different precision or in a clearly specified format, use DoubleToString(). Numbers of the bool type are displayed as "true" or "false" strings. Numbers of the datetime type are displayed as "YYYY.MM.DD HH:MI:SS". See also Comment, Print, StringFormat
670
File Functions
FileWriteArray
The function writes arrays of any type except for string to a BIN file (can be an array of structures not containing strings or dynamic arrays).
int FileWriteArray( int file_handle // File handle // Array // Start index in the array // Number of elements void array[], int int ); start_item=0, items_count=WHOLE_ARRAY
Parameters file_handle [in] File descriptor returned by FileOpen(). array[] [out] Array for recording. start_item=0 [in] Initial index in the array (number of the first recorded element). items_count=WHOLE_ARRAY [in] Number of items to record (WHOLE_ARRAY means that records all items starting with the number start_item until the end of the array). Return Value Number of recorded items. Note String array can be recorded in a TXT file. In this case, strings are automatically ended by the line end characters "\r\n". Depending on the file type ANSI or UNICODE, strings are either converted to ansi-encoding or not. See also Variables
671
File Functions
FileWriteDouble
The function writes the value of a double parameter to a file, starting from the current position of the file pointer.
uint FileWriteDouble( int file_handle // File handle // Value to write double dvalue );
Parameters file_handle [in] File descriptor returned by FileOpen(). dvalue [in] The value of double type. Return Value If successful the function returns the number of bytes written (in this case sizeof(double)=8). The file pointer is shifted by the same number of bytes. See also Real types (double, float)
672
File Functions
FileWriteFloat
The function writes the value of the float parameter to a bin-file, starting from the current position of the file pointer.
uint FileWriteFloat( int file_handle // File handle // Value to be written float fvalue );
Parameters file_handle [in] File descriptor returned by FileOpen(). fvalue [in] The value of float type. Return Value If successful the function returns the number of bytes written (in this case sizeof(float)=4). The file pointer is shifted by the same number of bytes. See also Real types (double, float), FileWriteDouble
673
File Functions
FileWriteInteger
The function writes the value of the int parameter to a bin-file, starting from the current position of the file pointer.
uint FileWriteInteger( int file_handle int ivalue, int size=INT_VALUE ); // File handle // Value to be written // Size in bytes
Parameters file_handle [in] File descriptor returned by FileOpen(). ivalue [in] Integer value. size=INT_VALUE [in] Number of bytes (up to 4 inclusive), that should be written. The corresponding constants are provided: CHAR_VALUE=1, SHORT_VALUE=2 and INT_VALUE=4, so the function can write the integer value of char, uchar, short, ushort, int, or uint type. Return Value If successful the function returns the number of bytes written. The file pointer is shifted by the same number of bytes. See also IntegerToString, StringToInteger, Integer types
674
File Functions
FileWriteLong
The function writes the value of the long-type parameter to a bin-file, starting from the current position of the file pointer.
uint FileWriteLong( int file_handle // File handle // Value to be written long lvalue );
Parameters file_handle [in] File descriptor returned by FileOpen(). lvalue [in] Value of type long. Return Value If successful the function returns the number of bytes written (in this case sizeof(long)=8). The file pointer is shifted by the same number of bytes. See also Integer types, FileWriteInteger
675
File Functions
FileWriteString
The function writes the value of a string-type parameter into a BIN or TXT file starting from the current position of the file pointer. When writing to a TXT file: if there is a symbol in the string '\n' (LF) without previous character '\r' (CR), then before '\n' the missing '\r' is added.
uint FileWriteString( int file_handle // File handle // string to write // number of symbols string svalue, int ); size=-1
Parameters file_handle [in] File descriptor returned by FileOpen(). svalue [in] String. size=-1 [in] The number of characters that you want to write. This option is needed for writing a string into a BIN file. If the size is not specified, then the entire string without the trailer 0 is written. If you specify a size smaller than the length of the string, then a part of the string without the trailer 0 is written. If you specify a size greater than the length of the string, the string is filled by the appropriate number of zeros. For files of TXT type, this parameter is ignored and the string is written entirely. Return Value If successful the function returns the number of bytes written. The file pointer is shifted by the same number of bytes. Note Note that when writing to a file opened by the FILE_UNICODE flag (or without a flag FILE_ANSI), then the number of bytes written will be twice as large as the number of string characters written. When recording to a file opened with the FILE_ANSI flag, the number of bytes written will coincide with the number of string characters written. See also Type string, StringFormat
676
File Functions
FileWriteStruct
The function writes into a bin-file contents of a structure passed as a parameter, starting from the current position of the file pointer.
uint FileWriteStruct( int file_handle // File handle // link to an object // size to be written in bytes any_simple_struct str_object&, int ); size=-1
Parameters file_handle [in] File descriptor returned by FileOpen(). str_object& [in] Reference to the object of this structure. The structure should not contain strings, dynamic arrays or virtual functions. size=-1 [in] Number of bytes that you want to record. If size is not specified or the specified number of bytes is greater than the size of the structure, the entire structure is written. Return Value If successful the function returns the number of bytes written. The file pointer is shifted by the same number of bytes. See also Structures and classes
677
File Functions
FolderCreate
The function creates a directory in the Files directory (depending on the value of common_flag).
bool FolderCreate( string folder_name, int ); common_flag=0 // String with the name of the new folder // Scope
Parameters folder_name [in] The name of the directory you want to create. Contains the full path to the folder. common_flag=0 [in] Flag determining the location of the directory. If common_flag=FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder (MQL5\files or MQL5\tester\files in case of testing). Return Value Returns true if successful, otherwise - false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox.
678
File Functions
FolderDelete
The function removes the specified directory. If the folder is not empty, then it can't be removed.
bool FolderDelete( string folder_name, int ); common_flag=0 // String with the name of the folder to delete // Scope
Parameters folder_name [in] The name of the directory you want to delete. Contains the full path to the folder. common_flag=0 [in] Flag determining the location of the directory. If common_flag=FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder (MQL5\files or MQL5\tester\files in the case of testing). Return Value Returns true if successful, otherwise false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. If the directory contains at least one file and/or subdirectory, then this directory can't be deleted, it must be cleared first. FolderClean() is used to clear a folder of all its files or subfolders.
679
File Functions
FolderClean
The function deletes all files in a specified folder.
bool FolderClean( string folder_name, int ); common_flag=0 // String with the name of the deleted folder // Scope
Parameters folder_name [in] The name of the directory where you want to delete all files. Contains the full path to the folder. common_flag=0 [in] Flag determining the location of the directory. If common_flag = FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder (MQL5\files or MQL5\tester\files in case of testing). Return Value Returns true if successful, otherwise false. Note For security reasons, work with files is strictly controlled in the MQL5 language. Files with which file operations are conducted using MQL5 means, cannot be outside the file sandbox. This function should be used with caution, since all the files and all subdirectories are deleted irretrievably.
680
Custom Indicators
Custom Indicators
This is the group functions used in the creation of custom indicators. These functions can't be used when writing Expert Advisors and Scripts. Function SetIndexBuffer Action Binds the specified indicator buffer with onedimensional dynamic array of the double type Sets the value of an indicator property of the double type Sets the value of an indicator property of the int type Sets the value of an indicator property of the string type Sets the value of an indicator line property of the type double Sets the value of an indicator line property of the int type Sets the value of an indicator line property of the string type Returns the value of an indicator line property of the integer type
IndicatorSetDouble
IndicatorSetInteger
IndicatorSetString
PlotIndexSetDouble
PlotIndexSetInteger
PlotIndexSetString
PlotIndexGetInteger
All the necessary calculations of a custom indicator must be placed in the predetermined function OnCalculate(). If you use a short form of the OnCalculate() function call, like
int OnCalculate (const int rates_total, const int prev_calculated, const int begin, const double& p
then the rates_total variable contains the value of the total number of elements of the price[] array, passed as an input parameter for calculating indicator values. Parameter prev_calculated is the result of the execution of OnCalculate() at the previous call; it allows organizing a saving algorithm for calculating indicator values. For example, if the current value rates_total = 1000, prev_calculated = 999, then perhaps it's enough to make calculations only for one value of each indicator buffer. If the information about the size of the input array price would have been unavailable, then it would lead to the necessity to make calculations for 1000 values of each indicator buffer. At the first call of OnCalculate() value prev_calculated = 0. If the price[] array has changed somehow, then in this case prev_calculated is also equal to 0. The begin parameter shows the number of initial values of the price array, which don't contain data for calculation. For example, if values of Accelerator Oscillator (for which the first 37 values aren't calculated) were used as an input parameter, then begin = 37. For example, let's consider a simple indicator:
#property indicator_chart_window
681
Custom Indicators
#property indicator_buffers 1 #property indicator_plots //---- plot Label1 #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- indicator buffers double Label1Buffer[]; | //+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA); //--} //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const int begin, const double &price[]) { //--Print("begin = ",begin," return(rates_total); } prev_calculated = ",prev_calculated," rates_total = ",rates_total); //--- return value of prev_calculated for next call | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ "Label1" DRAW_LINE Red STYLE_SOLID 1 1
Drag it from the "Navigator" window to the window of the Accelerator Oscillator indicator and we indicate that calculations will be made based on the values of the previous indicator:
682
Custom Indicators
As a result, the first call of OnCalculate() the value of prev_calculated will be equal to zero, and in further calls it will be equal to the rates_total value (until the number of bars on the price chart increases).
The value of the begin parameter will be exactly equal to the number of initial bars, for which the values of the Accelerator indicator aren't calculated according to the logic of this indicator. If we look at the source code of the custom indicator Accelerator.mq5, we'll see the following lines in the OnInit() function:
//--- sets first bar from what index will be drawn PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,37);
Using the function PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, empty_first_values), we set the number of non-existing first values in the zero indicator array of a custom indicator, which we don't
683
Custom Indicators need to accept for calculation (empty_first_values). Thus, we have mechanisms to: 1. set the number of initial values of an indicator, which shouldn't be used for calculations in another custom indicator; 2. get information on the number of first values to be ignored when you call another custom indicator, without going into the logic of its calculations.
684
Custom Indicators
indicator_maximum
indicator_levelN
no preprocessor directive
indicator_levelcolor
Color of N level N-
indicator_levelwidth
indicator_levelstyle
Description of the adjusted property of a plot Short name of the number N plot. It is displayed in DataWindow and in the pop-up tooltip when pointing the mouse cursor over it Line color for N plot
indicator_colorN
PlotIndexSetInteger(N-1,
685
Custom Indicators
PLOT_LINE_COLOR, nColor) indicator_styleN PlotIndexSetInteger(N-1, PLOT_LINE_STYLE, nType) PlotIndexSetInteger(N-1, PLOT_DRAW_TYPE, nType) PlotIndexSetInteger(N-1, PLOT_LINE_WIDTH, nWidth) Functions of IndicatorSet... () type IndicatorSetString( INDICATOR_SHORTNAME, sShortName) Line style for N plot
indicator_typeN
indicator_widthN
Description
Sets the convenient short name of the indicator that will be displayed in the list of indicators (opened in the terminal by pressing Ctrl+I). Sets required accuracy of display of indicator values number of decimal places Sets number of levels in the indicator window Default price type used for the indicator calculation. It is specified when necessary, only if OnCalculate() of the first type is used. The property value can also be set from the dialog of indicator properties in the "Parameters" tab - "Apply to".
no preprocessor directive
no preprocessor directive
IndicatorSetInteger( INDICATOR_LEVELS, nLevels) No function, the property can be set only by the preprocessor directive.
indicator_applied_price
It should be noted that numeration of levels and plots in preprocessor terms starts with one, while numeration of the same properties at using functions starts with zero, i.e. the indicated value must be by 1 less than that indicated for #property. There are several directives, for which there are no corresponding functions: Directive indicator_chart_window indicator_separate_window indicator_buffers indicator_plots Description Indicator is displayed in the main window Indicator is displayed in a separate subwindow Number of required indicator buffers Number of plots in the indicator
686
Custom Indicators
SetIndexBuffer
The function binds a specified indicator buffer with one-dimensional dynamic array of the double type announced at the global level.
bool SetIndexBuffer( int double index, buffer[], // buffer index // array // what will be stored
ENUM_INDEXBUFFER_TYPE data_type );
Parameters index [in] Number of the indicator buffer. The numbering starts with 0. The number must be less than the value declared in #propertyindicator_buffers. buffer[] [in] An array declared in the custom indicator program. data_type [in] Type of data stored in the indicator array. By default it is INDICATOR_DATA (values of the calculated indicator). It may also take the value of INDICATOR_COLOR_INDEX; in this case this buffer is used for storing color indexes for the previous indicator buffer. You can specify up to 64 colors in the #propertyindicator_colorN line. The INDICATOR_CALCULATIONS value means that the buffer is used in intermediate calculations of the indicator and is not intended for drawing. Return Value If successful, returns true, otherwise - false. Note After binding, the dynamic array buffer[] will be indexed as in common arrays, even if the indexing of timeseries is pre-installed for the bound array. If you want to change the order of access to elements of the indicator array, use the ArraySetAsSeries() function after binding the array using the SetIndexBuffer() function. Please note that you can't change the size for dynamic arrays set as indicator buffers by the function SetIndexBuffer(). For indicator buffers, all operations of size changes are performed by the executing sub-system of the terminal. Example:
//+------------------------------------------------------------------+ //| //| //| TestCopyBuffer1.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00"
687
Custom Indicators
#property indicator_plots //---- plot MA #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- input parameters input bool input int input ENUM_MA_METHOD input int //--- indicator buffers double int MABuffer[]; ma_handle; | AsSeries=true; period=15; smootMode=MODE_EMA; shift=0; "MA" DRAW_LINE Red STYLE_SOLID 1 1
//+------------------------------------------------------------------+ //| Custom indicator initialization function int OnInit() { //--- indicator buffers mapping if(AsSeries) ArraySetAsSeries(MABuffer,true); Print("Indicator buffer is timeseries = ",ArrayGetAsSeries(MABuffer)); SetIndexBuffer(0,MABuffer,INDICATOR_DATA); Print("Indicator buffer after SetIndexBuffer() is timeseries = ", ArrayGetAsSeries(MABuffer)); //--- change the oredr of accessing elements of the indicator buffer ArraySetAsSeries(MABuffer,AsSeries); IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries); //--ma_handle=iMA(Symbol(),0,period,shift,smootMode,price); return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
688
Custom Indicators
const int &spread[]) { //--- Copy the values of the moving average in the buffer MABuffer int copied=CopyBuffer(ma_handle,0,0,rates_total,MABuffer); Print("MABuffer[0] = ",MABuffer[0]);// Depending on the value AsSeries // Will receive a very old value // Or for the current unfinished bar //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+
689
Custom Indicators
IndicatorSetDouble
The function sets the value of the corresponding indicator property. Property of the indicator should be of the double type. There are 2 variants of the function. Call indicating identifier of the property.
bool IndicatorSetDouble( int prop_id, // identifier // value to be set double prop_value );
double prop_value )
Parameters prop_id [in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_DOUBLE enumeration. prop_modifier [in] Modifier of the specified property. Only level properties require a modifier. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise - false.
690
Custom Indicators
IndicatorSetInteger
The function sets the value of the corresponding indicator property. The property must be of int or color type. There are 2 variants of the function. Call indicating identifier of the property.
bool IndicatorSetInteger( int prop_id, int prop_value ); // identifier // value to be set
Parameters prop_id [in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_INTEGER enumeration. prop_modifier [in] Modifier of the specified property. Only level properties require a modifier. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise - false.
691
Custom Indicators
IndicatorSetString
The function sets the value of a corresponding indicator property. The indicator property must be of the string type. There are 2 variants of the function. Call indicating identifier of the property.
bool IndicatorSetString( int prop_id, // identifier // value to be set string prop_value );
string prop_value )
Parameters prop_id [in] The value can be one of the values of the ENUM_CUSTOMIND_PROPERTY_STRING enumeration. prop_modifier [in] Modifier of the specified property. Only level properties require a modifier. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise - false.
692
Custom Indicators
PlotIndexSetDouble
The function sets the value of the corresponding property of the corresponding indicator line. The indicator property must be of the double type.
bool PlotIndexSetDouble( int int plot_index, prop_id, // plotting style index // property identifier // value to be set
double prop_value );
Parameters plot_index [in] Index of the graphical plotting prop_id [in] The value can be one of the values of the ENUM_PLOT_PROPERTY_DOUBLE enumeration. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise false.
693
Custom Indicators
PlotIndexSetInteger
The function sets the value of the corresponding property of the corresponding indicator line. The indicator property must be of the int, char, bool or color type. There are 2 variants of the function. Call indicating identifier of the property.
bool PlotIndexSetInteger( int plot_index, int prop_id, int prop_value ); // plotting style index // property identifier // value to be set
Parameters plot_index [in] Index of the graphical plotting prop_id [in] The value can be one of the values of the ENUM_PLOT_PROPERTY_INTEGER enumeration. prop_modifier [in] Modifier of the specified property. Only level properties require a modifier. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise false. Example: an indicator that draws a three-color line. The color scheme changes every 5 ticks.
694
Custom Indicators
#property indicator_chart_window #property indicator_buffers 2 #property indicator_plots //---- plot ColorLine #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- indicator buffers double double int ColorLineBuffer[]; ColorBuffer[]; MA_handle; | "ColorLine" DRAW_COLOR_LINE Red,Green,Blue STYLE_SOLID 3 1
//+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,ColorLineBuffer,INDICATOR_DATA); SetIndexBuffer(1,ColorBuffer,INDICATOR_COLOR_INDEX); //--- get MA handle MA_handle=iMA(Symbol(),0,10,0,MODE_EMA,PRICE_CLOSE); //--} //+------------------------------------------------------------------+ //| get color index | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
695
Custom Indicators
int getIndexOfColor(int i) { int j=i%300; if(j<100) return(0);// first index if(j<200) return(1);// second index return(2); // third index } //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--static int ticks=0,modified=0; int limit; //--- first calculation or number of bars was changed if(prev_calculated==0) { //--- copy values of MA into indicator buffer ColorLineBuffer int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer); if(copied<=0) return(0);// copying failed - throw away //--- now set line color for every bar for(int i=0;i<rates_total;i++) ColorBuffer[i]=getIndexOfColor(i); } else { //--- copy values of MA into indicator buffer ColorLineBuffer int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer); if(copied<=0) return(0); ticks++;// ticks counting if(ticks>=5)//it's time to change color scheme { ticks=0; // reset counter modified++; // counter of color changes if(modified>=3)modified=0;// reset counter ResetLastError(); switch(modified) | //+------------------------------------------------------------------+
696
Custom Indicators
{ case 0:// first color scheme PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,Red); PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Blue); PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,Green); Print("Color scheme "+modified); break; case 1:// second color scheme PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,Yellow); PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Pink); PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,LightSlateGray); Print("Color scheme "+modified); break; default:// third color scheme PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,LightGoldenrod); PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Orchid); PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,LimeGreen); Print("Color scheme "+modified); } } else { //--- set start position limit=prev_calculated-1; //--- now we set line color for every bar for(int i=limit;i<rates_total;i++) ColorBuffer[i]=getIndexOfColor(i); } } //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+
697
Custom Indicators
PlotIndexSetString
The function sets the value of the corresponding property of the corresponding indicator line. The indicator property must be of the string type.
bool PlotIndexSetString( int int plot_index, prop_id, // plotting style index // property identifier // value to be set
string prop_value );
Parameters plot_index [in] Index of graphical plot prop_id [in] The value can be one of the values of the ENUM_PLOT_PROPERTY_STRING enumeration. prop_value [in] The value of the property. Return Value If successful, returns true, otherwise false.
698
Custom Indicators
PlotIndexGetInteger
The function sets the value of the corresponding property of the corresponding indicator line. The indicator property must be of the int, color, bool or char type. There are 2 variants of the function. Call indicating identifier of the property.
int PlotIndexGetInteger( int plot_index, int prop_id, ); // plotting style index // property identifier
Parameters plot_index [in] Index of the graphical plotting prop_id [in] The value can be one of the values of the ENUM_PLOT_PROPERTY_INTEGER enumeration. prop_modifier [in] Modifier of the specified property. Only level properties require a modifier. Note Function is designed to extract the settings of drawing of the appropriate indicator line. The function works in tandem with the function PlotIndexSetInteger to copy the drawing properties of one line to another. Example: an indicator that colors candles depending on the day of the week. Colors for each day are set in a program way.
699
Custom Indicators
#property indicator_separate_window #property indicator_buffers 5 #property indicator_plots //---- plot ColorCandles #property indicator_label1 #property indicator_type1 #property indicator_style1 #property indicator_width1 //--- indicator buffers double double double double double color OpenBuffer[]; HighBuffer[]; LowBuffer[]; CloseBuffer[]; ColorCandlesColors[]; ColorOfDay[6]={CLR_NONE,MediumSlateBlue, DarkGoldenrod,ForestGreen,BlueViolet,Red}; //+------------------------------------------------------------------+ //| Custom indicator initialization function void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,OpenBuffer,INDICATOR_DATA); SetIndexBuffer(1,HighBuffer,INDICATOR_DATA); SetIndexBuffer(2,LowBuffer,INDICATOR_DATA); SetIndexBuffer(3,CloseBuffer,INDICATOR_DATA); SetIndexBuffer(4,ColorCandlesColors,INDICATOR_COLOR_INDEX); //--- set number of colors in color buffer | //+------------------------------------------------------------------+ "ColorCandles" DRAW_COLOR_CANDLES STYLE_SOLID 1 1
700
Custom Indicators
PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,6); //--- set colors for color buffer for(int i=1;i<6;i++) PlotIndexSetInteger(0,PLOT_LINE_COLOR,i,ColorOfDay[i]); //--- set accuracy IndicatorSetInteger(INDICATOR_DIGITS,_Digits); printf("We have %u colors of days",PlotIndexGetInteger(0,PLOT_COLOR_INDEXES)); //--} //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--int i; MqlDateTime t; //---if(prev_calculated==0) i=0; else i=prev_calculated-1; //---while(i<rates_total) { OpenBuffer[i]=open[i]; HighBuffer[i]=high[i]; LowBuffer[i]=low[i]; CloseBuffer[i]=close[i]; //--- set color for every candle TimeToStruct(time[i],t); ColorCandlesColors[i]=t.day_of_week; //--i++; } //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
701
Object Functions
Object Functions
This is the group of functions intended for working with graphic objects relating to any specified chart. Function ObjectCreate Action Creates an object of the specified type in a specified chart Returns the name of an object of the corresponding type in the specified chart (specified chart subwindow) Removes the object with the specified name from the specified chart (from the specified chart subwindow) Removes all objects of the specified type from the specified chart (from the specified chart subwindow) Searches for an object with the specified ID by the name Returns the time value for the specified object price value Returns the price value of an object for the specified time Changes the coordinates of the specified object anchor point Returns the number of objects of the specified type in the specified chart (specified chart subwindow) Returns the double value of the corresponding object property Returns the integer value of the corresponding object property Returns the string value of the corresponding object property Sets the value of the corresponding object property Sets the value of the corresponding object property Sets the value of the corresponding object property
ObjectName
ObjectDelete
ObjectsDeleteAll
ObjectFind
ObjectGetTimeByValue
ObjectGetValueByTime
ObjectMove
ObjectsTotal
ObjectGetDouble
ObjectGetInteger
ObjectGetString
ObjectSetDouble
ObjectSetInteger
ObjectSetString
702
Object Functions Every graphical object should have a name unique within one chart, including its subwindows. Changing of a name of a graphic object generates two events: event of deletion of an object with the old name, and event of creation of an object with a new name. After an object is created or an object property is modified it is recommended to call the ChartRedraw () function, which commands the client terminal to forcibly draw a chart (and all visible objects in it).
703
Object Functions
ObjectCreate
The function creates an object with the specified name, type, and the initial coordinates in the specified chart subwindow. During creation up to 30 coordinates can be specified.
bool ObjectCreate( long string int int chart_id, name, type, nwin, // chart identifier // object name // object type // window index // time of the first anchor point // price of the first anchor point // time of the N-th anchor point // price of the N-th anchor point // time of the 30th anchor point // price of the 30th anchor point
datetime time1, double ... datetime timeN=0, double ... datetime time30=0, double ); price30=0 priceN=0, price1,
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. The name must be unique within a chart, including its subwindows. type [in] Object type. The value can be one of the values of the ENUM_OBJECT enumeration. nwin [in] Number of the chart subwindow. 0 means the main chart window. The specified subwindow must exist, otherwise the function returns false. time1 [in] The time coordinate of the first anchor. price1 [in] The price coordinate of the first anchor point. timeN=0 [in] The time coordinate of the N-th anchor point. priceN=0 [in] The price coordinate of the N-th anchor point. time30=0 [in] The time coordinate of the thirtieth anchor point. price30=0 [in] The price coordinate of the thirtieth anchor point.
704
Object Functions
Return Value Returns true or false depending on whether the object is created or not. To read more about the error call GetLastError(). If the object has been created already, the function tries to change its coordinates. Note The numbering of the chart subwindows (if there are subwindows with indicators in the chart) starts with 1. The main chart window of the chart is and always has index 0. The large number of anchor points (up to 30) is implemented for future use. At the same time, the limit of 30 possible anchor points for graphical objects is determined by the limit on the number of parameters (not more than 64) that can be used when calling a fucntion. When an object is renamed, two events are formed simultaneously. These events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: an event of deletion of an object with the old name; an event of creation of an object with a new name.
705
Object Functions
ObjectName
The function returns the name of the corresponding object in the specified chart, in the specified subwindow, of the specified type.
string ObjectName( long chart_id, int int int ); pos, nwin=-1, type=-1 // chart identifier // number in the list of objects // window index // object type
Parameters chart_id [in] Chart identifier. 0 means the current chart. pos [in] Ordinal number of the object according to the specified filter by the number and type of the subwindow. nwin=-1 [in] Number of the chart subwindow. 0 means the main chart window, -1 means all the subwindows of the chart, including the main window. type=-1 [in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1 means all types. Return Value Name of the object is returned in case of success. Note When an object is renamed, two events are formed simultaneously. These events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: an event of deletion of an object with the old name; an event of creation of an object with a new name.
706
Object Functions
ObjectDelete
The function removes the object with the specified name from the specified chart.
bool ObjectDelete( long chart_id, // chart identifier // object name string name );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of object to be deleted. Return Value Returns true if the removal was successful, otherwise returns false. To read more about the error call GetLastError(). Note When an object is renamed, two events are formed simultaneously. These events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: an event of deletion of an object with the old name; an event of creation of an object with a new name.
707
Object Functions
ObjectsDeleteAll
Removes all objects from the specified chart, specified chart subwindow, of the specified type.
int ObjectsDeleteAll( long chart_id, int int ); nwin=-1, type=-1 // chart identifier // window index // object type
Parameters chart_id [in] Chart identifier. 0 means the current chart. nwin=-1 [in] Number of the chart subwindow. 0 means the main chart window, -1 means all the subwindows of the chart, including the main window. type=-1 [in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1 means all types. Return Value Returns the number of deleted objects. To read more about the error call GetLastError().
708
Object Functions
ObjectFind
The function searches for an object with the specified name in the chart with the specified ID.
int ObjectFind( long chart_id, // chart identifier // object name string name );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] The name of the searched object. Return Value If successful the function returns the number of the subwindow (0 means the main window of the chart), in which the object is found. If the object is not found, the function returns a negative number. To read more about the error call GetLastError(). Note When an object is renamed, two events are formed simultaneously. These events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: an event of deletion of an object with the old name; an event of creation of an object with a new name.
709
Object Functions
ObjectGetTimeByValue
The function returns the time value for the specified price value of the specified object.
datetime ObjectGetTimeByValue( long chart_id, // chart identifier // object name // Price // Line number string name, double value, int ); line_id
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. value [in] Price value. line_id [in] Line identifier. Return Value The time value for the specified price value of the specified object. Note An object can have several values in one price coordinate, therefore it is necessary to specify the line number. This function applies only to the following objects: Trendline (OBJ_TREND) Trendline by angle (OBJ_TRENDBYANGLE) Gann line (OBJ_GANNLINE) Equidistant channel (OBJ_CHANNEL) - 2 lines Liner regression channel (OBJ_REGRESSION) - 3 lines Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines Arrowed line (OBJ_ARROWED_LINE) See also Object Types
710
Object Functions
ObjectGetValueByTime
The function returns the price value for the specified time value of the specified object.
double ObjectGetValueByTime( long string chart_id, name, // chart identifier // object name // Time // Line number
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. time [in] Time value. line_id [in] Line ID. Return Value The price value for the specified time value of the specified object. Note An object can have several values in one price coordinate, therefore it is necessary to specify the line number. This function applies only to the following objects: Trendline (OBJ_TREND) Trendline by angle (OBJ_TRENDBYANGLE) Gann line (OBJ_GANNLINE) Equidistant channel (OBJ_CHANNEL) - 2 lines Liner regression channel (OBJ_REGRESSION) - 3 lines Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines Arrowed line (OBJ_ARROWED_LINE) See also Object Types
711
Object Functions
ObjectMove
The function changes coordinates of the specified anchor point of the object.
bool ObjectMove( long string int chart_id, name, point_index, // chart identifier // object name // anchor point number // Time // Price
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. point_index [in] Index of the anchor point. The number of anchor points depends on the type of object. time [in] Time coordinate of the selected anchor point. price [in] Price coordinate of the selected anchor point. Return Value If successful, returns true, in case of failure returns false. To read more about the error call GetLastError().
712
Object Functions
ObjectsTotal
The function returns the number of objects in the specified chart, specified subwindow, of the specified type.
int ObjectsTotal( long chart_id, int int ); nwin=-1, type=-1 // chart identifier // window index // object type
Parameters chart_id [in] Chart identifier. 0 means the current chart. nwin=-1 [in] Number of the chart subwindow. 0 means the main chart window, -1 means all the subwindows of the chart, including the main window. type=-1 [in] Type of the object. The value can be one of the values of the ENUM_OBJECT enumeration. -1 means all types. Return Value The number of objects.
713
Object Functions
ObjectSetDouble
The function sets the value of the corresponding object property. The object property must be of the double type. There are 2 variants of the function. Setting property value, without modifier
bool ObjectSetDouble( long chart_id, // chart identifier // object name // property // value string name, int prop_id,
double prop_value );
double prop_value );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_DOUBLE enumeration. prop_modifier [in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. prop_value [in] The value of the property. Return Value The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. To read more about the error call GetLastError(). Example of creating a Fibonacci object and adding a new level in it
//| Script program start function |
can
be
one
of
the
values
of
the
//+------------------------------------------------------------------+
714
Object Functions
void OnStart() { //--- auxiliary arrays double high[],low[],price1,price2; datetime time[],time1,time2; //--- Copy the open prices - 100 latest bars are enough int copied=CopyHigh(Symbol(),0,0,100,high); if(copied<=0) { Print("Failed to copy the values of the High price series"); return; } //--- Copy the close price - 100 latest bars are enough copied=CopyLow(Symbol(),0,0,100,low); if(copied<=0) { Print("Failed to copy the values of the Low price series"); return; } //--- Copy the open time for the last 100 bars copied=CopyTime(Symbol(),0,0,100,time); if(copied<=0) { Print("Failed to copy the values of the price series of Time"); return; } //--- Organize access to the copied data as to timeseries - backwards ArraySetAsSeries(high,true); ArraySetAsSeries(low,true); ArraySetAsSeries(time,true); //--- Coordinates of the first anchor point of the Fibo object price1=high[70]; time1=time[70]; //--- Coordinates of the second anchor point of the Fibo object price2=low[50]; time2=time[50]; //--- Time to create the Fibo object bool created=ObjectCreate(0,"Fibo",OBJ_FIBO,0,time1,price1,time2,price2); if(created) // If the object is created successfully { //--- set the color of Fibo levels ObjectSetInteger(0,"Fibo",OBJPROP_LEVELCOLOR,Blue); //--- by the way, how much Fibo levels do we have? int levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS); Print("Fibo levels before = ",levels); //---output to the Journal => number of level:value level_desription
715
Object Functions
for(int i=0;i<levels;i++) { Print(i,": ",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i), " } //--- Try to increase the number of levels per unit bool modified=ObjectSetInteger(0,"Fibo",OBJPROP_LEVELS,levels+1); if(!modified) // failed to change the number of levels { Print("Failed to change the number of levels of Fibo, error ",GetLastError()); } //--- just inform Print("Fibo levels after = ",ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS)); //--- set a value for a newly created level bool added=ObjectSetDouble(0,"Fibo",OBJPROP_LEVELVALUE,levels,133); if(added) // managed to set a value for the level { Print("Successfully set one more Fibo level"); //--- Also do not forget to set the level description ObjectSetString(0,"Fibo",OBJPROP_LEVELTEXT,levels,"my level"); ChartRedraw(0); //--- Get the actual value of the number of levels in the Fibo object levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS); Print("Fibo levels after adding = ",levels); //--- once again output all levels - just to make sure for(int i=0;i<levels;i++) { Print(i,":",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i), " } } else // Fails if you try to increase the number of levels in the Fibo object { Print("Failed to set one more Fibo level. Error ",GetLastError()); } } } ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i)); ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i));
716
Object Functions
ObjectSetInteger
The function sets the value of the corresponding object property. The object property must be of the datetime,int,color,boolorchar type. There are 2 variants of the function. Setting property value, without modifier
bool ObjectSetInteger( long chart_id, // chart identifier // object name // property // value string name, int long ); prop_id, prop_value
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_INTEGER enumeration. prop_modifier [in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. prop_value [in] The value of the property. Return Value The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. To read more about the error call GetLastError(). See also Object Types, Object Properties can be one of the values of the
717
Object Functions
ObjectSetString
The function sets the value of the corresponding object property. The object property must be of the string type. There are 2 variants of the function. Setting property value, without modifier
bool ObjectSetString( long chart_id, // chart identifier // object name // property // value string name, int prop_id,
string prop_value );
string prop_value );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_STRING enumeration. prop_modifier [in] Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. prop_value [in] The value of the property. Return Value The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. To read more about the error call GetLastError(). Note When an object is renamed, two events are formed simultaneously. TThese events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: can be one of the values of the
718
Object Functions an event of deletion of an object with the old name; an event of creation of an object with a new name.
719
Object Functions
ObjectGetDouble
The function returns the value of the corresponding object property. The object property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double ObjectGetDouble( long chart_id, // chart identifier // object name // property identifier // property modifier, if required string name, int int ); prop_id, prop_modifier=0
2. Returns true or false, depending on the success of the function. If successful, the property value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetDouble( long chart_id, // chart identifier // object name // property identifier // property modifier // here we accept the property value string name, int int prop_id, prop_modifier,
double&double_var );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_DOUBLE enumeration. prop_modifier [in] Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. double_var [out] Variable of the double type that received the value of the requested property. Return Value Value of the double type for the first calling variant. For the second variant the function returns true, if this property is maintained and the value has been placed into the double_var variable, otherwise returns false. To read more about the error call GetLastError(). can be one of the values of the
720
Object Functions
ObjectGetInteger
The function returns the value of the corresponding object property. The object property must be of the datetime,int,color,boolorchar type. There are 2 variants of the function. 1. Immediately returns the property value.
long ObjectGetInteger( long chart_id, // chart identifier // object name // property identifier // property modifier, if required string name, int int ); prop_id, prop_modifier=0
2. Returns true or false, depending on the success of the function. If successful, the property value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetInteger( long chart_id, // chart identifier // object name // property identifier // property modifier // here we accept the property value string name, int int long& ); prop_id, prop_modifier, long_var
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_INTEGER enumeration. prop_modifier [in] Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. long_var [out] Variable of the long type that receives the value of the requested property. Return Value The long value for the first calling variant. For the second variant the function returns true, if this property is maintained and the value has been placed into the long_var variable, otherwise returns false. To read more about the error call GetLastError(). can be one of the values of the
721
Object Functions
ObjectGetString
The function returns the value of the corresponding object property. The object property must be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string ObjectGetString( long chart_id, // chart identifier // object name // property identifier // property modifier, if required string name, int int ); prop_id, prop_modifier=0
2. Returns true or false, depending on the success of the function. If successful, the property value is placed to a receiving variable passed by by reference by the last parameter.
bool ObjectGetString( long chart_id, // chart identifier // object name // property identifier // property modifier // here we accept the property value string name, int int prop_id, prop_modifier,
string&string_var );
Parameters chart_id [in] Chart identifier. 0 means the current chart. name [in] Name of the object. prop_id [in] ID of the object property. The value ENUM_OBJECT_PROPERTY_STRING enumeration. prop_modifier [in] Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. string_var [out] Variable of the string type that receives the value of the requested properties. Return Value String value for the first version of the call. For the second version of the call returns true, if this property is maintained and the value has been placed into the string_var variable, otherwise returns false. To read more about the error call GetLastError(). can be one of the values of the
722
Object Functions
Note When an object is renamed, two events are formed simultaneously. These events can be handled in an Expert Advisor or indicator by the OnChartEvent() function: an event of deletion of an object with the old name; an event of creation of an object with a new name.
723
Technical Indicators
724
Technical Indicators
iAO iATR iBearsPower iBands iBullsPower iCCI iChaikin iCustom iDEMA iDeMarker iEnvelopes iForce iFractals iFRAMA iGator iIchimoku iBWMFI iMomentum iMFI iMA iOsMA iMACD iOBV iSAR iRSI iRVI iStdDev iStochastic iTEMA iTriX iWPR iVIDyA
Awesome Oscillator Average True Range Bears Power Bollinger Bands Bulls Power Commodity Channel Index Chaikin Oscillator Custom indicator Double Exponential Moving Average DeMarker Envelopes Force Index Fractals Fractal Adaptive Moving Average Gator Oscillator Ichimoku Kinko Hyo Market Facilitation Index by Bill Williams Momentum Money Flow Index Moving Average Moving Average of Oscillator (MACD histogram) Moving Averages Convergence-Divergence On Balance Volume Parabolic Stop And Reverse System Relative Strength Index Relative Vigor Index Standard Deviation Stochastic Oscillator Triple Exponential Moving Average Triple Exponential Moving Averages Oscillator Williams' Percent Range Variable Index DYnamic Average
725
Technical Indicators
iVolumes
Volumes
726
Technical Indicators
iAC
The function creates Accelerator Oscillator in a global cache of the client terminal and returns its handle. It has only one buffer.
int iAC( string symbol, // symbol name // period ENUM_TIMEFRAMES period );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means the current timeframe. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
727
Technical Indicators
iAD
The function returns the handle of the Accumulation/Distribution indicator. It has only one buffer.
int iAD( string ENUM_TIMEFRAMES symbol, period, // symbol name // period // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means the current timeframe. applied_volume [in] The volume used. Can be any of ENUM_APPLIED_VOLUME values. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
728
Technical Indicators
iADX
The function returns the handle of the Average Directional Movement Index indicator.
int iADX( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); adx_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. adx_period [in] Period to calculate the index. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.
729
Technical Indicators
iADXWilder
The function returns the handle of Average Directional Movement Index by Welles Wilder.
int iADXWilder( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); adx_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. adx_period [in] Period to calculate the index. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.
730
Technical Indicators
iAlligator
The function returns the handle of the Alligator indicator.
int iAlligator( string ENUM_TIMEFRAMES int int int int int int ENUM_MA_METHOD symbol, period, jaw_period, jaw_shift, teeth_period, teeth_shift, lips_period, lips_shift, ma_method, // symbol name // period // period for the calculation of jaws // horizontal shift of jaws // period for the calculation of teeth // horizontal shift of teeth // period for the calculation of lips // horizontal shift of lips // type of smoothing // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. jaw_period [in] Averaging period for the blue line (Alligator's Jaw) jaw_shift [in] The shift of the blue line relative to the price chart. It should be remembered that the line shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining buffer values using the CopyBuffer() function,the shift value will have no effect. teeth_period [in] Averaging period for the red line (Alligator's Teeth). teeth_shift [in] The shift of the red line relative to the price chart. It should be remembered that the line shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining buffer values using the CopyBuffer() function,the shift value will have no effect. lips_period [in] Averaging period for the green line (Alligator's lips). lips_shift [in] The shift of the green line relative to the price chart. It should be remembered that the line shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining buffer values using the CopyBuffer() function,the shift value will have no effect. ma_method
731
Technical Indicators [in] The method of averaging. Can be any of the ENUM_MA_METHOD values. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - GATORJAW_LINE, 1 - GATORTEETH_LINE, 2 GATORLIPS_LINE.
732
Technical Indicators
iAMA
The function returns the handle of the Adaptive Moving Average indicator. It has only one buffer.
int iAMA( string ENUM_TIMEFRAMES int int int int symbol, period, ama_period, fast_ma_period, slow_ma_period, ama_shift, // symbol name // period // average period for AMA // fast MA period // slow MA period // horizontal shift of the indicator // type of the price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ama_period [in] The calculation period, on which the efficiency coefficient is calculated. fast_ma_period [in] Fast period for the smoothing coefficient calculation for a rapid market. slow_ma_period [in] Slow period for the smoothing coefficient calculation in the absence of trend. ama_shift [in] Shift of the indicator relative to the price chart. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
733
Technical Indicators
iAO
The function returns the handle of the Awesome oscillator indicator. It has only one buffer.
int iAO( string symbol, // symbol name // period ENUM_TIMEFRAMES period );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
734
Technical Indicators
iATR
The function returns the handle of the Average True Range indicator. It has only one buffer.
int iATR( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); ma_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] The value of the averaging period for the indicator calculation. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
735
Technical Indicators
iBearsPower
The function returns the handle of the Bears Power indicator. It has only one buffer.
int iBearsPower( string ENUM_TIMEFRAMES int ); symbol, period, ma_period, // symbol name // period // averaging period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] The value of the averaging period for the indicator calculation. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
736
Technical Indicators
iBands
The function returns the handle of the Bollinger Bands indicator.
int iBands( string ENUM_TIMEFRAMES int int double symbol, period, bands_period, bands_shift, deviation, // symbol name // period // period for average line calculation // horizontal shift of the indicator // number of standard deviations // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. bands_period [in] The averaging period of the main line of the indicator. bands_shift [in] The shift the indicator relative to the price chart. It should be remembered that the line shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining buffer values using the CopyBuffer() function,the shift value will have no effect. deviation [in] Deviation from the main line. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - BASE_LINE, 1 - UPPER_BAND, 2 - LOWER_BAND
737
Technical Indicators
iBullsPower
The function returns the handle of the Bulls Power indicator. It has only one buffer.
int iBullsPower( string ENUM_TIMEFRAMES int ); symbol, period, ma_period, // symbol name // period // averaging period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] The averaging period for the indicator calculation. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
738
Technical Indicators
iCCI
The function returns the handle of the Commodity Channel Index indicator. It has only one buffer.
int iCCI( string ENUM_TIMEFRAMES int symbol, period, ma_period, // symbol name // period // averaging period // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] The averaging period for the indicator calculation. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
739
Technical Indicators
iChaikin
The function returns the handle of the Chaikin Oscillator indicator. It has only one buffer.
int iChaikin( string ENUM_TIMEFRAMES int int ENUM_MA_METHOD symbol, period, fast_ma_period, slow_ma_period, ma_method, // symbol name // period // fast period // slow period // smoothing type // type of volume
ENUM_APPLIED_VOLUME applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. fast_ma_period [in] Fast averaging period for calculations. slow_ma_period [in] Slow averaging period for calculations. ma_method [in] Smoothing type. Can be one of the averaging constants of ENUM_MA_METHOD. applied_volume [in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
740
Technical Indicators
iCustom
The function returns the handle of a specified custom indicator.
int iCustom( string symbol, // symbol name // period // folder/custom indicator_name // list of indicator input parameters ENUM_TIMEFRAMES period, string ... ); name
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. name [in] The name of the custom indicator, with path relative to the root directory of indicators (MQL5/Indicators/). If an indicator is located in a subdirectory, for example, in MQL5/Indicators/ Examples, its name must be specified like: "Examples\\indicator_name" (it is necessary to use a double slash instead of the single slash as a separator). ... [in] input-parameters of a custom indicator, separated by commas. Type and order of parameters must match. If there is no parameters specified, then default values will be used. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note A custom indicator must be compiled (with extension EX5) and located in the directory MQL5/ Indicators of the client terminal or its subdirectory. Indicators that require testing are defined automatically from the call of the iCustom() function, if the corresponding parameter is set through a constant string. For all other cases (use of the IndicatorCreate() function or use of a non-constant string in the parameter that sets the indicator name) the property #property tester_indicator is required:
#property tester_indicator "indicator_name.ex5"
If the first call form is used in the indicator, then at the custom indicator start you can additionally indicate data for calculation in its "Parameters" tab. If the "Apply to" parameter is not selected explicitly, the default calculation is based on the values of "Close" prices.
741
Technical Indicators
When you call a custom indicator from mql5-program, the Applied_Price parameter or a handle of another indicator should be passed last, after all input variables of the custom indicator. See also Program Properties, Timeseries and Indicators Access,IndicatorCreate(), IndicatorRelease() Example:
#property indicator_separate_window #property indicator_buffers 1 #property indicator_plots //---- plot Label1 #property indicator_label1 #property indicator_type1 #property indicator_color1 #property indicator_style1 #property indicator_width1 //--- input parameters input int MA_Period=21; input int MA_Shift=0; input ENUM_MA_METHOD MA_Method=MODE_SMA; //--- indicator buffers double int MA_handle; //+------------------------------------------------------------------+ //| Custom indicator initialization function int OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA); ResetLastError(); MA_handle=iCustom(NULL,0,"Custom Moving Average", | //+------------------------------------------------------------------+ Label1Buffer[]; //--- Handle of the Custom Moving Average.mq5 custom indicator "Label1" DRAW_LINE Red STYLE_SOLID 1 1
742
Technical Indicators
MA_Period, MA_Shift, MA_Method, PRICE_CLOSE // using the close prices ); Print("MA_handle = ",MA_handle," //--return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //--- Copy the values of the indicator Custom Moving Average to our indicator buffer int copy=CopyBuffer(MA_handle,0,0,rates_total,Label1Buffer); Print("copy = ",copy," if(copy<=0) Print("An attempt to get the values if Custom Moving Average has failed"); //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+ rates_total = ",rates_total); //--- If our attempt has failed - Report this | //+------------------------------------------------------------------+ error = ",GetLastError());
743
Technical Indicators
iDEMA
The function returns the handle of the Double Exponential Moving Average indicator. It has only one buffer.
int iDEMA( string ENUM_TIMEFRAMES int int symbol, period, ma_period, ma_shift, // symbol name // period // averaging period // horizontal shift // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period (bars count) for calculations. ma_shift [in] Shift of the indicator relative to the price chart. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
744
Technical Indicators
iDeMarker
The function returns the handle of the DeMarker indicator. It has only one buffer.
int iDeMarker( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); ma_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period (bars count) for calculations. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
745
Technical Indicators
iEnvelopes
The function returns the handle of the Envelopes indicator.
int iEnvelopes( string ENUM_TIMEFRAMES int int ENUM_MA_METHOD symbol, period, ma_period, ma_shift, ma_method, // symbol name // period // period for the average line calculation // horizontal shift of the indicator // type of smoothing // type of price or handle
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the main line. ma_shift [in] The shift of the indicator relative to the price chart. It should be remembered that the line shift is only visual, and values in the indicator buffer are stored without the shift. When obtaining buffer values using the CopyBuffer() function,the shift value will have no effect. ma_method [in] Smoothing type. Can be one of the values of ENUM_MA_METHOD. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. deviation [in] The deviation from the main line (in percents). Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers: 0 - UPPER_LINE, 1 - LOWER_LINE.
746
Technical Indicators
iForce
The function returns the handle of the Force Index indicator. It has only one buffer.
int iForce( string ENUM_TIMEFRAMES int ENUM_MA_METHOD symbol, period, ma_period, ma_method, // symbol name // period // averaging period // smoothing type // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the indicator calculations. ma_method [in] Smoothing type. Can be one of the values of ENUM_MA_METHOD. applied_volume [in] The volume used. Can be one of the values of ENUM_APPLIED_VOLUME. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
747
Technical Indicators
iFractals
The function returns the handle of the Fractals indicator.
int iFractals( string symbol, // symbol name // period ENUM_TIMEFRAMES period );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - UPPER_LINE, 1 - LOWER_LINE.
748
Technical Indicators
iFrAMA
The function returns the handle of the Fractal Adaptive Moving Average indicator. It has only one buffer.
int iFrAMA( string ENUM_TIMEFRAMES int int symbol, period, ma_period, ma_shift, // symbol name // period // averaging period // horizontal shift on the chart // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Period (bars count) for the indicator calculations. ma_shift [in] Shift of the indicator in the price chart. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
749
Technical Indicators
iGator
The function returns the handle of the Gator indicator. The Oscillator shows the difference between the blue and red lines of Alligator (upper histogram) and difference between red and green lines (lower histogram).
int iGator( string ENUM_TIMEFRAMES int int int int int int ENUM_MA_METHOD symbol, period, jaw_period, jaw_shift, teeth_period, teeth_shift, lips_period, lips_shift, ma_method, // symbol name // period // period for the calculation of the jaws // jaws horizontal shift // period for the calculation of the teeth // teeth horizontal shift // period for the calculation of the lips // lips horizontal shift // type of smoothing // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. jaw_period [in] Averaging period for the blue line (Alligator's Jaw). jaw_shift [in] The shift of the blue line relative to the price chart. It isn't directly connected with the visual shift of the indicator histogram. teeth_period [in] Averaging period for the red line (Alligator's Teeth). teeth_shift [in] The shift of the red line relative to the price chart. It isn't directly connected with the visual shift of the indicator histogram. lips_period [in] Averaging period for the green line (Alligator's lips). lips_shift [in] The shift of the green line relative to the price charts. It isn't directly connected with the visual shift of the indicator histogram. ma_method [in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.
750
Technical Indicators applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note Buffer numbers: 0 - UPPER_HISTOGRAM, 1 - color buffer of the upper histogram, 2 LOWER_HISTOGRAM, 3 - color buffer of the lower histogram.
751
Technical Indicators
iIchimoku
The function returns the handle of the Ichimoku Kinko Hyo indicator.
int iIchimoku( string symbol, // symbol name // period // period of Tenkan-sen // period of Kijun-sen // period of Senkou Span B ENUM_TIMEFRAMES period, int int int ); tenkan_sen, kijun_sen, senkou_span_b
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. tenkan_sen [in] Averaging period for Tenkan Sen. kijun_sen [in] Averaging period for Kijun Sen. senkou_span_b [in] Averaging period for Senkou Span B. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers: 0 - TENKANSEN_LINE, 1 - KIJUNSEN_LINE, 2 - SENKOUSPANA_LINE, 3 SENKOUSPANB_LINE, 4 - CHINKOUSPAN_LINE.
752
Technical Indicators
iBWMFI
The function returns the handle of the Market Facilitation Index indicator. It has only one buffer.
int iBWMFI( string ENUM_TIMEFRAMES symbol, period, // symbol name // period // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. applied_volume [in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
753
Technical Indicators
iMomentum
The function returns the handle of the Momentum indicator. It has only one buffer.
int iMomentum( string ENUM_TIMEFRAMES int symbol, period, mom_period, // symbol name // period // averaging period // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. mom_period [in] Averaging period (bars count) for the calculation of the price change. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
754
Technical Indicators
iMFI
The function returns the handle of the Money Flow Index indicator.
int iMFI( string ENUM_TIMEFRAMES int symbol, period, ma_period, // symbol name // period // averaging period // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period (bars count) for the calculation. applied_volume [in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
755
Technical Indicators
iMA
The function returns the handle of the Moving Average indicator. It has only one buffer.
int iMA( string ENUM_TIMEFRAMES int int ENUM_MA_METHOD symbol, period, ma_period, ma_shift, ma_method, // symbol name // period // averaging period // horizontal shift // smoothing type // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the calculation of the moving average. ma_shift [in] Shift of the indicator relative to the price chart. ma_method [in] Smoothing type. Can be one of the ENUM_MA_METHOD values. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
756
Technical Indicators
iOsMA
The function returns the handle of the Moving Average of Oscillator indicator. The OsMA oscillator shows the difference between values of MACD and its signal line. It has only one buffer.
int iOsMA( string ENUM_TIMEFRAMES int int int symbol, period, fast_ema_period, slow_ema_period, signal_period, // symbol name // period // period for Fast Moving Average // period for Slow Moving Average // averaging period for their difference // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. fast_ema_period [in] Period for Fast Moving Average calculation. slow_ema_period [in] Period for Slow Moving Average calculation. signal_period [in] Averaging period for signal line calculation. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note In some systems this oscillator is also known as MACD histogram.
757
Technical Indicators
iMACD
The function returns the handle of the Moving Averages Convergence/Divergence indicator. In systems where s is called MACD Histogram, this indicator is shown as two lines. In the client terminal the Moving Averages Convergence/Divergence looks like a histogram.
int iMACD( string ENUM_TIMEFRAMES int int int symbol, period, fast_ema_period, slow_ema_period, signal_period, // symbol name // period // period for Fast average calculation // period for Slow average calculation // period for their difference averaging // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. fast_ema_period [in] Period for Fast Moving Average calculation. slow_ema_period [in] Period for Slow Moving Average calculation. signal_period [in] Period for Signal line calculation. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
758
Technical Indicators
iOBV
The function returns the handle of the On Balance Volume indicator. It has only one buffer.
int iOBV( string ENUM_TIMEFRAMES symbol, period, // symbol name // period // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. applied_volume [in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
759
Technical Indicators
iSAR
The function returns the handle of the Parabolic Stop and Reverse system indicator. It has only one buffer.
int iSAR( string symbol, // symbol name // period // step increment // maximal stop level ENUM_TIMEFRAMES period, double double ); step, maximum
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. step [in] The stop level increment, usually 0.02. maximum [in] The maximal stop level, usually 0.2. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
760
Technical Indicators
iRSI
The function returns the handle of the Relative Strength Index indicator. It has only one buffer.
int iRSI( string ENUM_TIMEFRAMES int symbol, period, ma_period, // symbol name // period // averaging period // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the RSI calculation. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
761
Technical Indicators
iRVI
The function returns the handle of the Relative Vigor Index indicator.
int iRVI( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); ma_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the RVI calculation. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
762
Technical Indicators
iStdDev
The function returns the handle of the Standard Deviation indicator. It has only one buffer.
int iStdDev( string ENUM_TIMEFRAMES int int ENUM_MA_METHOD symbol, period, ma_period, ma_shift, ma_method, // symbol name // period // averaging period // horizontal shift // smoothing type // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period for the indicator calculations. ma_shift [in] Shift of the indicator relative to the price chart. ma_method [in] Type of averaging. Can be any of the ENUM_MA_METHOD values. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
763
Technical Indicators
iStochastic
The function returns the handle of the Stochastic Oscillator indicator.
int iStochastic( string symbol, // symbol name // period // K-period (number of bars for calculations) // D-period (period of first smoothing) // final smoothing // type of smoothing // stochastic calculation method ENUM_TIMEFRAMES period, int int int ENUM_MA_METHOD ENUM_STO_PRICE ); Kperiod, Dperiod, slowing, ma_method, price_field
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. Kperiod [in] Averaging period (bars count) for the %K line calculation. Dperiod [in] Averaging period (bars count) for the %D line calculation. slowing [in] Slowing value. ma_method [in] Type of averaging. Can be any of the ENUM_MA_METHOD values. price_field [in] Parameter of price selection for calculations. Can be one of the ENUM_STO_PRICE values. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed. Note The buffer numbers: 0 - MAIN_LINE, 1 - SIGNAL_LINE.
764
Technical Indicators
iTEMA
The function returns the handle of the Triple Exponential Moving Average indicator. It has only one buffer.
int iTEMA( string ENUM_TIMEFRAMES int int symbol, period, ma_period, ma_shift, // symbol name // period // averaging period // horizontal shift of indicator // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period (bars count) for calculation. ma_shift [in] Shift of indicator relative to the price chart. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
765
Technical Indicators
iTriX
The function returns the handle of the Triple Exponential Moving Averages Oscillator indicator. It has only one buffer.
int iTriX( string ENUM_TIMEFRAMES int symbol, period, ma_period, // symbol name // period // averaging period // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. ma_period [in] Averaging period (bars count) for calculations. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
766
Technical Indicators
iWPR
The function returns the handle of the Larry Williams' Percent Range indicator. It has only one buffer.
int iWPR( string symbol, // symbol name // period // averaging period ENUM_TIMEFRAMES period, int ); calc_period
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. calc_period [in] Period (bars count) for the indicator calculation. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
767
Technical Indicators
iVIDyA
The function returns the handle of the Variable Index Dynamic Average indicator. It has only one buffer.
int iVIDyA( string ENUM_TIMEFRAMES int int int symbol, period, cmo_period, ema_period, ma_shift, // symbol name // period // period for Chande Momentum // EMA smoothing period // horizontal shift on the price chart // type of price or handle
ENUM_APPLIED_PRICE applied_price );
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. cmo_period [in] Period (bars count) for the Chande Momentum Oscillator calculation. ema_period [in] EMA period (bars count) for smoothing factor calculation. ma_shift [in] Shift of the indicator relative to the price chart. applied_price [in] The price used. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
768
Technical Indicators
iVolumes
The function returns the handle of the Volumes indicator. It has an only one buffer.
int iVolumes( string ENUM_TIMEFRAMES symbol, period, // symbol name // period // volume type for calculation
ENUM_APPLIED_VOLUME applied_volume )
Parameters symbol [in] The symbol name of the security, the data of which should be used to calculate the indicator. The NULL value means the current symbol. period [in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe. applied_volume [in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values. Returned value Returns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE. The computer memory can be freed from an indicator that is no more utilized, using the IndicatorRelease() function, to which the indicator handle is passed.
769
Event Functions
This group contains functions for working with custom events and timer events. Besides this group, there are special functions for handling predefined events. Function EventSetTimer Action Starts the timer event generator with the specified periodicity for the current chart Stops the generation of events by the timer in the current chart Generates a custom event for the specified chart
EventKillTimer
EventChartCustom
770
EventSetTimer
The function indicates to the client terminal, that events from the timer must be generated with the specified periodicity for the chart, to which the Expert Advisor is attached.
bool EventSetTimer( int seconds ); // number of seconds
Parameters seconds [in] Number of seconds that determine the frequency of the timer event occurrence. Return Value In case of success returns true, otherwise false. In order to get an error code, the GetLastError() function should be called. Note Normally, this function must be called from the OnInit() function or from a class constructor. In order to handle events coming from the timer, the Expert Advisor must have the OnTimer() function. Every Expert Advisor, as well as every indicator works with its own timer and receives events only from it. As soon as a mql5 program stops operating, the timer is destroyed forcibly if it was created but hasn't been disabled by the EventKillTimer() function. For each program no more than one timer can be run.
771
EventKillTimer
Specifies the client terminal that is necessary to stop the generation of events from Timer.
void EventKillTimer();
Return Value No return value. Note Typically, this function must be called from a function OnDeinit(), if the EventSetTimer() function has been called from OnInit(). This function can also be called form the class destructor, if the EventSetTimer() function has been called in the constructor of this class. Every Expert Advisor, as well as every indicator works with its own timer and receives events only from it. As soon as a mql5 program stops operating, the timer is destroyed forcibly if it was created but hasn't been disabled by the EventKillTimer() function
772
EventChartCustom
The function generates a custom event for the specified chart.
void EventChartCustom( long chart_id, // identifier of the event receiving chart // event identifier // parameter of type long // parameter of type double // string parameter of the event ushort custom_event_id, long lparam,
Parameters chart_id [in] Chart identifier. 0 means the current chart. custom_event_id [in] ID of the user events. This identifier is automatically CHARTEVENT_CUSTOM and converted to the integer type. lparam [in] Event parameter of the long type passed to the OnChartEvent function. dparam [in] Event parameter of the double type passed to the OnChartEvent function. sparam [in] Event parameter of the string type passed to the OnChartEvent function. If the string is longer than 63 characters, it is truncated. Return Value No return value. Note An Expert Advisor or indicator attached to the specified chart handles the event using the function OnChartEvent(int event_id, long& lparam, double& dparam, string& sparam). For each type of event, the input parameters of the OnChartEvent() function have definite values that are required for the processing of this event. The events and values passed through this parameters are listed in the below table. Event Value of the id parameter Value of lparam parameter code of pressed key the Value of dparam parameter the Value of sparam parameter the added to the value
Event of keystroke
773
creation Event of change of an object property via the properties dialog Event of graphical object deletion Event of a mouse click on the chart Event of a mouse click in a graphical object belonging to the chart Event of a graphical object dragging using the mouse Event of the finished text editing in the entry box of the LabelEdit graphical object ID of the user event under the N number Example: CHARTEVENT_OB JECT_CHANGE
CHARTEVENT_OB JECT_DELETE
CHARTEVENT_C LICK
the X coordinate
the Y coordinate
CHARTEVENT_OB JECT_CLICK
the X coordinate
the Y coordinate
CHARTEVENT_OB JECT_DRAG
CHARTEVENT_OB JECT_ENDEDIT
Name of the LabelEdit graphical object, in which text editing has completed Value set by the EventChartCusto m() function
CHARTEVENT_CU STOM+N
//+------------------------------------------------------------------+ //| //| //| ButtonClickExpert.mq5 | Copyright 2009, MetaQuotes Software Corp. | http://www.mql5.com |
//+------------------------------------------------------------------+ #property copyright "2009, MetaQuotes Software Corp." #property link #property version "http://www.mql5.com" "1.00"
string buttonID="Button"; string labelID="Info"; int broadcastEventID=5000; //+------------------------------------------------------------------+ //| Expert initialization function |
774
775
776
777
Standard Library
Standard Library
This group of chapters contains the technical details of the MQL5 Standard Library and descriptions of all its key components. MQL5 Standard Library is written in MQL5 and is designed to facilitate writing programs (indicators, scripts, experts) to end users. Library provides convenient access to most of the internal functions MQL5. MQL5 Standard Library is placed in the working directory of the terminal in the 'Include' folder. Section Base class Classes of data Classes for file operations Classes for string operations Classes for graphic objects Class for working with chart Technical indicators Trade Classes Trading Strategy Classes Location Include\ Include\Arrays\ Include\Files\ Include\Strings\ Include\Objects\ Include\Charts\ Include\Indicators\ Include\Trade\ Include\Expert\
778
Standard Library
Description
Class CObject provides all its descendants to be part of a linked list. Also identifies a number of virtual methods for further implementation in descendant classes.
Declaration
class CObject
Title
#include <Object.mqh>
Class Methods
Attributes Prev Prev Next Next Compare methods virtual Compare Returns the result of comparison with another object Gets the value of the previous item Sets the value of the previous item Gets the value of the subsequent element Sets the next element
Input/output virtual Save virtual Load virtual Type Derived classes: CArray CChartObject CChart CString CFile CList CTreeNode Writes object to a file Reads the object from the file Returns the type of object
779
Standard Library
Prev
Gets a pointer to the previous list item.
CObject* Prev()
Return Value Pointer to the previous list item. If an item is listed first, then return NULL. Example:
//--- example for CObject::Prev() #include <Object.mqh> //--void OnStart() { CObject *object_first,*object_second; //--object_first=new CObject; if(object_first==NULL) { printf("Object create error"); return; } object_second=new CObject; if(object_second==NULL) { printf("Object create error"); delete object_first; return; } //--- set interconnect object_first.Next(object_second); object_second.Prev(object_first); //--- use prev object CObject *object=object_second.Prev(); //--- delete objects delete object_first; delete object_second; }
780
Standard Library
Prev
Sets the pointer to the previous list item.
void Prev( CObject* object ) // Pointer to the previous list item
Parameters object [in] New value pointer to the previous list item. Example:
//--- example for CObject::Prev(CObject*) #include <Object.mqh> //--void OnStart() { CObject *object_first,*object_second; //--object_first=new CObject; if(object_first==NULL) { printf("Object create error"); return; } object_second=new CObject; if(object_second==NULL) { printf("Object create error"); delete object_first; return; } //--- set interconnect object_first.Next(object_second); object_second.Prev(object_first); //--- use objects //--- ... //--- delete objects delete object_first; delete object_second; }
781
Standard Library
Next
Gets a pointer to the next element of the list.
CObject* Next()
Return Value Pointer to the next item in the list. If the last item in the list, returns NULL. Example:
//--- example for CObject::Next() #include <Object.mqh> //--void OnStart() { CObject *object_first,*object_second; //--object_first=new CObject; if(object_first==NULL) { printf("Object create error"); return; } object_second=new CObject; if(object_second==NULL) { printf("Object create error"); delete object_first; return; } //--- set interconnect object_first.Next(object_second); object_second.Prev(object_first); //--- use next object CObject *object=object_first.Next(); //--- delete objects delete object_first; delete object_second; }
782
Standard Library
Next
Sets the pointer to the next element of the list.
void Next( CObject* object ) // Pointer to the next list item
Parameters object [in] New value pointer to the next list item. Example:
//--- example for CObject::Next(CObject*) #include <Object.mqh> //--void OnStart() { CObject *object_first,*object_second; //--object_first=new CObject; if(object_first==NULL) { printf("Object create error"); return; } object_second=new CObject; if(object_second==NULL) { printf("Object create error"); delete object_first; return; } //--- set interconnect object_first.Next(object_second); object_second.Prev(object_first); //--- use objects //--- ... //--- delete objects delete object_first; delete object_second; }
783
Standard Library
Compare
Compares the data item in the list with data on another element of the list.
virtual int Compare( CObject const * node, int ) const mode=0 // Node to compare with // Compare mode
Parameters node [in] Pointer to a list item to compare mode=0 [in] Variant Comparison Return Value 0 - in case the list items are equal, -1 - if the list item is less than the item in the list for comparison (node), 1 - if the list item more than item in the list for comparison (node). Note Method Compare () in class CObject always returns 0 and does not perform any action.If you want to compare data derived class, the method Compare (...) Should be implemented.The mode parameter should be used when implementing multivariate comparison. Example:
//--- example for CObject::Compare(...) #include <Object.mqh> //--void OnStart() { CObject *object_first,*object_second; //--object_first=new CObject; if(object_first==NULL) { printf("Object create error"); return; } object_second=new CObject; if(object_second==NULL) { printf("Object create error"); delete object_first; return; } //--- set interconnect object_first.Next(object_second);
784
Standard Library
object_second.Prev(object_first); //--- compare objects int result=object_first.Compare(object_second); //--- delete objects delete object_first; delete object_second; }
785
Standard Library
Save
Saves data element list in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (), binary Return Value true - if successfully completed, false - if an error. Note Method Save (int) in class CObject always returns true and does not perform any action. If you want to save the data derived class in the file, the method Save (int) should be implemented. Example:
//--- example for CObject::Save(int) #include <Object.mqh> //--void OnStart() { int //--if(object!=NULL) { printf("Object create error"); return; } //--- set objects data //--- . . . //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!object.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete object; FileClose(file_handle); //--return; } file_handle; CObject *object=new CObject;
786
Standard Library
FileClose(file_handle); } delete object; }
787
Standard Library
Load
Loads data item in the list from a file.
virtual bool Load( int file_handle ) // handle to file
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (), binary Return Value true if successfully completed, false - if an error. Note Method Load (int) in class CObject always returns true and does not perform any action. If you want to load the data derived class from a file, the method Load (int) should be implemented. Example:
//--- example for CObject::Load(int) #include <Object.mqh> //--void OnStart() { int //--if(object!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!object.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete object; FileClose(file_handle); //--return; } FileClose(file_handle); } file_handle; CObject *object=new CObject;
788
Standard Library
//--- use object //--- . . . delete object; }
789
Standard Library
Type
Gets the type identifier.
virtual int Type() const
790
Standard Library
Data Structures
This section contains the technical details of working with various data structures (arrays, linked lists, etc.) and description of the relevant components of the MQL5 Standard Library . Using classes of data structures, will save time when creating custom data stores of various formats (including composite data structures). MQL5 Standard Library (in terms of data sets) is placed in the working directory of the terminal in the Include\Arrays folder.
Data Arrays
Use of classes of dynamic arrays of data will save time when creating a custom data stores of various formats (including multidimensional arrays). MQL5 Standard Library (in terms of arrays of data) is placed in the working directory of the terminal in the Include\Arrays folder. Class Base class of dynamic data array CArray CArrayChar CArrayShort Description Base class of dynamic data array Dynamic array of variables of type char or uchar Dynamic array of variables of type short or ushort Dynamic array of variables of type int or uint Dynamic array of variables of type long or ulong Dynamic array of variables of type float Dynamic array of variables of type double Dynamic array of variables of type string Dynamic array of pointers CObject Provides the ability to work with a list of instances of CObject and its descendant Provides the ability to work with nodes of the binary tree CTree Provides the ability to work with the binary tree of the CTreeNode class instances and its descendants
CArrayInt CArrayLong CArrayFloat CArrayDouble CArrayString Base class of object array CArrayObj Base class of list CList
CTreeNode
CTree
791
Standard Library
CArray
CArray class is the base class a dynamic array of variables.
Description
Class CArray provides the ability to work with a dynamic array of variables in the part of the attributes of management of memory allocation, sorting, and working with files.
Declaration
class CArray : public CObject
Title
#include <Arrays\Array.mqh>
Class Methods
Attributes Step Step Total Available Gets the step increment size of the array Set the increment size of the array Gets the number of elements in the array Gets the number of free elements of the array are available without additional memory allocation Gets the maximum possible size of the array without memory reallocation Gets sign sorted array to the specified option Gets the version of the sorting array
Max
Sort methods Sort Input/output virtual Save virtual Load Derived classes: CArrayChar Saves data array in the file Loads data array from a file Sorts an array to the specified option
792
793
Standard Library
Step
Gets the step increment size of the array.
int Step() const
794
Standard Library
Step
Sets the increment size of the array.
bool Step( int step ) // step
Parameters step [in] The new value of step increments in the size of the array. Return Value true if successful, false - if there was an attempt to establish a step less than or equal to zero. Example:
//--- example for CArray::Step(int) #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- set resize step bool result=array.Step(1024); //--- use array //--- ... //--- delete array delete array; }
795
Standard Library
Total
Gets the number of elements in the array.
int Total() const;
796
Standard Library
Available
Gets the number of free elements of the array are available without additional memory allocation.
int Available() const
Return Value Number of free elements of the array are available without additional memory allocation. Example:
//--- example for CArray::Available() #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- check available int available=array.Available(); //--- use array //--- ... //--- delete array delete array; }
797
Standard Library
Max
Gets the maximum possible size of the array without memory reallocation.
int Max() const
Return Value The maximum possible size of the array without reallocation memory. Example:
//--- example for CArray::Max() #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- check maximum size int max=array.Max(); //--- use array //--- ... //--- delete array delete array; }
798
Standard Library
IsSorted
Gets sign sorted array to the specified option.
bool IsSorted( int mode=0 ) const // Sorting mode
Parameters mode=0 [in] Tested version of the sort. Return Value Flag of the sorted list. If the list is sorted by the specified version - true, otherwise - false. Note Symptom sorted array can not be changed directly. Symptom sorted set method Sort () and reset any methods to add / insert except InsertSort (...). Example:
//--- example for CArray::IsSorted() #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- check sorted if(array.IsSorted()) { //--- use methods for sorted array //--- ... } //--- delete array delete array; }
799
Standard Library
SortMode
Gets the version of the sorting array.
int SortMode() const;
800
Standard Library
Clear
Deletes all of the array elements without memory release.
void Clear()
Example:
//--- example for CArray::Clear() #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- use array //--- ... //--- clear array array.Clear(); //--- delete array delete array; }
801
Standard Library
Sort
Sorts an array to the specified option.
void Sort( int mode=0 ) // Sorting mode
Parameters mode=0 [in] Mode of array sorting. Return Value No. Note Sorting an array is always ascending.For arrays of primitive data types (CArrayChar, CArrayShort, etc.), the parameter mode is not used.For the array CArrayObj, multivariate sort should be implemented in the method Sort (int) derived class. Example:
//--- example for CArray::Sort(int) #include <Arrays\Array.mqh> //--void OnStart() { CArray *array=new CArray; //--if(array==NULL) { printf("Object create error"); return; } //--- sorting by mode 0 array.Sort(0); //--- use array //--- ... //--- delete array delete array; }
802
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArray::Save(int) #include <Arrays\Array.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- delete array delete array; } file_handle; CArray *array=new CArray;
803
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArray::Load(...) #include <Arrays\Array.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- delete array delete array; } file_handle; CArray *array=new CArray;
804
Standard Library
CArrayChar
CArrayChar class is a class of dynamic array of variables of type char or uchar.
Description
Class CArrayChar provides the ability to work with a dynamic array of variables of type char or uchar. In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayChar : public CArray
Title
#include <Arrays\ArrayChar.mqh>
Class Methods
Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
805
Standard Library
Shift
Moves an item from a given position in the array to the specified offset
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array methods InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
806
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayChar::Reserve(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
807
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayChar::Resize(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
808
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
809
Standard Library
Add
Adds an element to the end of the array.
bool Add( char element ) // Element to add
Parameters element [in] value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayChar::Add(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
810
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const char& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayChar::AddArray(const char &[]) #include <Arrays\ArrayChar.mqh> //--char src[]; //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
811
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayChar* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayChar-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayChar::AddArray(const CArrayChar*) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayChar *src=new CArrayChar; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
812
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
813
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( char element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayChar::Insert(char,int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
814
Standard Library
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray( const char& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayChar::InsertArray(const char &[],int) #include <Arrays\ArrayChar.mqh> //--char src[]; //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
815
Standard Library
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray( CArrayChar* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayChar-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayChar::InsertArray(const CArrayChar*,int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayChar *src=new CArrayChar; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
816
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
817
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const char& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayChar::AssignArray(const char &[]) #include <Arrays\ArrayChar.mqh> //--char src[]; //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
818
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayChar* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayChar-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayChar::AssignArray(const CArrayChar*) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayChar *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayChar;
819
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
820
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value char element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayChar::Update(int,char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,'A')) { printf("Update error"); delete array; return; } //--- delete array delete array; }
821
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Value
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayChar::Shift(int,int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
822
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] Position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayChar::Delete(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
823
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Positions of the last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayChar::DeleteRange(int,int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
824
Standard Library
At
Gets the element from the given position in the array.
char At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, CHAR_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, CHAR_MAX may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayChar::At(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { char result=array.At(i); if(result==CHAR_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--- error of reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
825
Standard Library
//--- delete array delete array; }
826
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const char& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayChar::CompareArray(const char &[]) #include <Arrays\ArrayChar.mqh> //--char src[]; //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
827
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const CArrayChar* src ) const // Pointer to the sources
Parameters src [in] Pointer to an instance of class CArrayChar-source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayChar::CompareArray(const CArrayChar*) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayChar *src=new CArrayChar; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
828
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( char element ) // Element to insert
Parameters element [in] Value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayChar::InsertSort(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort('A')) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
829
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::Search(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
830
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchGreat(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
831
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchLess(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
832
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array
int SearchGreatOrEqual( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchGreatOrEqual(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
833
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchLessOrEqual(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
834
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchFirst(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
835
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( char element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayChar::SearchLast(char) #include <Arrays\ArrayChar.mqh> //--void OnStart() { CArrayChar *array=new CArrayChar; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast('A')!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
836
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true if successfully completed, false - if an error. Example:
//--- example for CArrayChar::Save(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- delete array delete array; } file_handle; CArrayChar *array=new CArrayChar;
837
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true if successfully completed, false - if an error. Example:
//--- example for CArrayChar::Load(int) #include <Arrays\ArrayChar.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %c",i,array.At(i)); file_handle; CArrayChar *array=new CArrayChar;
838
Standard Library
} //--- delete array delete array; }
839
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
840
Standard Library
CArrayShort
CArrayShort class is a class of dynamic array of variables of type short or ushort.
Description
Class CArrayShort provides the ability to work with a dynamic array of variables of type short or ushort.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayShort : public CArray
Title
#include <Arrays\ArrayShort.mqh>
Class Methods
Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
841
Standard Library
Shift
Moves an item from a given position in the array to the specified offset
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
842
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayShort::Reserve(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
843
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayShort::Resize(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
844
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
845
Standard Library
Add
Adds an element to the end of the array.
bool Add( short element ) // Element to add
Parameters element [in] Value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayShort::Add(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
846
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const short& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayShort::AddArray(const short &[]) #include <Arrays\ArrayShort.mqh> //--short src[]; //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
847
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayShort* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayShort-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayShort::AddArray(const CArrayShort*) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayShort *src=new CArrayShort; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
848
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
849
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( short element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayShort::Insert(short,int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
850
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( const short& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayShort::InsertArray(const short &[],int) #include <Arrays\ArrayShort.mqh> //--short src[]; //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
851
Standard Library
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray( CArrayShort* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayShort-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayShort::InsertArray(const CArrayShort*,int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayShort *src=new CArrayShort; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
852
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
853
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const short& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayShort::AssignArray(const short &[]) #include <Arrays\ArrayShort.mqh> //--short src[]; //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
854
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayShort* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayShort-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayShort::AssignArray(const CArrayShort*) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayShort *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayShort;
855
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
856
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value short element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayShort::Update(int,short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,100)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
857
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Positions // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayShort::Shift(int,int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
858
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] Position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayShort::Delete(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
859
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of the lase element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayShort::DeleteRange(int,int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
860
Standard Library
At
Gets the element from the given position in the array.
short At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, SHORT_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, SHORT_MAX may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayShort::At(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { short result=array.At(i); if(result==SHORT_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--- error of reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
861
Standard Library
//--- delete array delete array; }
862
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const short& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayShort::CompareArray(const short &[]) #include <Arrays\ArrayShort.mqh> //--short src[]; //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
863
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const CArrayShort* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayShort-source elements for comparison. Return Value true if arrays are equal, false - if not.
Example:
//--- example for CArrayShort::CompareArray(const CArrayShort*) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayShort *src=new CArrayShort; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
864
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( short element ) // Element to insert
Parameters element [in] Value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayShort::InsertSort(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(100)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
865
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::Search(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
866
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchGreat(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
867
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchLess(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
868
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchGreatOrEqual(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
869
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchLessOrEqual(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
870
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchFirst(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
871
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( short element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayShort::SearchLast(short) #include <Arrays\ArrayShort.mqh> //--void OnStart() { CArrayShort *array=new CArrayShort; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast(100)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
872
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayShort::Save(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(i); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayShort *array=new CArrayShort;
873
Standard Library
} delete array; }
874
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayShort::Load(int) #include <Arrays\ArrayShort.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %d",i,array.At(i)); file_handle; CArrayShort *array=new CArrayShort;
875
Standard Library
} delete array; }
876
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
877
Standard Library
CArrayInt
CArrayInt class is a class of dynamic array of variables of type int or uint.
Description
Class CArrayInt provides the ability to work with a dynamic array of variables of type int or uint.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayInt : public CArray
Title
#include <Arrays\ArrayInt.mqh>
Class Methods
Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
878
Standard Library
Shift
Moves an item from a given position in the array to the specified offset
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
879
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayInt::Reserve(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
880
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Number
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayInt::Resize(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
881
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
882
Standard Library
Add
Adds an element to the end of the array.
bool Add( int element ) // Element to add
Parameters element [in] value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayInt::Add(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
883
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const int& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayInt::AddArray(const int &[]) #include <Arrays\ArrayInt.mqh> //--int src[]; //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
884
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayInt* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayInt-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayInt::AddArray(const CArrayInt*) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayInt *src=new CArrayInt; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
885
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
886
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( int element, int pos ) // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayInt::Insert(int,int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
887
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( const int& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayInt::InsertArray(const int &[],int) #include <Arrays\ArrayInt.mqh> //--int src[]; //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
888
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( CArrayInt* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayInt-source elements to insert. pos [in] Position in the array to insert. Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayInt::InsertArray(const CArrayInt*,int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayInt *src=new CArrayInt; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
889
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
890
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const int& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayInt::AssignArray(const int &[]) #include <Arrays\ArrayInt.mqh> //--int src[]; //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
891
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayInt* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayInt-source element to copy. Return Value true if successful, false - if you can not copy the items.
Example:
//--- example for CArrayInt::AssignArray(const CArrayInt*) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayInt *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } =new CArrayInt;
892
Standard Library
//--- arrays is identical //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
893
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, int element ) // Position // Value
Parameters pos [in] Position of the element in the array to change. element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayInt::Update(int,int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,10000)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
894
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayInt::Shift(int,int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
895
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] Position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayInt::Delete(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
896
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of the last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayInt::DeleteRange(int,int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
897
Standard Library
At
Gets the element from the given position in the array.
int At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, INT_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, INT_MAX could be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayInt::At(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { int result=array.At(i); if(result==INT_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--- error of reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
898
Standard Library
//--- delete array delete array; }
899
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const int& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayInt::CompareArray(const int &[]) #include <Arrays\ArrayInt.mqh> //--int src[]; //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
900
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const CArrayInt* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayInt-source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayInt::CompareArray(const CArrayInt*) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayInt *src=new CArrayInt; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
901
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( int element ) // Element to insert
Parameters element [in] value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayInt::InsertSort(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(10000)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
902
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::Search(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
903
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::SearchGreat(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
904
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::SearchLess(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
905
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( int element ) const // Element to search
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::SearchGreatOrEqual(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
906
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::SearchLessOrEqual(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
907
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt:: SearchFirst(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
908
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( int element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayInt::SearchLast(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { CArrayInt *array=new CArrayInt; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast(10000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
909
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayInt::Save(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(i); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayInt *array=new CArrayInt;
910
Standard Library
} delete array; }
911
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayInt::Load(int) #include <Arrays\ArrayInt.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %d",i,array.At(i)); file_handle; CArrayInt *array=new CArrayInt;
912
Standard Library
} delete array; }
913
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
914
Standard Library
CArrayLong
CArrayLong class is a class of dynamic array of variables of type long or ulong.
Description
Class CArrayLong provides the ability to work with a dynamic array of variables of type long or ulong. In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayLong : public CArray
Title
#include <Arrays\ArrayLong.mqh>
Class Methods
Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
915
Standard Library
Shift
Moves an item from a given position in the array to the specified offset
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
916
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayLong::Reserve(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
917
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayLong::Resize(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
918
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
919
Standard Library
Add
Adds an element to the end of the array.
bool Add( long element ) // Element to add
Parameters element [in] Value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayLong::Add(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
920
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const long& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayLong::AddArray(const long &[]) #include <Arrays\ArrayLong.mqh> //--long src[]; //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
921
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayLong* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayLong-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayLong::AddArray(const CArrayLong*) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayLong *src=new CArrayLong; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
922
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
923
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( long element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayLong::Insert(long,int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
924
Standard Library
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray( const long& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayLong::InsertArray(const long &[],int) #include <Arrays\ArrayLong.mqh> //--long src[]; //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
925
Standard Library
InsertArray
Inserts an array of elements from another array ukazannogy position.
bool InsertArray( CArrayLong* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayLong-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayLong::InsertArray(const CArrayLong*,int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayLong *src=new CArrayLong; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
926
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
927
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const long& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayLong::AssignArray(const long &[]) #include <Arrays\ArrayLong.mqh> //--long src[]; //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
928
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayLong* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayLong-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayLong::AssignArray(const CArrayLong*) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayLong *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayLong;
929
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
930
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value long element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayLong::Update(int,long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,1000000)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
931
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayLong::Shift(int,int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
932
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] Position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayLong::Delete(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
933
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of the last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayLong::DeleteRange(int,int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
934
Standard Library
At
Gets the element from the given position in the array.
long At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, LONG_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, LONG_MAX may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayLong::At(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { long result=array.At(i); if(result==LONG_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--- Error reading from the array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
935
Standard Library
//--- delete array delete array; }
936
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const long& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayLong::CompareArray(const long &[]) #include <Arrays\ArrayLong.mqh> //--long src[]; //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
937
Standard Library
CompareArrayconst
Compares array with another array.
bool CompareArrayconst( const CArrayLong* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayLong-source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayLong::CompareArray(const CArrayLong*) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayLong *src=new CArrayLong; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
938
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( long element ) // Element to insert
Parameters element [in] Value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element.
Example:
//--- example for CArrayLong::InsertSort(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(1000000)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
939
Standard Library
Search
Searches for an element equal to the model in sorted array.
int Search( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::Search(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
940
Standard Library
SearchGreat
Searches for an element of larger sample, in sorted array.
int SearchGreat( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchGreat(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
941
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchLess(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
942
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the model in sorted array.
int SearchGreatOrEqual( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchGreatOrEqual(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
943
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the model in sorted array.
int SearchLessOrEqual( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchLessOrEqual(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
944
Standard Library
SearchFirst
Finds the first element equal to the model in sorted array.
int SearchFirst( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchFirst(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
945
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( long element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayLong::SearchLast(long) #include <Arrays\ArrayLong.mqh> //--void OnStart() { CArrayLong *array=new CArrayLong; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast(1000000)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
946
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true if successfully completed, false - if an error. Example:
//--- example for CArrayLong::Save(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(i); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayLong *array=new CArrayLong;
947
Standard Library
} delete array; }
948
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true if successfully completed, false - if an error. Example:
//--- example for CArrayLong::Load(int) #include <Arrays\ArrayLong.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %I64",i,array.At(i)); file_handle; CArrayLong *array=new CArrayLong;
949
Standard Library
} delete array; }
950
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
951
Standard Library
CArrayFloat
CArrayFloat class is a class of dynamic array of variables of type float.
Description
Class CArrayFloat provides the ability to work with a dynamic array of variables of type float.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayFloat : public CArray
Title
#include <Arrays\ArrayFloat.mqh>
Class Methods
Attributes Delta Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release Set the comparison tolerance
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
952
Standard Library
Update
Changes the element at the specified position array Moves an item from a given position in the array to the specified offset Removes the element from the specified position array Deletes a group of elements from the specified position array
Shift
Delete
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
953
Standard Library
Delta
Set tolerance comparison.
void Delta( float delta ) // Tolerance
Parameters delta [in] the new value of the admission of comparison. Return Value None Note Admission of comparison used in the search. Values are considered equal if their difference is less than or equal to tolerance. The default tolerance is 0.0. Example:
//--- example for CArrayFloat::Delta(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- set compare variation array.Delta(0.001); //--- use array //--- . . . //--- delete array delete array; }
954
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayFloat::Reserve(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
955
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayFloat::Resize(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
956
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
957
Standard Library
Add
Adds an element to the end of the array.
bool Add( float element ) // Element to add
Parameters element [in] Value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayFloat::Add(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
958
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const float& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayFloat::AddArray(const float &[]) #include <Arrays\ArrayFloat.mqh> //--float src[]; //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
959
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayFloat* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayFloat-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayFloat::AddArray(const CArrayFloat*) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayFloat *src=new CArrayFloat; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
960
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
961
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( float element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayFloat::Insert(float,int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
962
Standard Library
InsertArray
Inserts an array of elements from another array with the specified position.
bool InsertArray( const float& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayFloat::InsertArray(const float &[],int) #include <Arrays\ArrayFloat.mqh> //--float src[]; //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
963
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( CArrayFloat* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayFloat-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayFloat::InsertArray(const CArrayFloat*,int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayFloat *src=new CArrayFloat; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
964
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
965
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const float& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayFloat::AssignArray(const float &[]) #include <Arrays\ArrayFloat.mqh> //--float src[]; //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
966
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayFloat* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayFloat-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayFloat::AssignArray(const CArrayFloat*) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayFloat *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayFloat;
967
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
968
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value float element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayFloat::Update(int,float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,100.0)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
969
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayFloat::Shift(int,int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
970
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] Position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayFloat::Delete(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
971
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayFloat::DeleteRange(int,int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
972
Standard Library
At
Gets the element from the given position in the array.
float At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, FLT_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, FLT_MAX may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayFloat::At(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { float result=array.At(i); if(result==FLT_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--- error reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
973
Standard Library
//--- delete array delete array; }
974
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const float& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayFloat::CompareArray(const float &[]) #include <Arrays\ArrayFloat.mqh> //--float src[]; //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
975
Standard Library
AssignArrayconst
Copies the array elements from another array.
bool AssignArrayconst( const CArrayFloat* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayFloat-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayFloat::CompareArray(const CArrayFloat*) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayFloat *src=new CArrayFloat; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
976
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( float element ) // Element to insert
Parameters element [in] Value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayFloat::InsertSort(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(100.0)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
977
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::Search(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
978
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::SearchGreat(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
979
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat:: SearchLess(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
980
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::SearchGreatOrEqual(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
981
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::SearchLessOrEqual(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
982
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::SearchFirst(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
983
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( float element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayFloat::SearchLast(float) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { CArrayFloat *array=new CArrayFloat; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
984
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayFloat::Save(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(i); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayFloat *array=new CArrayFloat;
985
Standard Library
} delete array; }
986
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayFloat::Load(int) #include <Arrays\ArrayFloat.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %f",i,array.At(i)); file_handle; CArrayFloat *array=new CArrayFloat;
987
Standard Library
} delete array; }
988
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
989
Standard Library
CArrayDouble
CArrayDouble class is a class of dynamic array of variables of type double.
Description
Class CArrayDouble provides the ability to work with a dynamic array of variables of type double.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayDouble : public CArray
Title
#include <Arrays\ArrayDouble.mqh>
Class Methods
Attributes Delta Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a full memory release Set the comparison tolerance
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
990
Standard Library
Update
Changes the element at the specified position array Moves an item from a given position in the array to the specified offset
Shift
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Derived classes: CIndicatorBuffer Saves data array in the file Loads data array from a file Gets the type identifier of the array
991
Standard Library
Delta
Set tolerance comparison.
void Delta( double delta ) // Tolerance
Parameters delta [in] The new value of the admission of comparison. Return Value No Note Admission of comparison used in the search. Values are considered equal if their difference is less than or equal to tolerance. The default tolerance is 0.0. Example:
//--- example for CArrayDouble::Delta(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- set compare variation array.Delta(0.001); //--- use array //--- . . . //--- delete array delete array; }
992
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayDouble::Reserve(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
993
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayDouble::Resize(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
994
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
995
Standard Library
Add
Adds an element to the end of the array.
bool Add( double element ) // Element to add
Parameters element [in] value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayDouble::Add(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(i)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
996
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const double& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayDouble::AddArray(const double &[]) #include <Arrays\ArrayDouble.mqh> //--double src[]; //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
997
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayDouble* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayDouble-source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayDouble::AddArray(const CArrayDouble*) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayDouble *src=new CArrayDouble; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
998
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
999
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( double element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayDouble::Insert(double,int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(i,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
1000
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( const double& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayDouble::InsertArray(const double &[],int) #include <Arrays\ArrayDouble.mqh> //--double src[]; //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1001
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( CArrayDouble* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayDouble-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayDouble::InsertArray(const CArrayDouble*,int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayDouble *src=new CArrayDouble; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
1002
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
1003
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const double& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayDouble::AssignArray(const double &[]) #include <Arrays\ArrayDouble.mqh> //--double src[]; //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1004
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayDouble* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayDouble-source element to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayDouble::AssignArray(const CArrayDouble*) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayDouble *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayDouble;
1005
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
1006
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value double element )
Parameters pos [in] Position of the element in the array to change element [in] New value. Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayDouble::Update(int,double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,100.0)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
1007
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayDouble::Shift(int,int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
1008
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayDouble::Delete(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1009
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayDouble::DeleteRange(int,int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1010
Standard Library
At
Gets the element from the given position in the array.
double At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, DBL_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, DBL_MAX may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayDouble::At(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { double result=array.At(i); if(result==DBL_MAX && GetLastError()==ERR_OUT_OF_RANGE) { //--Error reading from the array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
1011
Standard Library
//--- delete array delete array; }
1012
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const double& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayDouble::CompareArray(const double &[]) #include <Arrays\ArrayDouble.mqh> //--double src[]; //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
1013
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const CArrayDouble* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayDouble-source elements for comparison. Return Value true if arrays are equal, false - if not.
Example:
//--- example for CArrayDouble::CompareArray(const CArrayDouble*) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayDouble *src=new CArrayDouble; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
1014
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( double element ) // Element to insert
Parameters element [in] value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayDouble::InsertSort(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(100.0)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
1015
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::Search(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1016
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::SearchGreat(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1017
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble:: SearchLess(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1018
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::SearchGreatOrEqual(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1019
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::SearchLessOrEqual(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1020
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::SearchFirst(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1021
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( double element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayDouble::SearchLast(double) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { CArrayDouble *array=new CArrayDouble; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast(100.0)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1022
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayDouble::Save(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(i); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayDouble *array=new CArrayDouble;
1023
Standard Library
} //--- delete array delete array; }
1024
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayDouble::Load(int) #include <Arrays\ArrayDouble.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %f",i,array.At(i)); file_handle; CArrayDouble *array=new CArrayDouble;
1025
Standard Library
} //--- delete array delete array; }
1026
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
1027
Standard Library
CArrayString
CArrayString class is a class of dynamic array of variables of type string.
Description
Class CArrayString provides the ability to work with a dynamic array of variables of type string.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.
Declaration
class CArrayString : public CArray
Title
#include <Arrays\ArrayString.mqh>
Class Methods
Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Sets a new (smaller) size of the array
Adds an element to the end of the array Adds to the end of the array elements from another array Adds to the end of the array elements from another array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array Copies the array elements from another array
AddArray
Insert
InsertArray
InsertArray
1028
Standard Library
Shift
Moves an item from a given position in the array to the specified offset
Delete methods Delete Removes the element from the specified position array Deletes a group of elements from the specified position array
DeleteRange
Access methods At Gets the element from the specified position array
Compare methods CompareArray CompareArray Sorted array opetations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output virtual Save virtual Load virtual Type Saves data array in the file Loads data array from a file Gets the type identifier of the array
1029
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayString::Reserve(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- reserve memory if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1030
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value true if successful, false - if there was an attempt to set the size of less than or equal to zero. Note Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayString::Resize(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array; }
1031
Standard Library
Shutdown
Clears the array with a full memory release.
bool Shutdown()
1032
Standard Library
Add
Adds an element to the end of the array.
bool Add( string element ) // Element to add
Parameters element [in] value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Example:
//--- example for CArrayString::Add(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements for(int i=0;i<100;i++) { if(!array.Add(IntegerToString(i))) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
1033
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const string& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayString::AddArray(const string &[]) #include <Arrays\ArrayString.mqh> //--string src[]; //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1034
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayString* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayString - the source of elements to add. Return Value true if successful, false - if you can not add items. Example:
//--- example for CArrayString::AddArray(const CArrayString*) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayString *src=new CArrayString; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array delete src;
1035
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
1036
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( string element, int ) pos // Element to insert // Position
Parameters element [in] Value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayString::Insert(string,int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(IntegerToString(i),0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
1037
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( const string& src[], int ) pos // Source array // Position
Parameters src[] [in] Reference to an array of source elements to insert pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayString::InsertArray(const string &[],int) #include <Arrays\ArrayString.mqh> //--string src[]; //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1038
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( CArrayString* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayString - the source of elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Example:
//--- example for CArrayString::InsertArray(const CArrayString*,int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayString *src=new CArrayString; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- insert another array if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array;
1039
Standard Library
return; } //--- delete source array delete src; //--- use array //--- . . . //--- delete array delete array; }
1040
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const string& src[] ) // Source array
Parameters src[] [in] Reference to an array of source elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayString::AssignArray(const string &[]) #include <Arrays\ArrayString.mqh> //--string src[]; //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1041
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayString* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayString - source of elements to copy. Return Value true if successful, false - if you can not copy the items. Example:
//--- example for CArrayString::AssignArray(const CArrayString*) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayString *src if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- assign another array if(!array.AssignArray(src)) { printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array =new CArrayString;
1042
Standard Library
delete src; //--- use array //--- . . . //--- delete array delete array; }
1043
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value string element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Example:
//--- example for CArrayString::Update(int, string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,"ABC")) { printf("Update error"); delete array; return; } //--- delete array delete array; }
1044
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayString::Shift(int,int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
1045
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Example:
//--- example for CArrayString::Delete(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete element if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1046
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Example:
//--- example for CArrayString::DeleteRange(int,int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1047
Standard Library
At
Gets the element from the given position in the array.
string At( int pos ) const // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element in case of success, "- if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE). Note Of course, "" may be a valid value of an array element, so having a value, always check the last error code. Example:
//--- example for CArrayString::At(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . for(int i=0;i<array.Total();i++) { string result=array.At(i); if(result=="" && GetLastError()==ERR_OUT_OF_RANGE) { //--- Error reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . }
1048
Standard Library
//--- delete array delete array; }
1049
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const string& src[] ) const // Source array
Parameters src[] [in] Reference to an array of source elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayString::CompareArray(const string &[]) #include <Arrays\ArrayString.mqh> //--string src[]; //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- compare with another array int result=array.CompareArray(src); //--- delete array delete array; }
1050
Standard Library
CompareArray
Compares array with another array.
bool CompareArrays( const CArrayString* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayString - the source of elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayString::CompareArray(const CArrayString*) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayString *src=new CArrayString; if(src==NULL) { printf("Object create error"); delete array; return; } //--- add source arrays elements //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
1051
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( string element ) // Element to insert
Parameters element [in] value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Example:
//--- example for CArrayString::InsertSort(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort("ABC")) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
1052
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString::Search(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.Search("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1053
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString::SearchGreat(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreat("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1054
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString:: SearchLess(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLess("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1055
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString:: SearchGreatOrEqual(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchGreatOrEqual("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1056
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString:: SearchLessOrEqual(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLessOrEqual("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1057
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString:: SearchFirst(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchFirst("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1058
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( string element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayString:: SearchLast(string) #include <Arrays\ArrayString.mqh> //--void OnStart() { CArrayString *array=new CArrayString; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- search element if(array.SearchLast("ABC")!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1059
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayString::Save(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { array.Add(IntegerToString(i)); } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); file_handle; CArrayString *array=new CArrayString;
1060
Standard Library
} delete array; }
1061
Standard Library
Load
Loads data array from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayString::Load(int) #include <Arrays\ArrayString.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrays elements for(int i=0;i<array.Total();i++) { printf("Element[%d] = %s",i,array.At(i)); file_handle; CArrayString *array=new CArrayString;
1062
Standard Library
} delete array; }
1063
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
1064
Standard Library
CArrayObj
CArrayObj class is a class of dynamic array of pointers to instances of CObject and his heirs.
Description
Class CArrayObj provides the ability to work with a dynamic array of pointers to instances of CObject and his heirs. This gives the possibility to work as a multidimensional dynamic arrays of primitive data types, and the more difficult for organized data structures. In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array. In addition, the implemented methods of work with the file. There are certain subtleties of the class CArrayObj.
Declaration
class CArrayObj : public CArray
Title
#include <Arrays\ArrayObj.mqh>
Class Method
Attributes FreeMode FreeMode Memory control Reserve Allocates memory to increase the size of the array Sets a new (smaller) size of the array Clears the array with a total exemption memory array (not element). Gets the flag memory management Sets the flag memory management
Resize Shutdown
Add methods Add AddArray Insert Adds an element to the end of the array Adds an element to the end of the array Inserts an element in the array to the specified position Inserts an array of elements from another array with the specified position Copies the array elements from another array
InsertArray
1065
Standard Library
Update
Changes the element at the specified position array Moves an item from a given position in the array to the specified offset
Shift
Delete methods Detach Gets the element from the specified position and removing it from the array Removes the element from the specified position array Deletes a group of elements from the specified position array Removes all elements of the array without the release of the memory array
Delete
DeleteRange
Clear
Access methods At Gets the element from the specified position array
Compare methods CompareArray Sorted array operations InsertSort Search Inserts element in a sorted array Searches for an element equal to the model in sorted array Searches for an element of more samples in sorted array Searches for an element less than the sample in the sorted array Searches for an element greater than or equal to the model in sorted array Searches for an element less than or equal to the model in sorted array Finds the first element equal to the model in sorted array Finds the last element equal to the model in sorted array Compares array with another array
SearchGreat
SearchLess
SearchGreatOrEqual
SearchLessOrEqual
SearchFirst
SearchLast
Input/output Save Load Saves data array in the file Loads data array from a file
1066
Standard Library
Practical application of arrays are descendants of class CObject (including all classes of the standard library). For example, consider the options for two-dimensional array:
#include <Arrays\ArrayDouble.mqh> #include <Arrays\ArrayObj.mqh> //--void OnStart() { int i,j; int first_size=10; int second_size=100; //--- create array CArrayObj //--if(array==NULL) { printf("Object create error"); return; } //--- create subarrays for(i=0;i<first_size;i++) { sub_array=new CArrayDouble; if(sub_array==NULL) { delete array; printf("Object create error"); return; } //--- fill array for(j=0;j<second_size;j++) { sub_array.Add(i*j); } array.Add(sub_array); } //--- create array OK for(i=0;i<first_size;i++) { *array=new CArrayObj; CArrayDouble *sub_array;
1067
Standard Library
sub_array=array.At(i); for(j=0;j<second_size;j++) { double element=sub_array.At(j); //--- use array element } } delete array; }
Subtleties
The class has a mechanism to control dynamic memory, so be careful when working with elements of the array. Mechanism of memory management can be switched on / off using the method FreeMode (bool). By default, the mechanism is enabled. Accordingly, there are two options for dealing with the class CArrayObj: 1. Mechanism of memory management is enabled. (default) In this case, CArrayObj take responsibility for freeing the memory elements after their removal from the array. In this program the user should not free the array elements. Example:
int i; //--- Create an array CArrayObj *array=new CArrayObj; //--- Fill array elements for(i=0;i<10;i++) array.Add(new CObject); //--- Do something for(i=0;i<array.Total();i++) { CObject *object=array.At(i); //--- Action with an element . . . } //--- Remove the array with the elements delete array;
2. Mechanism of memory management is turned off. In this case, CArrayObj not otvetstvechaet for freeing the memory elements after their removal from the array. In this program the user must free the array elements. Example:
int i;
1068
Standard Library
//--- Create an array CArrayObj *array=new CArrayObj; //--- Disable the mechanism of memory management array.FreeMode(false); //--- Fill array elements for(i=0;i<10;i++) array.Add(new CObject); //--- Do something for(i=0;i<array.Total();i++) { CObject *object=array.At(i); //--- Action with an element . . . } //--- Remove array elements while(array.Total()) delete array.Detach(); //--- Remove empty array delete array;
1069
Standard Library
FreeMode
Gets the flag memory management.
bool FreeMode() const
1070
Standard Library
FreeMode
Sets the flag memory management.
void FreeMode( bool mode ) // New flag
Parameters mode [in] New value of the flag memory management. Return Value None. Note Setting the flag memory management - an important point in the use of class CArrayObj.Since the array elements are pointers to dynamic objects, it is important to determine what to do with them when removing from the array. If the flag is set, removing an element from the array, the element is automatically deleted by the operator delete.If the flag is not set, it is assumed that a pointer to the deleted object is still somewhere in the user program and will be relieved of it (the program) then. If the user resets the flag memory management, the user must understand their responsibility for the removal of the array before the completion of the program, because otherwise, is not freed memory occupied by the elements when they create new operator. When large amounts of data, it could lead, eventually, even to break your terminal.If the user does not reset the flag memory management, there is another "reef". Using pointers, array, stored somewhere in the local variables, after removing the array will lead to a critical error and crashes the program user.By default, the memory management flag is set, ie the class of the array is responsible for freeing the memory elements. Example:
//--- example for CArrayObj::FreeMode(bool) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- reset free mode flag array.FreeMode(false);
1071
Standard Library
//--- use array //--- . . . //--- delete array delete array; }
1072
Standard Library
Reserve
Allocates memory to increase the size of the array.
bool Reserve( int size ) // Number
Parameters size [in] The number of additional elements of the array. Return Value true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase. Note To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayObj::Reserve(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } if(!array.Reserve(1024)) { printf("Reserve error"); delete array; return; } //--- use array //--- . . . //--- delete array delete array; }
1073
Standard Library
Resize
Sets a new (smaller) size of the array.
bool Resize( int size ) // Size
Parameters size [in] New size of the array. Return Value To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Note Changing the size of array allows to use memory in the optimal way. Excess element located to the right are lost. The memory for lost elements is released or not depending on the mode of memory management. To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default). Example:
//--- example for CArrayObj::Resize(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- resize array if(!array.Resize(10)) { printf("Resize error"); delete array; return; } //--- delete array delete array;
1074
Standard Library
}
1075
Standard Library
Clear
Removes all elements of the array without the release of the memory array.
void Clear()
Return Value No. Note If enabled memory management, memory, deleted items are exempt. Example:
//--- example for CArrayObj::Clear() #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- clear array array.Clear(); //--- delete array delete array; }
1076
Standard Library
Shutdown
Clears the array with a total exemption memory array (not element).
bool Shutdown()
Return Value true if successful, false - if an error occurred. Note If enabled memory management, memory, deleted items are exempt. Example:
//--- example for CArrayObj::Shutdown() #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shutdown array if(!array.Shutdown()) { printf("Shutdown error"); delete array; return; } //--- delete array delete array; }
1077
Standard Library
CreateElement
Creates a new array element at the specified position.
bool CreateElement( int index ) // Position
Parameters index [in] position in which you want to create a new element. Return Value true if successful, false - if you can not create element. Note Method CreateElement (int) in class CArrayObj always returns false and does not perform any action. If necessary, in a derived class, method CreateElement (int) should be implemented. Example:
//--- example for CArrayObj::CreateElement(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { int //--if(array==NULL) { printf("Object create error"); return; } //--- fill array array.Reserve(size); for(int i=0;i<size;i++) { if(!array.CreateElement(i)) { printf("Element create error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; size=100; CArrayObj *array=new CArrayObj;
1078
Standard Library
}
1079
Standard Library
Add
Adds an element to the end of the array.
bool Add( CObject* element ) // Element to add
Parameters element [in] value of the element to add to the array. Return Value true if successful, false - if you can not add an element. Note Element is not added to the array if the value for transmit invalid pointer (such as NULL). Example:
//--- example for CArrayObj::Add(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add 100 arrays elements for(int i=0;i<100;i++) { if(!array.Add(new CObject)) { printf("Element addition error"); delete array; return; } } //--- use array //--- . . . //--- delete array delete array; }
1080
Standard Library
AddArray
Adds to the end of the array elements from another array.
bool AddArray( const CArrayObj * src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayDouble - source of elements to add. Return Value true if successful, false - if you can not add items. Note Adding elements of the array in the array is actually copying the pointers.Therefore, when calling the method, there is a "reef" - that there may be a pointer to a dynamic object in more than one variable.
//--- example extern bool extern int make_error; error;
extern CArrayObj *src; //--- Create a new instance CArrayObj //--- Default memory management is turned on CArrayObj *array=new CArrayObj; //--- Add (copy) the elements of the array-istochika if(array!=NULL) bool result=array.AddArray(src); if(make_error) { //--- Commit wrongdoing switch(error) { case 0: //--- Remove the array-source, without checking its flag memory management delete src; //--- Result: //--- May appeal //--- For "bitomu" pointer in the array receiver break; case 1: //--- Disable the mechanism of memory management in an array of source if(src.FreeMode()) src.FreeMode(false); //--- But do not remove the array-source //--- Result: //--- After removal of the array, the receiver may appeal
1081
Standard Library
//--- For "bitomu" pointer in the array-source break; case 2: //--- Disable the mechanism of memory management in an array of source src.FreeMode(false); //--- Disable the mechanism of memory management in an array receiver array.FreeMode(false); //--- Result: //--- After the completion of the program, obtain a "memory leak" break; } } else { //--- Disable the mechanism of memory management in an array of source if(src.FreeMode()) src.FreeMode(false); //--- Remove the array-source delete src; //--- Result: //--- Treatment for an array-recepient be correct //--- Delete the array, the receiver will delete its elements }
Example:
//--- example for CArrayObj::AddArray(const CArrayObj*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayObj *src=new CArrayObj; if(src==NULL) { printf("Object create error"); delete array; return; } //--- reset free mode flag src.FreeMode(false); //--- fill source array
1082
Standard Library
//--- . . . //--- add another array if(!array.AddArray(src)) { printf("Array addition error"); delete src; delete array; return; } //--- delete source array without elements delete src; //--- use array //--- . . . //--- delete array delete array; }
1083
Standard Library
Insert
Inserts an element in the array to the specified position.
bool Insert( CObject* element, int ) pos // Element to insert // Position
Parameters element [in] value of the element to be inserted into an array pos [in] Position in the array to insert Return Value true if successful, false - if you can not insert the element. Note Element is not added to the array if the value for transmit invalid pointer (such as NULL). Example:
//--- example for CArrayObj::Insert(CObject*,int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- insert elements for(int i=0;i<100;i++) { if(!array.Insert(new CObject,0)) { printf("Insert error"); delete array; return; } } //--- use array //--- . . . //--- delete array
1084
Standard Library
delete array; }
1085
Standard Library
InsertArray
Inserts an array of elements from another array specified position.
bool InsertArray( const CArrayObj* src, int ) pos // Pointer to the source // Position
Parameters src [in] Pointer to an instance of class CArrayObj-source elements to insert. pos [in] Position in the array to insert Return Value true if successful, false - if you can not paste items. Note See: CArrayObj::AddArray(const CArrayObj*). Example:
//--- example for CArrayObj::InsertArray(const CArrayObj*,int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayObj *src=new CArrayObj; if(src==NULL) { printf("Object create error"); delete array; return; } //--- reset free mode flag src.FreeMode(false); //--- fill source array //--- . . . //--- insert another array
1086
Standard Library
if(!array.InsertArray(src,0)) { printf("Array inserting error"); delete src; delete array; return; } //--- delete source array without elements delete src; //--- use array //--- . . . //--- delete array delete array; }
1087
Standard Library
AssignArray
Copies the array elements from another array.
bool AssignArray( const CArrayObj* src ) // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayObj - source of elements to copy. Return Value true if successful, false - if you can not copy the items. Note If the challenge AssignArray array receiver is not empty, all its elements will be removed from the array and, if the flag memory management, memory, deleted items will be released.Array-receiver is an exact copy of the array source. Additionally see CArrayObj::AddArray(const CArrayObj*). Example:
//--- example for CArrayObj::AssignArray(const CArrayObj*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayObj *src=new CArrayObj; if(src==NULL) { printf("Object create error"); delete array; return; } //--- reset free mode flag src.FreeMode(false); //--- fill source array //--- . . . //--- assign another array if(!array.AssignArray(src)) {
1088
Standard Library
printf("Array assigned error"); delete src; delete array; return; } //--- arrays is identical //--- delete source array without elements delete src; //--- use array //--- . . . //--- delete array delete array; }
1089
Standard Library
Update
Changes the element at the specified position array.
bool Update( int pos, // Position // Value CObject* element )
Parameters pos [in] Position of the element in the array to change element [in] New value element Return Value true if successful, false - if you can not change the element. Note The element does not change if we as a parameter to pass an invalid pointer (ie NULL). If enabled memory management, memory placeholder released. Example:
//--- example for CArrayObj::Update(int,CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- update element if(!array.Update(0,new CObject)) { printf("Update error"); delete array; return; } //--- delete array delete array; }
1090
Standard Library
Shift
Moves an item from a given position in the array to the specified offset.
bool Shift( int pos, int shift ) // Position // Shift
Parameters pos [in] Position of the moved element array shift [in] The value of displacement (both positive and negative). Return Value true if successful, false - if you can not move the item. Example:
//--- example for CArrayObj::Shift(int,int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- shift element if(!array.Shift(10,-5)) { printf("Shift error"); delete array; return; } //--- delete array delete array; }
1091
Standard Library
Detach
Remove an item from a given position in the array.
CObject* Detach( int pos ) // Position
Parameters pos [in] Position of the seized item in the array. Return Value Pointer to the removal of elements in case of success, NULL - if you can not remove the element. Note When removed from the array element is not removed in any state of the flag memory management. Pointer to the array element withdrawn from the ingredients of the release after use. Example:
//--- example for CArrayObj::Detach(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . CObject *object=array.Detach(0); if(object==NULL) { printf("Detach error"); delete array; return; } //--- use element //--- . . . //--- delete element delete object; //--- delete array delete array; }
1092
Standard Library
Delete
Removes the element from the given position in the array.
bool Delete( int pos ) // Position
Parameters pos [in] position removes the element in the array. Return Value true if successful, false - if you can not remove the element. Note If enabled memory management, memory, deleted items are exempt. Example:
//--- example for CArrayObj::Delete(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . if(!array.Delete(0)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1093
Standard Library
DeleteRange
Deletes a group of elements from a given position in the array.
bool DeleteRange( int from, int to ) // Position of the first element // Position of last element
Parameters from [in] Position of the first removes the element in the array. to [in] Position of the last deleted element in the array. Return Value true if successful, false - if you can not remove elements. Note If enabled memory management, memory, deleted items are exempt. Example:
//--- example for CArrayObj::DeleteRange(int,int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- delete elements if(!array.DeleteRange(0,10)) { printf("Delete error"); delete array; return; } //--- delete array delete array; }
1094
Standard Library
At
Gets the element from the given position in the array.
CObject* At( int pos ) // Position
Parameters pos [in] Position of the desired element in the array. Return Value The value of the element, if successful, NULL-if there was an attempt to get an element of nonexistent position. Example:
//--- example for CArrayObj::At(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add elements //--- . . . for(int i=0;i<array.Total();i++) { CObject *result=array.At(i); if(result==NULL) { //--- Error reading from array printf("Get element error"); delete array; return; } //--- use element //--- . . . } delete array; }
1095
Standard Library
CompareArray
Compares array with another array.
bool CompareArray( const CArrayObj* src ) const // Pointer to the source
Parameters src [in] Pointer to an instance of class CArrayObj - the source of elements for comparison. Return Value true if arrays are equal, false - if not. Example:
//--- example for CArrayObj::CompareArray(const CArrayObj*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- create source array CArrayObj *src=new CArrayObj; if(src==NULL) { printf("Object create error"); delete array; return; } //--- fill source array //--- . . . //--- compare with another array int result=array.CompareArray(src); //--- delete arrays delete src; delete array; }
1096
Standard Library
InsertSort
Inserts element in a sorted array.
bool InsertSort( CObject* element ) // Element to insert
Parameters element [in] Value of the element to be inserted into a sorted array Return Value true if successful, false - if you can not insert the element. Note Element is not added to the array if the value for transmit invalid pointer (such as NULL). Example:
//--- example for CArrayObj::InsertSort(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- insert element if(!array.InsertSort(new CObject)) { printf("Insert error"); delete array; return; } //--- delete array delete array; }
1097
Standard Library
Search
Searches for an element equal to the sample in the sorted array.
int Search( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj::Search(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.Search(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1098
Standard Library
SearchGreat
Searches for an element of more samples in sorted array.
int SearchGreat( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj::SearchGreat(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchGreat(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1099
Standard Library
SearchLess
Searches for an element less than the sample in the sorted array.
int SearchLess( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj:: SearchLess(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchLess(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1100
Standard Library
SearchGreatOrEqual
Searches for an element greater than or equal to the sample in the sorted array.
int SearchGreatOrEqual( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj::SearchGreatOrEqual(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchGreatOrEqual(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1101
Standard Library
SearchLessOrEqual
Searches for an element less than or equal to the sample in the sorted array.
int SearchLessOrEqual( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj:: SearchLessOrEqual(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchLessOrEqual(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1102
Standard Library
SearchFirst
Finds the first element equal to the sample in the sorted array.
int SearchFirst( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj::SearchFirst(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchFirst(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1103
Standard Library
SearchLast
Finds the last element equal to the model in sorted array.
int SearchLast( CObject* element ) const // Sample
Parameters element [in] The sample element to search in the array. Return Value The position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CArrayObj:: SearchLast(CObject*) #include <Arrays\ArrayObj.mqh> //--void OnStart() { CArrayObj *array=new CArrayObj; //--if(array==NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- sort array array.Sort(); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete array; return; } //--- set sample attributes //--- . . . //--- search element if(array.SearchLast(sample)!=-1) printf("Element found"); else //--- delete array delete array; } printf("Element not found");
1104
Standard Library
Save
Saves data array in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] Handle to previously opened by FileOpen (...) function binary file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CArrayObj::Save(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- add arrays elements //--- . . . //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } delete array; } file_handle; CArrayObj *array=new CArrayObj;
1105
Standard Library
Load
Loads data array from a file.s
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle to open earlier, with the function FileOpen (...), binary file. Return Value true - if successfully completed, false - if an error. Note When reading from the file array to create each element of the method is called CArrayObj:: CreateElement(int). Example:
//--- example for CArrayObj::Load(int) #include <Arrays\ArrayObj.mqh> //--void OnStart() { int //--if(array!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!array.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete array; FileClose(file_handle); //--return; } FileClose(file_handle); } file_handle; CArrayObj *array=new CArrayObj;
1106
Standard Library
//--- use arrays elements //--- . . . //--- delete array delete array; }
1107
Standard Library
Type
Gets the type identifier of the array.
virtual int Type() const
1108
Standard Library
CList
CList Class is a class of dynamic list of instances of the class CObject and his heirs.
Description
Class CList provides the ability to work with a list of instances of CObject and his heirs. In the class implemented the ability to add / insert / delete items in the list, sort the list, search in sorted list. In addition, the implemented methods of work with the file. There are some subtleties of working with the class CList. The class has a mechanism to control dynamic memory, so be careful when working with elements of the list. Subtleties of the mechanism of memory management similar to those described in CArrayObj.
Declaration
class CList : public CObject
Title
#include <Arrays\List.mqh>
Class Methods
Attributes FreeMode Gets the flag memory management when deleting list items. Sets the flag memory management when deleting items in the list Gets the number of elements in the list Gets flag sorted list Gets the version of the sorting
FreeMode
Total IsSorted SortMode Create methods CreateElement Add methods Add Insert
Adds element to the end of the list Inserts element in the list in the specified position
Delete methods DetachCurrent Remove an item from the current position of the list without deleting it "physically" Removes the element from the current position
DeleteCurrent
1109
Standard Library
in the list Delete Removes the element from the specified position in the list Removes all list items
Clear Navigation IndexOf GetNodeAtIndex GetFirstNode GetPrevNode GetCurrentNode GetNextNode GetLastNode Ordering methods Sort MoveToIndex
Gets the index of the list item Gets an item with the specified index of the list Gets the first element of the list Gets the previous element list Gets the current list item Gets the next item in the list Gets the last item
Sort list Moves the current item list to the specified position Changes elements of the list seats
Input/output virtual Save virtual Load virtual Type Saves data in the file list Loads data from file list Gets the type identifier list
1110
Standard Library
FreeMode
Gets the flag memory management when deleting list items.
bool FreeMode() const
1111
Standard Library
FreeMode
Sets the flag memory management when deleting list items.
void FreeMode( bool mode ) // New value
Parameters mode [in] New value of the flag memory management. Note Setting the flag memory management - an important point in the use of class CList.Since the elements of the list are pointers to dynamic objects, it is important to determine what to do with them when you delete from the list.If the flag is set, then when you delete an item from the list, the item is automatically deleted by the operator delete.If the flag is not set, it is assumed that a pointer to the deleted object is still somewhere in the user program and will be relieved of it (the program) then. If the user resets the flag memory management, the user must understand their responsibility for the removal of items in the list before completing the program, because otherwise, is not freed memory occupied by the elements when they create new operator.When large amounts of data, it could lead, eventually, even to break your terminal. If the user does not reset the flag memory management, there is another "reef".Using pointers-list items that are stored somewhere in the local variables, after removing the list, will lead to a critical error and crashes the program user.By default, the memory management flag is set, ie the class list, is responsible for freeing the memory elements. Example:
//--- example for CList::FreeMode(bool) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- reset free mode flag list.FreeMode(false); //--- use list //--- . . . //--- delete list delete list;
1112
Standard Library
}
1113
Standard Library
Total
Gets the number of elements in the list.
int Total() const
1114
Standard Library
IsSorted
Gets the flag sorted list.
bool IsSorted( int mode=0 ) const // Sorting mode
Parameters mode=0 [in] Tested version sorting Return Value Flag of the sorted list. If the list is sorted by the specified option? true, otherwise? false. Note Flag of the sorted list can not be changed directly. Flag set by Sort (int) and resets any methods to add / insert. Example:
//--- example for CList::IsSorted() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- check sorted if(list.IsSorted(0)) { //--- use methods for sorted list //--- ... } //--- delete list delete list; }
1115
Standard Library
SortMode
Gets the version of the sort.
int SortMode() const
1116
Standard Library
CreateElement
Creates a new item to the list.
CObject* CreateElement()
Return Value Pointer to the newly created element, if successful, NULL - if you can not create element. Note Method CreateElement () in class CList always returns NULL and does not perform any actions. If necessary, in a derived class, method CreateElement () should be implemented. Example:
//--- example for CList::CreateElement(int) #include <Arrays\List.mqh> //--void OnStart() { int //--if(list==NULL) { printf("Object create error"); return; } //--- fill list for(int i=0;i<size;i++) { CObject *object=list.CreateElement(); if(object==NULL) { printf("Element create error"); delete list; return; } list.Add(object); } //--- use list //--- . . . //--- delete list delete list; } size=100; CList *list=new CList;
1117
Standard Library
Add
Adds an element to the end of the list.
int Add( CObject* element ) // Element to add
Parameters element [in] Value of the element to add to the list. Return Value If successful, it returns the index of added element, or -1 in the case of error. Note Element is not added to the list, if the parameter does not pass valid pointer (ie NULL). Example:
//--- example for CList::Add(Cobject*) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add 100 elements for(int i=0;i<100;i++) { if(list.Add(new CObject)==-1) { printf("Element addition error"); delete list; return; } } //--- use list //--- . . . //--- delete list delete list; }
1118
Standard Library
Insert
Inserts element in the list in the specified position.
int Insert( CObject* element, int ) pos // Element to insert // Position
Parameters element [in] value of the element to insert in the list pos [in] Position in the list to insert Return Value If successful, it returns the index of inserted element, or -1 in the case of error. Note Element is not added to the list, if the parameter does not pass valid pointer (ie NULL). Example:
//--- example for CList::Insert(CObject*,int) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- insert 100 elements for(int i=0;i<100;i++) { if(list.Insert(new CObject,0)==-1) { printf("Element insert error"); delete list; return; } } //--- use list //--- . . . //--- delete list
1119
Standard Library
delete list; }
1120
Standard Library
DetachCurrent
Extracts an element from the current position without its "physical" deleteion.
CObject* DetachCurrent()
Return Value Pointer to the removal of elements in case of success, NULL - if you can not remove the element. Note When removed from the list, the item is not removed in any state of the flag memory management. Pointer to withdraw from the list of ingredients of the release element after use. Example:
//--- example for CList::DetachCurrent() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.DetachCurrent(); if(object==NULL) { printf("Detach error"); delete list; return; } //--- use element //--- . . . //--- delete element delete object; //--- delete list delete list; }
1121
Standard Library
DeleteCurrent
Removes the element from the current position in the list.
bool DeleteCurrent()
Return Value true if successful, false - if you can not remove the element. Note If enabled memory management, memory, removes the element is released. Example:
//--- example for CList::DeleteCurrent() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . if(!list.DeleteCurrent()) { printf("Delete error"); delete list; return; } //--- delete list delete list; }
1122
Standard Library
Delete
Removes the element from the given position in the list.
bool Delete( int pos ) // Position
Parameters pos [in] position removes the element in the list. Return Value true if successful, false - if you can not remove the element. Note If enabled memory management, memory, removes the element is released. Example:
//--- example for CList::Delete(int) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . if(!list.Delete(0)) { printf("Delete error"); delete list; return; } //--- delete list delete list; }
1123
Standard Library
Clear
Removes all elements of the list.
void Clear()
Note If enabled memory management, memory, deleted items are exempt. Example:
//--- example for CList::Clear() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . //--- clear list list.Clear(); //--- delete list delete list; }
1124
Standard Library
IndexOf
Gets the index of the list item.
int IndexOf( CObject* element ) // Pointer to the element
Parameters element [in] Pointer to the list item. Return Value Index item in the list, or -1. Example:
//--- example for CList::IndexOf(CObject*) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } CObject *object=new CObject; if(object==NULL) { printf("Element create error"); delete list; return; } if(list.Add(object)) { int pos=list.IndexOf(object); } //--- delete list delete list; }
1125
Standard Library
GetNodeAtIndex
Gets an item with the specified index of the list.
CObject* GetNodeAtIndex( int pos ) // position
Parameters pos [in] item index in the list. Returned value Pointer to the item in case of success, NULL - if you can not get a pointer. Example:
//--- example for CList::GetNodeAtIndex(int) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetNodeAtIndex(10); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1126
Standard Library
GetFirstNode
Gets the first element of the list.
CObject* GetFirstNode()
Return Value Pointer to the first item in case of success, NULL - if you can not get a pointer. Example:
//--- example for CList::GetFirstNode() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetFirstNode(); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1127
Standard Library
GetPrevNode
Gets the previous element of the list.
CObject* GetPrevNode()
Return Value Pointer to the previous element, if successful, NULL - if you can not get a pointer. Example:
//--- example for CList::GetPrevNode() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetPrevNode(); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1128
Standard Library
GetCurrentNode
Gets the current list item.
CObject* GetCurrentNode()
Return Value Pointer to the current item, if successful, NULL - if you can not get a pointer. Example:
//--- example for CList::GetCurrentNode() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetCurrentNode(); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1129
Standard Library
GetNextNode
Gets the next item in the list.
CObject* GetNextNode()
Return Value Pointer to the next item if successful, NULL - if you can not get a pointer. Example:
//--- example for CList::GetNextNode() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetNextNode(); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1130
Standard Library
GetLastNode
Gets the last element of the list.
CObject* GetLastNode()
Return Value Pointer to the last element in the case of success, NULL - if you can not get a pointer. Example:
//--- example for CList::GetLastNode() #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add list elements //--- . . . CObject *object=list.GetLastNode(); if(object==NULL) { printf("Get node error"); delete list; return; } //--- use element //--- . . . //--- do not delete element //--- delete list delete list; }
1131
Standard Library
Sort
Sorts a list.
void Sort( int mode ) // Sorting mode
Parameters mode [in] Sorting mode. Return Value No. Note Sorting the list is always in ascending order. Example:
//--- example for CList::Sort(int) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- sorting by mode 0 list.Sort(0); //--- use list //--- ... //--- delete list delete list; }
1132
Standard Library
MoveToIndex
Moves the current item list to the specified position.
bool MoveToIndex( int pos ) // Position
Parameters pos [in] Position in the list to move. Return Value true if successful, false - if you can not move the item. Example:
//--- example for CList::MoveToIndex(int) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- move current node to begin list.MoveToIndex(0); //--- use list //--- . . . //--- delete list delete list; }
1133
Standard Library
Exchange
Changes elements of the list seats.
bool Exchange( CObject* node1, CObject* node2 ) // List item // List item
Parameters node1 [in] List item node2 [in] List item Return Value true if successful, false - if you can not change the elements in some places. Example:
//--- example for CList::Exchange(CObject*,CObject*) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- exchange list.Exchange(list.GetFirstNode(),list.GetLastNode()); //--- use list //--- . . . //--- delete list delete list; }
1134
Standard Library
CompareList
Compares the list with another list.
bool CompareList( CList* list ) // With whom we compare
Parameters list [in] A pointer to an instance of class CList-source elements for comparison. Return Value true if the lists are equal, false - if not. Example:
//--- example for CList::CompareList(const CList*) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- create source list CList *src=new CList; if(src==NULL) { printf("Object create error"); delete list; return; } //--- fill source list //--- . . . //--- compare with another list bool result=list.CompareList(src); //--- delete lists delete src; delete list; }
1135
Standard Library
Search
Searches for an element equal to the model in the sorted list.
CObject* Search( CObject* element ) // Sample
Parameters element [in] Sample cell to search for in the list. Return Value Pointer to the found item if successful, NULL - if the item was not found. Example:
//--- example for CList::Search(CObject*) #include <Arrays\List.mqh> //--void OnStart() { CList *list=new CList; //--if(list==NULL) { printf("Object create error"); return; } //--- add lists elements //--- . . . //--- sort list list.Sort(0); //--- create sample CObject *sample=new CObject; if(sample==NULL) { printf("Sample create error"); delete list; return; } //--- set sample attributes //--- . . . //--- search element if(list.Search(sample)!=NULL) printf("Element found"); else //--- delete list delete list; } printf("Element not found");
1136
Standard Library
Save
Saves data in the file list.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the previously opened using the function FileOpen (...) file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CList::Save(int) #include <Arrays\List.mqh> //--void OnStart() { int //--if(list!=NULL) { printf("Object create error"); return; } //--- add lists elements //--- . . . //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!list.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); delete list; FileClose(file_handle); //--return; } FileClose(file_handle); } //--- delete list delete list; file_handle; CList *list=new CList;
1137
Standard Library
}
1138
Standard Library
Load
Loads list data from a file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] Handle of the previously open, with the function FileOpen (...), binary Return Value true - if successfully completed, false - if an error. Note When reading from the file list items to create each element of the method is called CList:: CreateElement (). Example:
//--- example for CLoad::Load(int) #include <Arrays\List.mqh> //--void OnStart() { int //--if(list!=NULL) { printf("Object create error"); return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!list.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); delete list; FileClose(file_handle); //--return; } FileClose(file_handle); } file_handle; CList *list=new CList;
1139
Standard Library
//--- use list elements //--- . . . //--- delete list delete list; }
1140
Standard Library
Type
Gets the type identifier list.
virtual int Type()
1141
Standard Library
CTreeNode
Class CTreeNode is a class of node of the binary tree CTree.
Description
Class CTreeNode provides the ability to work with nodes of the binary tree CTree. Options of navigation through the tree is implemented in the class. Besides that methods of work with a file are implemented.
Declaration
class CTreeNode : public CObject
Title
#include <Arrays\TreeNode.mqh>
Class Methods
Attributes Owner Left Right Balance BalanceL Gets/sets the pointer of the owner node Gets/sets the pointer of the left node Gets/sets the pointer of the right node Gets the node balance Gets the balance of the left sub-branch of the node Gets the balance of the right sub-branch of the node
BalanceR
Creation of a new element CreateSample Comparison RefreshBalance Search GetNext Input/Output SaveNode LoadNode virtual Type Derived classes: Saves the node data to a file Downloads the node data from a file Gets the identifier of the node type Gets the pointer of the next node Recalculates the node balance Creates a new node instance
1142
Standard Library CTree Trees of CTreeNode class descendants get practical application. A descendant of class CTreeNode must have predefined methods: CreateSample that creates a new instance of the descendant class of CTreeNode, Compare that compares values of key fields of the descendant class of CTreeNode, Type (if it's necessary to identify a node), SaveNode and LoadNode (if it's necessary to work with a file). Let's consider and example of a CTree descendant class.
//+------------------------------------------------------------------+ //| //| //| MyTreeNode.mq5 | Copyright 2010, MetaQuotes Software Corp. | http://www.metaquotes.net/ |
//+------------------------------------------------------------------+ #property copyright "2010, MetaQuotes Software Corp." #property link //--#include <Arrays\TreeNode.mqh> //+------------------------------------------------------------------+ //| Describe classderived from CTreeNode. //| Class CMyTreeNode. //| Purpose: Class of element of a binary tree. //| Descendant of class CTreeNode. | | | | //+------------------------------------------------------------------+ "http://www.mql5.com"
//+------------------------------------------------------------------+ class CMyTreeNode : public CTreeNode { protected: //--- user's data long double string datetime public: CMyTreeNode(); //--- methods of accessing these user's data long void double void string void datetime void virtual bool virtual bool GetLong(void) SetLong(long value) GetDouble(void) SetDouble(double value) GetString(void) SetString(string value) GetDateTime(void) SetDateTime(datetime value) Save(int file_handle); Load(int file_handle); { return(m_long); } { m_long=value; } } } } { return(m_double); } { m_double=value; { m_string=value; { return(m_string); } { return(m_datetime); } { m_datetime=value; m_long; m_double; m_string; m_datetime; // key field of type long // custom variable of type double // custom variable of type string // custom variable of type datetime
1143
Standard Library
protected: virtual int Compare(const CObject *node,int mode); //--- methods of creating class instances virtual CTreeNode* CreateSample(); }; //+------------------------------------------------------------------+ //| CMyTreeNode class constructor. //| INPUT: none. //| OUTPUT: none. //| REMARK: none. void CMyTreeNode::CMyTreeNode() { //--- initialization of user's data m_long m_double m_string m_datetime } //+------------------------------------------------------------------+ //| Comparison with another three node by the specified algorithm. //| INPUT: //| node - array element to compare, mode - identifier of comparison algorithm. | | | | | =0; =0.0; =""; =0; | | | |
//+------------------------------------------------------------------+
//| OUTPUT: result of comparison (>0,0,<0). //| REMARK: none. int CMyTreeNode::Compare(const CObject *node,int mode) {
//+------------------------------------------------------------------+
//--- parameter mode is ignored, because tree construction algorithm is the only one int res=0; //--- explicit type casting CMyTreeNode *n=node; res=(int)(m_long-n.m_long); //--return(res); } //+------------------------------------------------------------------+ //| Creation of a new class instance. //| INPUT: none. //| OUTPUT: pointer to a new instance of class CMyTreeNode. //| REMARK: none. CTreeNode* CMyTreeNode::CreateSample() { CMyTreeNode *result=new CMyTreeNode; //--return(result); } | | | |
//+------------------------------------------------------------------+
1144
Standard Library
//+------------------------------------------------------------------+ //| Write tree node data to a file. //| INPUT: file_handle -handle of a file pre-opened for writing. //| OUTPUT: true if OK, otherwise false. //| REMARK: none. bool CMyTreeNode::Save(int file_handle) { uint i=0,len; //--- checks if(file_handle<0) return(false); //--- writing user data //--- writing custom variable of type long if(FileWriteLong(file_handle,m_long)!=sizeof(long)) //--- writing custom variable of type double if(FileWriteDouble(file_handle,m_double)!=sizeof(double)) //--- writing custom variable of type string len=StringLen(m_string); //--- write string length if(FileWriteInteger(file_handle,len,INT_VALUE)!=INT_VALUE) //--- write the string if(len!=0 && FileWriteString(file_handle,m_string,len)!=len) return(false); //--- writing custom variable of type datetime if(FileWriteLong(file_handle,m_datetime)!=sizeof(long)) //--return(true); } //+------------------------------------------------------------------+ //| Read tree node data from a file. //| INPUT: file_handle -handle of a file pre-opened for reading. //| OUTPUT: true if OK, otherwise false. //| REMARK: none. bool CMyTreeNode::Load(int file_handle) { uint i=0,len; //--- checks if(file_handle<0) return(false); //--- reading if(FileIsEnding(file_handle)) return(false); //--- reading custom variable of type char //--- reading custom variable of type long m_long=FileReadLong(file_handle); //--- reading custom variable of type double m_double=FileReadDouble(file_handle); //--- reading custom variable of type string //--- read the string length len=FileReadInteger(file_handle,INT_VALUE); | | | | return(false); return(false); return(false); return(false); | | | |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
1145
Standard Library
//--- read the string if(len!=0) m_string=FileReadString(file_handle,len); else m_string=""; //--- reading custom variable of type datetime m_datetime=FileReadLong(file_handle); //--return(true); }
1146
Standard Library
Owner
Gets the pointer of the owner node.
CTreeNode* Owner()
Owner
Sets the pointer of the owner node.
void Owner( CTreeNode* node ) // node
Parameters node [in] New value of the pointer of the owner node. Return Value None.
1147
Standard Library
Left
Gets the pointer of the left node.
CTreeNode* Left()
Left
Sets the pointer of the left node.
void Left( CTreeNode* node ) // node
Parameters node [in] New value of the pointer of the left node. Return Value None.
1148
Standard Library
Right
Gets the pointer of the right node.
CTreeNode* Right()
Right
Sets the pointer of the right node.
void Right( CTreeNode* node ) // node
Parameters node [in] New value of the pointer of the right node. Return Value None.
1149
Standard Library
Balance
Gets the node balance.
int Balance() const
1150
Standard Library
BalanceL
Gets the balance of the left sub-branch of the node.
int BalanceL() const
1151
Standard Library
BalanceR
Gets the balance of the right sub-branch of the node.
int BalanceR() const
1152
Standard Library
CreateSample
Creates a new node sample.
virtual CTreeNode* CreateSample()
1153
Standard Library
RefreshBalance
Recalculates the node balance.
int RefreshBalance()
1154
Standard Library
GetNext
Gets the pointer of the next node.
CTreeNode* GetNext( CTreeNode* node ) // node
Parameters node [in] Node of the search start. Return Value Pointer of the next node.
1155
Standard Library
SaveNode
Writes node data to a file.
bool SaveNode( int file_handle ) // handle
Parameters file_handle [in] Handle of a binary file that was earlier opened for writing. Return Value true in case of success, otherwise false.
1156
Standard Library
LoadNode
Reads node data from a file.
bool LoadNode( int file_handle, // handle // node CTreeNode* main )
Parameters file_handle [in] Handle of a binary file that was earlier opened for reading. main [in] Node for data. Return Value true in case of success, otherwise false.
1157
Standard Library
Type
Gets the identifier of the node type.
virtual int Type() const
1158
Standard Library
CTree
Class CTree is a class of the binary tree of samples of class CTreeNode and its descendants.
Description
Class CTree privides the possibility to work with a binary tree of CTreeNode class samples and its descendants. Options of adding/inserting/deleting of three elements and search in a tree are implemented in the class. Besides that, methods of work with a file are implemented. Note that mechanism of dynamic memory management is not implemented in class CTree (as distinct from classes CList and CArrayObj). All tree nodes are deleted with memory release.
Declaration
class CTree : public CTreeNode
Title
#include <Arrays\Tree.mqh>
Class Methods
Attributes Root Creation of a new element CreateElement Filling Insert Deletion Detach Delete Clear Search Find Input/output virtual Save virtual Load virtual Type Saves all the tree data to a file Downloads tree data from a file Gets identifier of the tree type Searches for a node in a tree by sample Detaches a specified node from a tree Deletes a specified node from a tree Deletes all nodes of a tree Adds a node to a tree Creates a new node instance Gets a root node of the tree
Trees of CTreeNode class descendants descendants of class CTree get practical application.
1159
Standard Library Descendant of class CTree must have a predefined method CreateElement that creates a new sample of descendant class CTreeNode. Let's consider an example of descendant class CTree.
//+------------------------------------------------------------------+ //| //| //| MyTree.mq5 | Copyright 2010, MetaQuotes Software Corp. | http://www.metaquotes.net/ |
//+------------------------------------------------------------------+ #property copyright "2010, MetaQuotes Software Corp." #property link //--#include <Arrays\Tree.mqh> #include "MyTreeNode.mqh" //--input int extCountedNodes = 100; //+------------------------------------------------------------------+ //| Describe class CMyTree derived from CTree. //| Class CMyTree. //| Purpose: Construction and navigation of a binary search tree. class CMyTree : public CTree { public: //--- methods of search on the tree by custom data CMyTreeNode* FindByLong(long find_long); //--- method of creation of the tree element virtual CTreeNode *CreateElement(); }; //--CMyTree MyTree; //+------------------------------------------------------------------+ //| Creation of a new tree node. //| INPUT: none. //| OUTPUT: pointer to the new tree node of OK, or NULL. //| REMARK: none. CTreeNode *CMyTree::CreateElement() { CMyTreeNode *node=new CMyTreeNode; //--return(node); } //+------------------------------------------------------------------+ //| Search of element in a list by value m_long. //| INPUT: find_long - searched value. //| OUTPUT: pointer of a found list element, or NULL. | | | | | | | | | | //+------------------------------------------------------------------+ "http://www.mql5.com"
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
1160
Standard Library
//| REMARK: none. CMyTreeNode* CMyTree::FindByLong(long find_long) { CMyTreeNode *res=NULL; CMyTreeNode *node; //--- create a tree node to pass the search parameter node=new CMyTreeNode; if(node==NULL) return(NULL); node.SetLong(find_long); //--res=Find(node); delete node; //--return(res); } //+------------------------------------------------------------------+ //| script "testing of class CMyTree" //--//--int OnStart() export { int uint int //--printf("Start test %s.",__FILE__); //--- Fill out MyTree with samples of class MyTreeNode in the amount of extCountedNodes. beg_time=GetTickCount(); for(i=0;i<extCountedNodes;i++) { node=MyTree.CreateElement(); if(node==NULL) { //--- emergency exit printf("%s (%4d): create error",__FILE__,__LINE__); return(__LINE__); } NodeSetData(node,i); node.SetLong(i); MyTree.Insert(node); } end_time=GetTickCount(); printf("Filling time of MyTree is %d ms.",end_time-beg_time); //--- Create a temporary tree TmpMyTree. i; pos; beg_time,end_time; array for string initialization | //+------------------------------------------------------------------+ string str_array[11]={"p","oo","iii","uuuu","yyyyy","ttttt","rrrr","eee","ww","q","999"}; |
//+------------------------------------------------------------------+
1161
Standard Library
CMyTree TmpMyTree; //--- Detach 50% of tree elements (all even) //--- and add them to the temporary tree TmpMyTree. beg_time=GetTickCount(); for(i=0;i<extCountedNodes;i+=2) { node=MyTree.FindByLong(i); if(node!=NULL) if(MyTree.Detach(node)) TmpMyTree.Insert(node); } end_time=GetTickCount(); //--- Return the detached node=TmpMyTree.Root(); while(node!=NULL) { if(TmpMyTree.Detach(node)) MyTree.Insert(node); node=TmpMyTree.Root(); } //--- Check work of method Save(int file_handle); int file_handle; file_handle=FileOpen("MyTree.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!MyTree.Save(file_handle)) { //--- error writing to a file //--- emergency exit printf("%s: Error %d in %d!",__FILE__,GetLastError(),__LINE__); //--- close file before leaving!!! FileClose(file_handle); return(__LINE__); } FileClose(file_handle); } //--- Check work of method Load(int file_handle); file_handle=FileOpen("MyTree.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!TmpMyTree.Load(file_handle)) { //--- error reading from file //--- emergency exit printf("%s: Error %d in %d!",__FILE__,GetLastError(),__LINE__); //--- close file before leaving!!! FileClose(file_handle); return(__LINE__); }
1162
Standard Library
FileClose(file_handle); } //--MyTree.Clear(); TmpMyTree.Clear(); //--printf("End test %s. OK!",__FILE__); //--return(0); } //+------------------------------------------------------------------+ //| Function of output of node contents to journal void NodeToLog(CMyTreeNode *node) { printf(" %I64d,%f,'%s','%s'", node.GetLong(),node.GetDouble(), node.GetString(),TimeToString(node.GetDateTime())); } //+------------------------------------------------------------------+ //| Function of "filling" of node with random values void NodeSetData(CMyTreeNode *node,int mode) { if(mode%2==0) { node.SetLong(mode*MathRand()); node.SetDouble(MathPow(2.02,mode)*MathRand()); } else { node.SetLong(mode*(long)(-1)*MathRand()); node.SetDouble(-MathPow(2.02,mode)*MathRand()); } node.SetString(str_array[mode%10]); node.SetDateTime(10000*mode); } | //+------------------------------------------------------------------+ | //+------------------------------------------------------------------+
1163
Standard Library
Root
Gets the root node of the tree.
CTreeNode* Root() const
1164
Standard Library
CreateElement
Creates a new instance of the node.
virtual CTreeNode* CreateElement()
1165
Standard Library
Insert
Adds a node to a tree.
CTreeNode* Insert( CTreeNode* new_node ) // node
Parameters new_node [in] pointer of a node to insert to a tree. Return Value Pointer of the owner node or NULL.
1166
Standard Library
Detach
Detaches a specified node from a tree.
bool Detach( CTreeNode* node ) // node
Parameters node [in] Node pointer to detach. Return Value true in case of success, otherwise false. Note After detachment the node pointer is not released. The tree is balanced.
1167
Standard Library
Delete
Deletes a specified node from a tree.
bool Delete( CTreeNode* node ) // node
Parameters node [in] Node pointer to delete. Return Value true in case of success, otherwise false. Note After deletion a node pointer is released. The tree is balanced.
1168
Standard Library
Clear
Deletes all nodes of a tree.
void Clear()
Return Value None. Note After deletion node pointers are released.
1169
Standard Library
Find
Searches for a node in a tree by sample.
CTreeNode* Find( CTreeNode* node ) // node
Parameters node [in] Node that contains data-search sample. Return Value Pointer of the found node or NULL.
1170
Standard Library
Save
Writes tree data to a file.
virtual bool Save( int file_handle ) // handle
Parameters file_handle [in] Handle of a binary file that was earlier opened for writing. Return Value true in case of success, otherwise false.
1171
Standard Library
Load
Reads tree data to a file.
virtual bool Load( int file_handle ) // handle
Parameters file_handle [in] Handle of a binary file that was earlier opened for reading. Return Value true in case of success, otherwise false.
1172
Standard Library
Type
Gets identifier of the tree type.
virtual int Type() const
1173
Standard Library
Graphic Objects
This section contains the technical details of working with classes of graphical objects and a description of the relevant components of the MQL5 Standard Library . The use of classes of graphical objects, will save time when creating custom programs (scripts, expert). MQL5 Standard Library (in terms of graphical objects) is placed in the working directory of the terminal in the Include\ChartObjects folder. Class/Group Base class for graphical object CChartObject Lines Channels Gann Tools Fibonacci Tools Elliott Tools Shapes Arrows Controls Description Base class of a graphic object Group classes "Lines" Group classes "Channels" Group classes "Gann" Group classes "Fibonacci" Group classes "Elliott" Group classes "Shapes" Group classes "Arrows" Group classes "Controls"
1174
Standard Library
CChartObject
CChartObject is a base class of graphic objects of chart type of the Standard MQL5 library.
Description
Class CChartObject provides the simplified access for all of its descendants to MQL5 API functions.
Declaration
class CChartObject : public CObject
Title
#include <ChartObjects\ChartObject.mqh>
Class Methods
Attributes ChartId Window Gets the ID chart, who owns a graphic Gets the number of windows in which the chart is a graphic Gets/sets the name of a graphic object Gets the number of anchor points
Name NumPoints Assign Attach SetPoint Delete Delete Detach Shift ShiftObject ShiftPoint Object properties Time
The relative movement of the object The relative movement of the object point
Gets/sets the time coordinates of the object point Gets/sets the price coordinate of a point object Gets/sets the color of the object Gets/sets the line style object Gets/sets the width of the line object
1175
Standard Library
Gets/sets the flag drawing object background Gets/sets the flag sit on an object Gets/sets the flag selectable object Gets/sets the text of the object Gets/sets the mask of flags visibility of the object Gets the time object creation
CreateTime Levels properties of the object LevelsCount LevelColor LevelStyle LevelWidth LevelValue LevelDescription Access to MQL5 API functions GetInteger SetInteger GetDouble SetDouble GetString SetString Input/Output virtual Save virtual Load virtual Type Derived classes: CChartObjectArrow CChartObjectBitmap CChartObjectBmpLabel CChartObjectCycles CChartObjectElliottWave3 CChartObjectEllipse CChartObjectFiboArc CChartObjectFiboFan
Gets/sets the number of levels of object Gets/sets the color of the line level Gets/sets the line style level Gets/sets the width of the line level Gets/sets the level Gets/sets the text level
Gets the value of the object properties Sets the object properties Gets the value of the object properties Sets the object properties Gets the value of the object properties Sets the object properties
Virtual method entry in the file Virtual method of reading from a file Virtual method of identification
1176
Standard Library CChartObjectFiboTimes CChartObjectHLine CChartObjectRectangle CChartObjectSubChart CChartObjectText CChartObjectTrend CChartObjectTriangle CChartObjectVLine
1177
Standard Library
ChartId
Gets the ID chart, who owns a graphic object.
long ChartId() const
Return Value Id chart on which the graphic object. If object not found, it returns -1. Example:
//--- example for CChartObject::ChartId #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get chart idintifier of chart object long chatr_id=object.ChartId(); }
1178
Standard Library
Window
Gets the number of windows in which the chart is a graphic object.
int Window() const
Return Value Number of windows in which the chart is a graphic object (0 - main window). If object not found, it returns -1. Example:
//--- example for CChartObject::Window #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get window of chart object int window=object.Window(); }
1179
Standard Library
Return Value Name of the graphic object tied to an instance of the class. If object not found, returns NULL.
Parameters name [in] The new name of the graphic object. Return Value true if successful, false - if you can not change the name. Example:
//--- example for CChartObject::Name #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get name of chart object string object_name=object.Name(); if(object_name!="MyChartObject") { //--- set name of chart object object.Name("MyChartObject"); } }
1180
Standard Library
NumPoints
Gets the number of anchor points of a graphic object.
int NumPoints() const
Return Value Number of points linking a graphic object that is bound to an instance of the class. If not bound object, it returns 0. Example:
//--- example for CChartObject::NumPoints #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get points count of chart object int points=object.NumPoints(); }
1181
Standard Library
Attach
Binds a graphical object to an instance of the class.
bool Attach( long chart_id, // Chart ID // Name of the object // Chart window // Number of points string name, int int ) window, points
Parameters chart_id [out] Chart identifier. name [in] Name of the graphic object. window [in] Chart window number (0 main window). points [in] Number of points anchor graphic object. Return Value true - if successful, false - if you can not bind object. Example:
//--- example for CChartObject::Attach #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- attach chart object if(!object.Attach(ChartID(),"MyObject",0,2)) { printf("Object attach error"); return; } }
1182
Standard Library
SetPoint
Sets the new coordinates of this anchor point graphic object.
bool SetPoint( int point, // Point number // Time coordinate // Price coordinate datetime new_time, double ) new_price
Parameters point [in] Number anchor point graphic object. new_time [in] The new value of the coordinates of this point of time bindings. new_price [in] New value coordinates of the price specified anchor point. Return Value true - if successful, false - if you can not change the coordinates of the point. Example:
//--- example for CChartObject::SetPoint #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; double //--if(object.NumPoints()>0) { //--- set point of chart object object.SetPoint(0,CurrTime(),price); } } price;
1183
Standard Library
Delete
Removes a graphical object with the attached chart.
bool Delete()
Return Value true - if successful, false - if you can not remove the object. Example:
//--- example for CChartObject::Delete #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- detach chart object if(!object.Delete()) { printf("Object delete error"); return; } }
1184
Standard Library
Detach
Untie graphic object.
bool Detach()
Return Value true - if successful, false - if you can not decouple the object. Example:
//--- example for CChartObject::Detach #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- detach chart object if(!object.Detach()) { printf("Object detach error"); return; } }
1185
Standard Library
ShiftObject
Moves a graphic object.
bool ShiftObject( datetime d_time, double ) d_price // Increment of time coordinate // Increment of price coordinate
Parameters d_time [in] Increment the coordinates of all points of time bindings d_price [in] Increment the coordinates of the prices of all waypoints. Return Value true - if successful, false - if you can not move the object. Example:
//--- example for CChartObject::ShiftObject #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; datetime double d_time; d_price;
1186
Standard Library
ShiftPoint
Moves a specified point anchor graphic.
bool ShiftPoint( int point, // Point number // Increment of time coordinate // Increment of price coordinate datetime d_time, double ) d_price
Parameters point [in] Number anchor point graphic object. d_time [in] Increment the coordinates of time specified anchor point. d_price [in] Increment the coordinates of the price specified anchor point. Return Value true - if successful, false - if you can not move the point. Example:
//--- example for CChartObject::ShiftPoint #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; datetime double //--if(object.NumPoints()>0) { //--- shift point of chart object object.ShiftPoint(0,d_time,d_price); } } d_time; d_price;
1187
Standard Library
Parameters point [in] Number anchor point graphic object. Return Value Coordinates of time specified anchor point graphic object that is bound to an instance of the class. If not bound object or the object is not this point, it returns 0.
Parameters point [in] Number anchor point graphic object. new_time [in] The new value of the coordinates of this point of time anchor graphic object. Return Value true - if successful, false - if you can not change the coordinate of time. Example:
//--- example for CChartObject::Time #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.NumPoints();i++) { //--- get time of point chart object datetime point_time=object.Time(i); if(point_time==0)
1188
Standard Library
{ //--- set time of point chart object object.Time(i,TimeCurrent()); } } }
1189
Standard Library
Parameters point [in] Number anchor point graphic object. Return Value Coordinate prices specified anchor point graphic object that is bound to an instance of the class. If not bound object or the object is not this point, it returns EMPTY_VALUE.
Parameters point [in] Number anchor point graphic object. new_price [in] News value coordinates of the price specified anchor point graphic object. Return Value true - if successful, false - if you can not change the coordinate prices. Example:
//--- example for CChartObject::Price #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; double //--for(int i=0;i<object.NumPoints();i++) { //--- get price of point chart object double point_price=object.Price(i); price;
1190
Standard Library
if(point_price!=price) { //--- set price of point chart object object.Price(i,price); } } }
1191
Standard Library
Return Value Color line of graphic object, assigned to the class instance. If there is no object assigned, it returns CLR_NONE.
Parameters new_color [in] New value line color graphic object. Return Value true - if successful, false - if you can not change the color. Example:
//--- example for CChartObject::Color #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get color of chart object color object_color=object.Color(); if(object_color!=Red) { //--- set color of chart object object.Color(Red); } }
1192
Standard Library
Return Value Style line of the graphic object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters new_style [in] New value-style line drawing object. Return Value true - if successful, false - if you can not change the style. Example:
//--- example for CChartObject::Style #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get style of chart object ENUM_LINE_STYLE style=object.Style(); if(style!=STYLE_SOLID) { //--- set style of chart object object.Style(STYLE_SOLID); } }
1193
Standard Library
Return Value The thickness of the line graphic object that is bound to an instance of the class. If not bound object, it returns -1.
Parameters new_width [in] The new value of the thickness of the line graphic object. Return Value true - if successful, false - if you can not change the thickness. Example:
//--- example for CChartObject::Width #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get width of chart object int width=object.Width(); if(width!=1) { //--- set width of chart object object.Width(1); } }
1194
Standard Library
Return Value Flag of drawing in the background, a graphic object that is bound to an instance of the class. If not bound object returns false.
Parameters background [in] New value of the flag drawing a graphic object in the background. Return Value true - if successful, false - if you can not change the flag. Example:
//--- example for CChartObject::Background #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get background flag of chart object bool background_flag=object.Background(); if(!background_flag) { //--- set background flag of chart object object.Background(true); } }
1195
Standard Library
Return Value Flag "slate", a graphic object that is bound to an instance of the class. If not bound object returns false.
Parameters selected [in] New value of the flag "reprimand" graphic object. Return Value true - if successful, false - if you can not change the flag. Example:
//--- example for CChartObject::Selected #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get selected flag of chart object bool selected_flag=object.Selected(); if(selected_flag) { //--- set selected flag of chart object object.Selected(false); } }
1196
Standard Library
Return Value Flag "selectable", a graphic object that is bound to an instance of the class. If not bound object returns false.
Parameters selectable [in] New value of the flag "selectable" graphic object. Return Value true - if successful, false - if you can not change the flag. Example:
//--- example for CChartObject::Selectable #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get selectable flag of chart object bool selectable_flag=object.Selectable(); if(selectable_flag) { //--- set selectable flag of chart object object.Selectable(false); } }
1197
Standard Library
Return Value Description (text) graphic object that is bound to an instance of the class. If no bound object, it returns NULL.
Parameters text [in] New value descriptions (text) graphic object. Return Value true - if successful, false - if you can not change the description (text). Example:
//--- example for CChartObject::Description #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get description of chart object string description=object.Description(); if(description=="") { //--- set description of chart object object.Description("MyObject"); } }
1198
Standard Library
Return Value Flags visibility graphic object that is bound to an instance of the class. If not bound object, it returns 0.
Parameters new_timeframes [in] New flags visibility graphic object. Return Value true - if successful, false - if you can not change the flags of visibility. Example:
//--- example for CChartObject::Timeframes #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get timeframes of chart object int timeframes=object.Timeframes(); if(!(timeframes&OBJ_PERIOD_H1)) { //--- set timeframes of chart object object.Timeframes(timeframes|OBJ_PERIOD_H1); } }
1199
Standard Library
CreateTime
Gets the time to create graphical object.
datetime CreateTime() const
Return Value Time to create graphical object that is bound to an instance of the class. If not bound object, it returns 0. Example:
//--- example for CChartObject::CreateTime #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get create time of chart object datetime create_time=object.CreateTime(); }
1200
Standard Library
Return Value Number of levels of graphical object that is bound to an instance of the class. If not bound object, it returns 0.
Parameters levels [in] the number of new levels of graphic object. Return Value true - if successful, false - if you can not change the number of levels. Example:
//--- example for CChartObject::LevelsCount #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- get levels count of chart object int levels_count=object.LevelsCount(); //--- set levels count of chart object object.LevelsCount(levels_count+1); }
1201
Standard Library
Parameters level [in] Number of levels of graphical object. Return Value Color Line level specified graphic object that is bound to an instance of the class. If not bound object or the object is no specified level, it returns CLR_NONE.
Parameters level [in] Number of levels of graphical object. new_color [in] New value line color of the level of graphic object. Return Value true - if successful, false - if you can not change the color. Example:
//--- example for CChartObject::LevelColor #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get level color of chart object color level_color=object.LevelColor(i); if(level_color!=Red)
1202
Standard Library
{ //--- set level color of chart object object.LevelColor(i,Red); } } }
1203
Standard Library
Parameters level [in] Number of levels of graphical object. Return Value Line style specified level graphical object that is bound to an instance of the class. If not bound object or the object is no specified level of returns WRONG_VALUE.
Parameters level [in] Number of levels of graphical object. style [in] New value-style line level specified graphical object. Return Value true - if successful, false - if you can not change the style. Example:
//--- example for CChartObject::LevelStyle #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get level style of chart object ENUM_LINE_STYLE level_style=object.LevelStyle(i); if(level_style!=STYLE_SOLID)
1204
Standard Library
{ //--- set level style of chart object object.LevelStyle(i,STYLE_SOLID); } } }
1205
Standard Library
Parameters level [in] Number of levels of graphical object. Return Value The thickness of the lines of the level of graphical object that is bound to an instance of the class. If not bound object or the object is no specified level, it returns -1.
Parameters level [in] Number of levels of graphical object. new_width [in] New value line thickness specified level graphical object. Return Value position of the found element, if successful, -1 - if the item was not found. Example:
//--- example for CChartObject::LevelWidth #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get level width of chart object int level_width=object.LevelWidth(i); if(level_width!=1)
1206
Standard Library
{ //--- set level width of chart object object.LevelWidth(i,1); } } }
1207
Standard Library
Parameters level [in] Number of levels of graphical object. Return Value The value of this level of graphical object that is bound to an instance of the class. If not bound object or the object is no level specified, returns EMPTY_VALUE.
Parameters level [in] Number of levels of graphical object. new_value [in] New value of the level of graphic object. Return Value true - if successful, false - if you can not change the level. Example:
//--- example for CChartObject::LevelValue #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get level value of chart object double level_value=object.LevelValue(i); if(level_value!=0.1*i)
1208
Standard Library
{ //--- set level value of chart object object.LevelValue(i,0.1*i); } } }
1209
Standard Library
Parameters level [in] Number of levels of graphical object. Return Value Description (text) of the level of graphical object that is bound to an instance of the class. If not bound object or the object is no specified level, returns NULL.
Parameters level [in] Number of level of graphical object. text [in] New value of description (text) of the level of graphic object. Return Value true if successful, false - if you can not change the description (text). Example:
//--- example for CChartObject::LevelDescription #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get level description of chart object string level_description=object.LevelDescription(i); if(level_description=="")
1210
Standard Library
{ //--- set level description of chart object object.LevelDescription(i,"Level_"+IntegerToString(i)); } } }
1211
Standard Library
GetInteger
Provides simplified access to the functions of API MQL5 ObjectGetInteger() for integer-value properties (of type bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to an instance of the class graphic.There are two versions of a function call: Getting a property value without checking the correctness
long GetInteger( ENUM_OBJECT_PROPERTY_INTEGER prop_id, int ) const modifier=-1 // Identifier of integer-property // Modifier
Parameters prop_id [in] ID of double-graphic properties. modifier=-1 [in] Modifier (index) double-features. Return Value If successfull, it returns the value of integer-type property, if error, it returns 0. Getting a property value in verifying the correctness of such treatment
bool GetInteger( ENUM_OBJECT_PROPERTY_INTEGER prop_id, int long& ) const modifier, value // Identifier of integer-property // Modifier // Link to variable
Parameters prop_id [in] ID integer-graphic properties of the object. modifier [in] Modifier (index) integer-property. value [out] Reference to a variable to accommodate the integer-value properties. Return Value true - if successful, false - if you can not get integer-property. Example:
//--- example for CChartObject::GetInteger #include <ChartObjects\ChartObject.mqh> //--void OnStart()
1212
Standard Library
{ CChartObject object; //--- get color of chart object by easy method printf("Objects color is %s",ColorToString(object.GetInteger(OBJPROP_COLOR),true)); //--- get color of chart object by classic method long color_value; if(!object.GetInteger(OBJPROP_COLOR,0,color_value)) { printf("Get integer property error %d",GetLastError()); return; } else printf("Objects color is %s",color_value); for(int i=0;i<object.LevelsCount();i++) { //--- get levels width by easy method printf("Level %d width is %d",i,object.GetInteger(OBJPROP_LEVELWIDTH,i)); //--- get levels width by classic method long width_value; if(!object.GetInteger(OBJPROP_LEVELWIDTH,i,width_value)) { printf("Get integer property error %d",GetLastError()); return; } else printf("Level %d width is %d",i,width_value); } }
1213
Standard Library
SetInteger
Provides simplified access to the functions of API MQL5 ObjectSetInteger() to change the integerproperties (with types bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to an instance of the class graphic.There are two versions of a function call: Setting a property value that does not require a modifier
bool SetInteger( ENUM_OBJECT_PROPERTY_INTEGER prop_id, long ) value // Identifier of integer-property // Value
Parameters prop_id [in] ID integer-graphic properties of the object. value [in] new mutable integer-value properties. Setting a property value indicating the modifier
bool SetInteger( ENUM_OBJECT_PROPERTY_INTEGER prop_id, int long ) modifier, value // Identifier of integer-property // Modifier // Value
Parameters prop_id [in] ID integer-graphic properties of the object. modifier [in] Modifier (index) integer-property. value [in] new mutable integer-value properties. Return Value true - if successful, false - if you can not change the integer-property. Example:
//--- example for CChartObject::SetInteger #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- set new color of chart object
1214
Standard Library
if(!object.SetInteger(OBJPROP_COLOR,Red)) { printf("Set integer property error %d",GetLastError()); return; } for(int i=0;i<object.LevelsCount();i++) { //--- set levels width if(!object.SetInteger(OBJPROP_LEVELWIDTH,i,i)) { printf("Set integer property error %d",GetLastError()); return; } } }
1215
Standard Library
GetDouble
Provides simplified access to the functions of API MQL5 ObjectGetDouble() to get the values doubleproperties (having type float and double) of the graphic object, assigned to the class instance. There are two versions of a function call: Getting a property value without checking the correctness
double GetDouble( ENUM_OBJECT_PROPERTY_DOUBLE prop_id, int ) const modifier=-1 // Identifier of double-property // Modifier
Parameters prop_id [in] ID of double-graphic properties. modifier=-1 [in] Modifier (index) double-features. Return Value If successful, it returns the value of property of double type, if error, it returns EMPTY_VALUE. Getting a property value in verifying the correctness of such treatment
bool GetDouble( ENUM_OBJECT_PROPERTY_DOUBLE prop_id, int double& ) const modifier, value // Identifier of double-property // Modifier // Link to variable
Parameters prop_id [in] ID of double-graphic properties. modifier [in] Modifier (index) double-features. value [out] Reference to a variable to accommodate the double-value properties. Return Value true - if successful, false - if you can not get a double-feature. Example:
//--- example for CChartObject::GetDouble #include <ChartObjects\ChartObject.mqh> //--void OnStart()
1216
Standard Library
{ CChartObject object; //--for(int i=0;i<object.LevelsCount();i++) { //--- get levels value by easy method printf("Level %d value=%f",i,object.GetDouble(OBJPROP_LEVELVALUE,i)); //--- get levels value by classic method double value; if(!object.SetDouble(OBJPROP_LEVELVALUE,i,value)) { printf("Get double property error %d",GetLastError()); return; } else printf("Level %d value=%f",i,value); } }
1217
Standard Library
SetDouble
Provides simplified access to the functions of API MQL5 ObjectSetDouble() to change the doubleproperties (having type float and double) bound to an instance of the class graphic object. There are two versions of a function call: Setting a property value that does not require a modifier
bool SetDouble( ENUM_OBJECT_PROPERTY_DOUBLE prop_id, double ) value // Identifier of double-property // Value
Parameters prop_id [in] ID of double-graphic properties. value [in] New value mutable double-features. Setting a property value indicating the modifier
bool SetDouble( ENUM_OBJECT_PROPERTY_DOUBLE prop_id, int double ) modifier, value // Identifier of double-property // Modifier // Value
Parameters prop_id [in] ID of double-graphic properties. modifier [in] Modifier (index) of double-property. value [in] New value mutable double-property. Return Value true - if successful, false - if you can not change the double-feature. Example:
//--- example for CChartObject::SetDouble #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //---
1218
Standard Library
for(int i=0;i<object.LevelsCount();i++) { //--- set level value of chart object if(!object.SetDouble(OBJPROP_LEVELVALUE,i,0.1*i)) { printf("Set double property error %d",GetLastError()); return; } } }
1219
Standard Library
GetString
Provides simplified access to the functions of API MQL5 ObjectGetString() for string-value properties, is bound to an instance of the class graphic object. There are two versions of a function call: Getting a property value without checking the correctness
string GetString( ENUM_OBJECT_PROPERTY_STRING prop_id, int ) const modifier=-1 // Identifier of string-property // Modifier
Parameters prop_id [in] Identifier string-properties of graphic object. modifier=-1 [in] Modifier (index) string-properties. Return Value Value of string-property. Getting a property value in verifying the correctness of such treatment
bool GetString( ENUM_OBJECT_PROPERTY_STRING prop_id, int string& ) const modifier, value // Identifier of string-property // Modifier // Link to variable
Parameters prop_id [in] Identifier string-properties of graphic object. modifier [in] Modifier (index) string-properties. value [out] Reference to a variable to accommodate the string-value properties. Return Value true - if successful, false - if you can not get a string-property. Example:
//--- example for CChartObject::GetString #include <ChartObjects\ChartObject.mqh> //--void OnStart() {
1220
Standard Library
CChartObject object; string value; //--- get name of chart object by easy method printf("Object name is '%s'",object.GetString(OBJPROP_NAME)); //--- get name of chart object by classic method if(!object.GetString(OBJPROP_NAME,0,value)) { printf("Get string property error %d",GetLastError()); return; } else printf("Object name is '%s'",value); for(int i=0;i<object.LevelsCount();i++) { //--- get levels description by easy method printf("Level %d description is '%s'",i,object.GetString(OBJPROP_LEVELTEXT,i)); //--- get levels description by classic method if(!object.GetString(OBJPROP_LEVELTEXT,i,value)) { printf("Get string property error %d",GetLastError()); return; } else printf("Level %d description is '%s'",i,value); } }
1221
Standard Library
SetString
Provides simplified access to the functions of API MQL5 ObjectSetString() to change the properties of string-tied to the instance of the class graphic object. There are two versions of a function call: Setting a property value that does not require a modifier
bool SetString( ENUM_OBJECT_PROPERTY_STRING prop_id, string ) value // Identifier of string-property // Value
Parameters prop_id [in] Identifier string-properties of graphic object. value [in] New value mutable string-properties. Setting a property value indicating the modifier
bool SetString( ENUM_OBJECT_PROPERTY_STRING prop_id, int string ) modifier, value // Identifier of string-property // Modifier // Value
Parameters prop_id [in] Identifier string-properties of graphic object. modifier [in] Modifier (index) string-properties. value [in] New value mutable string-properties. Return Value true - if successful, false - if you can not change the string-property. Example:
//--- example for CChartObject::SetString #include <ChartObjects\ChartObject.mqh> //--void OnStart() { CChartObject object; //--- set new name of chart object if(!object.SetString(OBJPROP_NAME,"MyObject"))
1222
Standard Library
{ printf("Set string property error %d",GetLastError()); return; } for(int i=0;i<object.LevelsCount();i++) { //--- set levels description if(!object.SetString(OBJPROP_LEVELTEXT,i,"Level_"+IntegerToString(i))) { printf("Set string property error %d",GetLastError()); return; } } }
1223
Standard Library
Save
Saves parameters of the object in the file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the previously opened using the function FileOpen (...) file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CChartObject::Save #include <ChartObjects\ChartObject.mqh> //--void OnStart() { int file_handle; CChartObject object=new CChartObject; //--- set object parameters //--- . . . //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!object.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); FileClose(file_handle); //--return; } FileClose(file_handle); } }
1224
Standard Library
Load
Loads the parameters of the object from the file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the previously opened using the function FileOpen (...) file. Return Value true - if successfully completed, false - if an error. Example:
//--- example for CChartObject::Load #include <ChartObjects\ChartObject.mqh> //--void OnStart() { int file_handle; CChartObject object; //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!object.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use object //--- . . . }
1225
Standard Library
Type
Gets the type identifier graphic object.
virtual int Type() const
1226
Standard Library
Objects Lines
A group of graphic objects "Lines". This section contains the technical details of working with a group of classes of graphical objects "Lines" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectVLine CChartObjectHLine CChartObjectTrend CChartObjectTrendByAngle CChartObjectCycles See also Object types, Graphic objects Object Graphic object "Vertical Line" Graphic object "Horizontal Line" Graphic object "Trend Line" Graphic object "Trend Line by Angle" Graphic object "Cyclic Lines"
1227
Standard Library
CChartObjectVLine
Class CChartObjectVLine is a class for simplified access to "Vertical Line" graphic object properties.
Description
Class CChartObjectVLine provides access to "Vertical Line" object properties.
Declaration
class CChartObjectVLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Vertical Line"
1228
Standard Library
Create
Creates graphic object "Vertical Line".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // Time coordinate
datetime time )
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time [in] Time coordinate of the anchor point. Returned value true if successful, false if error.
1229
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1230
Standard Library
CChartObjectHLine
Class CChartObjectHLine is a class for simplified access to "Horizontal Line" graphic object properties.
Description
Class CChartObjectHLine provides access to "Horizonal Line" object properties.
Declaration
class CChartObjectHLine : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Horizontal Line"
1231
Standard Library
Create
Creates graphic object "Horizontal Line".
bool Create( long chart_id, // Chart identifier // Object name // Chart window // Price coordinate string name, long window,
double price )
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). price [in] Price coordinate of the anchor point. Returned value true if successful, false if error.
1232
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1233
Standard Library
CChartObjectTrend
Class CChartObjectTrend is a class for simplified access to "Trend Line" graphic object properties.
Description
Class CChartObjectTrend provides access to "Trend Line" object properties.
Declaration
class CChartObjectTrend : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create Create Properties RayLeft RayRight Input/output virtual Save virtual Load virtual Type Derived classes: CChartObjectChannel CChartObjectFibo CChartObjectFiboChannel CChartObjectFiboExpansion CChartObjectGannFan CChartObjectGannGrid CChartObjectPitchfork CChartObjectRegression CChartObjectStdDevChannel CChartObjectTrendByAngle See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Ray Left" Gets/Sets property "Ray Right" Creates graphic object "Trend Line"
1234
Standard Library
Create
Creates graphic object "Trend Line".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // 1st time coordinate // 1st price coordinate // 2nd time coordinate // 2nd price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1235
Standard Library
Returned value The value of "Ray Left" property, assigned to the class instance. If there is no object assigned, it returns false.
Parameters ray [in] New value of the "Ray Left" property. Returned value true if successful, false if flag hasn't changed error.
1236
Standard Library
Returned value The value of "Ray Right" property, assigned to the class instance. If there is no object assigned, it returns false.
Parameters ray [in] New value of the "Ray Right" property. Returned value true if successful, false if flag hasn't changed error.
1237
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...) . Returned value true if successful, false if error.
1238
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1239
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1240
Standard Library
CChartObjectTrendByAngle
Class CChartObjectTrendByAngle is a class for simplified access to "Trend Line by Angle" graphic object properties.
Description
Class CChartObjectTrendByAngle provides access to "Trend Line by Angle" object properties.
Declaration
class CChartObjectTrendByAngle : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create Create Properties Angle Input/output virtual Type Derived classes: CChartObjectGannLine See also Object types, Graphic objects Virtual method of identification Gets/Sets property "Angle" Creates graphic object "Trend Line by Angle"
1241
Standard Library
Create
Creates graphic object "Trend Line by Angle"
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // 1st time coordinate // 1st price coordinate // 2nd time coordinate // 2nd price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1242
Standard Library
Returned value The value of "Angle" property, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters angle [in] New value of the "Angle" property. Returned value true if successful, false if property hasn't changed.
1243
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1244
Standard Library
CChartObjectCycles
Class CChartObjectCycles is a class for simplified access to "Cyclic Lines" graphic object properties.
Description
Class CChartObjectCycles provides access to "Cyclic Lines" object properties.
Declaration
class CChartObjectCycles : public CChartObject
Title
#include <ChartObjects\ChartObjectsLines.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Cycle Lines"
1245
Standard Library
Create
Creates graphic object "Cyclic Lines"
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // 1st time coordinate // 1st price coordinate // 2nd time coordinate // 2nd price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1246
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1247
Standard Library
Objects Channels
A group of graphic objects "Channels". This section contains the technical details of working with a group of classes of graphical objects "Channels" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectChannel CChartObjectRegression CChartObjectStdDevChannel CChartObjectPitchfork See also Object types, Graphic objects Object Graphic object "Equidistant Channel" Graphic object "Linear Regression Channel" Graphic object "Standard deviations Channel" Graphic object "Andrew's Pitchfork"
1248
Standard Library
CChartObjectChannel
The CChartObjectChannel is a class for simplified access to "Equidistant Channel" graphic object properties.
Description
The class CChartObjectChannel provides access to "Equidistant Channel" object properties.
Declaration
class CChartObjectChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Equidistant Channel"
1249
Standard Library
Create
Creates graphic object "Equidistant Channel"
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // Time coordinate
Parameters chart_id [in] Chart ID (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error.
1250
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1251
Standard Library
CChartObjectRegression
Class CChartObjectRegression is a class for simplified access to "Linear Regression Channel" graphic object properties.
Description
Class CChartObjectRegression provides access to "Linear Regression Channel" object properties.
Declaration
class CChartObjectRegression : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create Create Creates graphic object "Linear Regression Channel"
Input/output virtual Type See also Object types, Graphic objects Virtual method of identification
1252
Standard Library
Create
Creates graphic object "Linear Regression Channel"
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // Second time coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. Returned value true if successful, false if error.
1253
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1254
Standard Library
CChartObjectStdDevChannel
Class CChartObjectStdDevChannel is a class for simplified access to "Standard Deviation Channel" graphic object properties.
Description
Class CChartObjectStdDevChannel provides access to "Standard Deviation Channel" object properties.
Declaration
class CChartObjectStdDevChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create Create Creates graphic object "Standard Deviation Channel"
Properties Deviations Input/output virtual Save virtual Load virtual Type See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Deviation"
1255
Standard Library
Create
Creates graphic object "Standard Deviation Channel"
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // Second time coordinate // Deviation
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. deviation [in] Numerical value for "Deviation" property. Returned value true if successful, false if error.
1256
Standard Library
Returned value Numerical value of "Deviation" property, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters deviation [in] New value for "Deviation" property. Returned value true if successful, false if property hasn't changed.
1257
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...) . Returned value true if successful, false if error.
1258
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...) . Returned value true if successful, false if error.
1259
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1260
Standard Library
CChartObjectPitchfork
Class CChartObjectPitchfork is a class for simplified access to "Andrew's Pitchfork" graphic object properties.
Description
Class CChartObjectPitchfork provides access to "Andrew's Pitchfork" object properties.
Declaration
class CChartObjectPitchfork : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsChannels.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Andrew's Pitchfork"
1261
Standard Library
Create
Creates graphic object "Andrew's Pitchfork"
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // 1st time coordinate // 1st price coordinate // ...
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point.. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the first anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error.
1262
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1263
Standard Library
Gann Tools
A group of graphic objects "Gann Tools". This section contains the technical details of working with a group of classes of graphical objects "Gann Tools" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectGannLine CChartObjectGannFan CChartObjectGannGrid See also Object types, Graphic objects Object Graphic object "Gann Line" Graphic object "Gann Fan" Graphic object "Gann Grid"
1264
Standard Library
CChartObjectGannLine
Class CChartObjectGannLine is a class for simplified access to "Gann Line" graphic object properties.
Description
Class CChartObjectGannLine provides access to "Gann Line" object properties.
Declaration
class CChartObjectGannLine : public CChartObjectTrendByAngle
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create Create Properties PipsPerBar Input/output virtual Save virtual Load virtual Type See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Scale" Creates graphic object "Gann Line"
1265
Standard Library
Create
Creates graphic object "Gann Line".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Pips per bar
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. ppb [in] Pips per bar. Returned value true if successful, false if error.
1266
Standard Library
Returned value Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters ppb [in] New value for "Pips per bar" property. Returned value true if successful, false if property hasn't changed.
1267
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1268
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1269
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1270
Standard Library
CChartObjectGannFan
Class CChartObjectGannFan is a class for simplified access to "Gann Fan" graphic object properties.
Description
Class CChartObjectGannFan provides access to "Gann Fan" object properties.
Declaration
class CChartObjectGannFan : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create Create Properties PipsPerBar Downtrend Input/output virtual Save virtual Load virtual Type See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Pips per bar" Gets/Sets property "Downtrend" Creates graphic object "Gann Fan"
1271
Standard Library
Create
Creates graphic object "Gann Fan".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Pips per bar
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. ppb [in] Pips per bar. Returned value true if successful, false if error.
1272
Standard Library
Returned value Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters ppb [in] New value for "Pips per bar" property. Returned value true if successful, false if property hasn't changed.
1273
Standard Library
Returned value Value of the "Downtrend" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters downtrend [in] New value for "Downtrend" property. Returned value true if successful, false if property hasn't changed.
1274
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1275
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1276
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1277
Standard Library
CChartObjectGannGrid
Class CChartObjectGannGrid is a class for simplified access to "Gann Grid" graphic object properties.
Description
Class CChartObjectGannGrid provides access to "Gann Grid" object properties.
Declaration
class CChartObjectGannGrid : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsGann.mqh>
Class Methods
Create Create Properties PipsPerBar Downtrend Input/output virtual Save virtual Load virtual Type See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Pips per bar" Gets/Sets property "Downtrend" Creates graphic object "Gann Grid"
1278
Standard Library
Create
Creates graphic object "Gann Grid".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Pips per bar
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. ppb [in] Pips per bar. Returned value true if successful, false if error.
1279
Standard Library
Returned value Value of "Pips per bar" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters ppb [in] New value for "Pips per bar" property. Returned value true if successful, false if property hasn't changed.
1280
Standard Library
Returned value Value of "Downtrend" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters downtrend [in] New value for "Downtrend" property. Returned value true if successful, false if property hasn't changed.
1281
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1282
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1283
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1284
Standard Library
Fibonacci Tools
A group of graphic objects "Fibonacci Tools". This section contains the technical details of working with a group of classes of graphical objects "Fibonacci Tools" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectFibo CChartObjectFiboTimes CChartObjectFiboFan CChartObjectFiboArc CChartObjectFiboChannel CChartObjectFiboExpansion See also Object types, Graphic objects Object Graphic object "Fibonacci Retracement" Graphic object "Fibonacci Time Zones" Graphic object "Fibonacci Fan" Graphic object "Fibonacci Arc" Graphic object "Fibonacci Channel" Graphic object "Fibonacci Expansion"
1285
Standard Library
CChartObjectFibo
Class CChartObjectFibo is a class for simplified access to "Fibonacci Retracement" graphic object properties.
Description
Class CChartObjectFibo provides access to "Fibonacci Retracement" object properties.
Declaration
class CChartObjectFibo : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Fibonacci Retracement"
1286
Standard Library
Create
Creates graphic object "Fibonacci Retracement".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1287
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1288
Standard Library
CChartObjectFiboTimes
Class CChartObjectFiboTimes is a class for simplified access to "Fibonacci Time Zones" graphic object properties.
Description
Class CChartObjectFiboTimes provides access to "Fibonacci Time Zones" object properties.
Declaration
class CChartObjectFiboTimes : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Fibonacci Time Zones"
1289
Standard Library
Create
Creates graphic object "Fibonacci Time Zones".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1290
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1291
Standard Library
CChartObjectFiboFan
Class CChartObjectFiboFan is a class for simplified access to "Fibonacci Fan" graphic object properties.
Description
Class CChartObjectFiboFan provides access to "Fibonacci Fan" object properties.
Declaration
class CChartObjectFiboFan : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Fibonacci Fan"
1292
Standard Library
Create
Creates graphic object "Fibonacci Fan".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, false if error.
1293
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1294
Standard Library
CChartObjectFiboArc
Class CChartObjectFiboArc is a class for simplified access to "Fibonacci Arc" graphic object properties.
Description
Class CChartObjectFiboArc provides access to "Fibonacci Arc" object properties.
Declaration
class CChartObjectFiboArc : public CChartObject
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Properties Scale Ellipse Input/output virtual Save virtual Load virtual Type See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Scale" Gets/Sets property "Ellipse" Creates graphic object "Fibonacci Arc"
1295
Standard Library
Create
Creates graphic object "Fibonacci Arc"
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Scale
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. scale [in] Scale. Returned value true if successful, false if error.
1296
Standard Library
Returned value Value of "Scale" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters scale [in] New value for "Scale" property. Returned value true if successful, false if property hasn't changed.
1297
Standard Library
Returned value Value of "Ellipse" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters ellipse [in] New value for "Scale" property. Returned value true if successful, false if property hasn't changed.
1298
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1299
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1300
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1301
Standard Library
CChartObjectFiboChannel
Class CChartObjectFiboChannel is a class for simplified access to "Fibonacci Channel" graphic object properties.
Description
Class CChartObjectFiboChannel provides access to "Fibonacci Channel" object properties.
Declaration
class CChartObjectFiboChannel : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Fibonacci Channel"
1302
Standard Library
Create
Creates graphic object "Fibonacci Channel".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error.
1303
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1304
Standard Library
CChartObjectFiboExpansion
Class CChartObjectFiboExpansion is a class for simplified access to "Fibonacci Expansion" graphic object properties.
Description
Class CChartObjectFiboExpansion provides access to "Fibonacci Expansion" object properties.
Declaration
class CChartObjectFiboExpansion : public CChartObjectTrend
Title
#include <ChartObjects\ChartObjectsFibo.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Fibonacci Expansion"
1305
Standard Library
Create
Creates graphic object "Fibonacci Expansion".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error.
1306
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1307
Standard Library
Elliott Tools
A group of graphic objects "Elliott Tools". This section contains the technical details of working with a group of classes of graphical objects "Elliott Tools" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectElliottWave3 CChartObjectElliottWave5 See also Object types, Graphic objects Object Graphic object "Correcting Wave" Graphic object "Impulse Wave"
1308
Standard Library
CChartObjectElliottWave3
Class CChartObjectElliottWave3 is a class for simplified access to "Correcting Wave" graphic object properties.
Description
Class CChartObjectElliottWave3 provides access to "Correcting Wave" object properties.
Declaration
class CChartObjectElliottWave3 : public CChartObject
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create Create Properties Degree Lines Input/output virtual Save virtual Load virtual Type Derived classes: CChartObjectElliottWave5 See also Object types, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Degree" Gets/Sets property "Lines" Creates graphic object "Correcting Wave"
1309
Standard Library
Create
Creates graphic object "Correcting Wave".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Time coordinate of the third anchor point. Returned value true if successful, false if error.
1310
Standard Library
Returned value Value of "Degree" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters degree [in] New value for "Degree" property. Returned value true if successful, false if property hasn't changed.
1311
Standard Library
Returned value Value of "Lines" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters lines [in] New value for "Lines" property. Returned value true if successful, false if flag hasn't changed.
1312
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1313
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened using by function FileOpen(...). Returned value true if successful, false if error.
1314
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1315
Standard Library
CChartObjectElliottWave5
Class CChartObjectElliottWave5 is a class for simplified access to "Impulse Wave" graphic object properties.
Description
Class CChartObjectElliottWave5 provides access to "Impulse Wave" object properties.
Declaration
class CChartObjectElliottWave5 : public CChartObjectElliottWave3
Title
#include <ChartObjects\ChartObjectsElliott.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Impulse Wave"
1316
Standard Library
Create
Creates graphic object "Impulse Wave".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate // Fourth time coordinate // Fourth price coordinate // Fifth time coordinate // Fifth price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. time4 [in] Time coordinate of the fourth anchor point.
1317
Standard Library price4 [in] Price coordinate of the fourth anchor point. time5 [in] Time coordinate of the fifth anchor point. price5 [in] Price coordinate of the fifth anchor point. Returned value true if successful, false if error.
1318
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1319
Standard Library
Objects Shapes
A group of graphic objects "Shapes". This section contains the technical details of working with a group of classes of graphical objects "Shapes" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectRectangle CChartObjectTriangle CChartObjectEllipse See also Object types, Graphic objects Object Graphic object "Rectangle" Graphic object "Triangle" Graphic object "Ellipse"
1320
Standard Library
CChartObjectRectangle
Class CChartObjectRectangle is a class for simplified access to "Rectangle" graphic object properties.
Description
Class CChartObjectRectangle provides access to "Rectangle" object properties.
Declaration
class CChartObjectRectangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Rectangle"
1321
Standard Library
Create
Creates graphic object "Rectangle".
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. Returned value true if successful, 0 if error
1322
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1323
Standard Library
CChartObjectTriangle
Class CChartObjectTriangle is a class for simplified access to "Triangle" graphic object properties.
Description
Class CChartObjectTriangle provides access to "Triangle" object properties.
Declaration
class CChartObjectTriangle : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Triangle"
1324
Standard Library
Create
Creates graphic object "Triangle".
bool Create( long string long chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error
1325
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1326
Standard Library
CChartObjectEllipse
Class CChartObjectEllipse is a class for simplified access to "Ellipse" graphic object properties.
Description
Class CChartObjectEllipse provides access to "Ellipse" object properties.
Declaration
class CChartObjectEllipse : public CChartObject
Title
#include <ChartObjects\ChartObjectsShapes.mqh>
Class Methods
Create Create Input/output virtual Type See also Object types, Graphic objects Virtual method of identification Creates graphic object "Ellipse"
1327
Standard Library
Create
Creates graphic object "Ellipse".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // First time coordinate // First price coordinate // Second time coordinate // Second price coordinate // Third time coordinate // Third price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time1 [in] Time coordinate of the first anchor point. price1 [in] Price coordinate of the first anchor point. time2 [in] Time coordinate of the second anchor point. price2 [in] Price coordinate of the second anchor point. time3 [in] Time coordinate of the third anchor point. price3 [in] Price coordinate of the third anchor point. Returned value true if successful, false if error
1328
Standard Library
Type
Returns object type identifier of the graphic object.
int Type() const
1329
Standard Library
Objects Arrows
Group for graphic objects Arrows. This section contains the technical details of working with a group of classes of graphical objects "Arrow" and a description of the relevant components of the MQL5 Standard Library . In essence, the arrow - this is some icon to be displayed to the user, which matches a certain code. There are two types of graphical objects "Arrow" to display icons on the charts: Object "Arrow", which allows you to specify the code icon displayed object. Group objects to display certain types of icons (and the corresponding certain fixed code).
1330
Standard Library
CChartObjectArrow
Class CChartObjectArrow is a class for simplified access to "Arrow" graphic object properties.
Description
Class CChartObjectArrow provides access to common properties of objects "Arrow" to all of its descendants.
Declaration
class CChartObjectArrow : public CChartObject
Title
#include <ChartObjects\ChartObjectsArrow.mqh>
Class Methods
Create Create Properties ArrowCode Anchor Input/output virtual Save virtual Load virtual Type See also Object types, Methods of binding sites, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Arrow Code" Gets/Sets property "Anchor" Creates graphic object "Arrow"
1331
Standard Library
Create
Creates graphic object "Arrow".
bool Create( long string int chart_id, name, window, // Chart ID // Object Name // Chart Window // Time // Price // Arrow Code
Parameters chart_id [in] Chart Identifier (0 current chart). name [in] Object name (Should be unique). window [in] Chart window number (0 base window). time [in] Time coordinate. price [in] Price coordinate. code [in] "Arrow" code (Wingdings). Returned value true if successful, overwise false. Example:
//--- example for CChartObjectArrow::Create #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { CChartObjectArrow arrow; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181)) { //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //---
1332
Standard Library
return; } //--- use arrow //--- . . . }
1333
Standard Library
Returned value Symbol code of "Arrow" object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters code [in] new value for "arrow" code (Wingdings). Returned value true if successful, false if code hasn't changed. Example:
//--- example for CChartObjectArrow::ArrowCode #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { CChartObjectArrow arrow; char code=181; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,code)) { //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //--return; } //--- use arrow to possible changes code //--- . . . //--- get code of arrow if(arrow.ArrowCode()!=code) { //--- set code of arrow
1334
Standard Library
arrow.ArrowCode(code); } //--- use arrow //--- . . . }
1335
Standard Library
Returned value Anchor type of "Arrow" object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters new_color [in] New value of color for line of the graphic object. Returned value true if successful, false if color hasn't changed. Example:
//--- example for CChartObject::Anchor #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { CChartObjectArrow arrow; ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181)) { //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //--return; } //--- get anchor of arrow if(arrow.Anchor()!=anchor) { //--- set anchor of arrow arrow.Anchor(anchor); }
1336
Standard Library
//--- use arrow //--- . . . }
1337
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // file handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...) . Returned value true if successful, overwise false. Example:
//--- example for CChartObjectArrow::Save #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { int file_handle; CChartObjectArrow arrow; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"Arrow",0,TimeCurrent(),price,181)) { //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //--return; } //--- open file file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!arrow.Save(file_handle)) { //--- file save error printf("File save: Error %d!",GetLastError()); FileClose(file_handle); //--return; } FileClose(file_handle); } }
1338
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // file handle
Parameters file_handle [in] handle of the file already opened using by function FileOpen(...). Returned value true if successful, overwise false. Example:
//--- example for CChartObjectArrow::Load #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { int //--- open file file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI); if(file_handle>=0) { if(!arrow.Load(file_handle)) { //--- file load error printf("File load: Error %d!",GetLastError()); FileClose(file_handle); //--return; } FileClose(file_handle); } //--- use arrow //--- . . . } file_handle; CChartObjectArrow arrow;
1339
Standard Library
Type
Returns graphic object type identifier
virtual int Type() const
Returned value Object type identifier (for example, OBJ_ARROW for CChartObjectArrow) Example:
//--- example for CChartObjectArrow::Type #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { CChartObjectArrow arrow; //--- get arrow type int type=arrow.Type(); }
1340
Standard Library
Description
Classes "Arrows with fixed code" provides access to the object properties.
Declarations
class CChartObjectArrowCheck class CChartObjectArrowDown class CChartObjectArrowUp class CChartObjectArrowStop class CChartObjectArrowThumbDown class CChartObjectArrowThumbUp class CChartObjectArrowLeftPrice : public CChartObjectArrow; : public CChartObjectArrow; : public CChartObjectArrow; : public CChartObjectArrow; : public CChartObjectArrow; : public CChartObjectArrow; : public CChartObjectArrow;
Title
<ChartObjects\ChartObjectsArrow.mqh>
Class Methods
Create Create Properties ArrowCode Input/output virtual Type Virtual method of identification "Gag" for method of code change Creates graphic object specified
1341
Standard Library
1342
Standard Library
Create
Creates graphic object "Arrow with fixed code".
bool Create( long string int chart_id, name, window, // Chart ID // Object Name // Chart Window // Time // Price
Parameters chart_id [in] Chart identifier (0 current chart). name [in] Unique name of the object to create. window [in] Chart window number (0 base window). time [in] Time coordinate. price [in] Price coordinate. Returned value true if successful, false if error. Example:
//--- example for CChartObjectArrowCheck::Create //--- example for CChartObjectArrowDown::Create //--- example for CChartObjectArrowUp::Create //--- example for CChartObjectArrowStop::Create //--- example for CChartObjectArrowThumbDown::Create //--- example for CChartObjectArrowThumbUp::Create //--- example for CChartObjectArrowLeftPrice::Create //--- example for CChartObjectArrowRightPrice::Create #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { //--- for example, take CChartObjectArrowCheck CChartObjectArrowCheck arrow; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"ArrowCheck",0,TimeCurrent(),price))
1343
Standard Library
{ //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //--return; } //--- use arrow //--- . . . }
1344
Standard Library
ArrowCode
Prohibits code changes for "Arrow".
bool ArrowCode( char code ) // code value
Parameters code [in] any value Returned value Always false. Example:
//--- example for CChartObjectArrowCheck::ArrowCode //--- example for CChartObjectArrowDown::ArrowCode //--- example for CChartObjectArrowUp::ArrowCode //--- example for CChartObjectArrowStop::ArrowCode //--- example for CChartObjectArrowThumbDown::ArrowCode //--- example for CChartObjectArrowThumbUp::ArrowCode //--- example for CChartObjectArrowLeftPrice::ArrowCode //--- example for CChartObjectArrowRightPrice::ArrowCode #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { //--- for example, take CChartObjectArrowCheck CChartObjectArrowCheck arrow; //--- set object parameters double price=SymbolInfoDouble(Symbol(),SYMBOL_BID); if(!arrow.Create(0,"ArrowCheck",0,TimeCurrent(),price)) { //--- arrow create error printf("Arrow create: Error %d!",GetLastError()); //--return; } //--- set code of arrow if(!arrow.ArrowCode(181)) { //--- it is not error printf("Arrow code can not be changed"); } //--- use arrow //--- . . . }
1345
Standard Library
Type
Returns graphic object type identifier
virtual int Type() const
Returned value Object type identifier (OBJ_ARROW_CHECK for CChartObjectArrowCheck, OBJ_ARROW_DOWN for CChartObjectArrowDown, OBJ_ARROW_UP for CChartObjectArrowUp, OBJ_ARROW_STOP for CChartObjectArrowStop, OBJ_ARROW_THUMB_DOWN for CChartObjectArrowThumbDown, OBJ_ARROW_THUMB_UP for CChartObjectArrowThumbUp, OBJ_ARROW_LEFT_PRICE for CChartObjectArrowLeftPrice, OBJ_ARROW_RIGHT_PRICE for CChartObjectArrowRightPrice). Example:
//--- example for CChartObjectArrowCheck::Type //--- example for CChartObjectArrowDown::Type //--- example for CChartObjectArrowUp::Type //--- example for CChartObjectArrowStop::Type //--- example for CChartObjectArrowThumbDown::Type //--- example for CChartObjectArrowThumbUp::Type //--- example for CChartObjectArrowLeftPrice::Type //--- example for CChartObjectArrowRightPrice::Type #include <ChartObjects\ChartObjectsArrows.mqh> //--void OnStart() { //--- for example, take CChartObjectArrowCheck CChartObjectArrowCheck arrow; //--- get arrow type int type=arrow.Type(); }
1346
Standard Library
Object Controls
A group of graphic objects "Object Controls". This section contains the technical details of working with a group of classes of graphical objects "Object Controls" and a description of the relevant components of the MQL5 Standard Library . Class name CChartObjectText CChartObjectLabel CChartObjectEdit CChartObjectButton CChartObjectSubChart CChartObjectBitmap CChartObjectBmpLabel CChartObjectRectLabel See also Object types, Graphic objects Object Graphic object "Text" Graphic object "Text Label" Graphic object "Edit" Graphic object "Button" Graphic object "Chart" Graphic object "Bitmap" Graphic object "Bitmap Label" Graphic object "Rectangle Label"
1347
Standard Library
CChartObjectText
Class CChartObjectText is a class for simplified access to "Text" graphic object properties.
Description
Class CChartObjectText provides access to "Text" object properties.
Declaration
class CChartObjectText : public CChartObject
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create Create Properties Angle Font FontSize Anchor Input/output virtual Save virtual Load virtual Type Derived classes: CChartObjectLabel See also Object types, Object properties, Methods of binding sites, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "Angle" Gets/Sets property "Font" Gets/Sets property "FontSize" Gets/Sets property "Anchor" Creates graphic object "Text"
1348
Standard Library
Create
Creates graphic object "Text".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // Time coordinate // Price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time [in] Time coordinate of the anchor point. price [in] Price coordinate of the anchor point. Returned value true if successful, false if error.
1349
Standard Library
Returned value Value of "Angle" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters angle [in] New value for "Angle" property. Returned value true if successful, false if property hasn't changed.
1350
Standard Library
Returned value Value of "Font" property of the object, assigned to the class instance. If there is no object assigned, it returns "".
Parameters font [in] New value for "Font" property. Returned value true if successful, false if property hasn't changed.
1351
Standard Library
Returned value Value of "FontSize" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters size [in] New value for "Font" property. Returned value true if successful, false if property hasn't changed.
1352
Standard Library
Returned value Value of "Anchor" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters anchor [in] New value for "Anchor" property. Returned value true if successful, false if property hasn't changed.
1353
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1354
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1355
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1356
Standard Library
CChartObjectLabel
Class CChartObjectLabel is a class for simplified access to "Label" graphic object properties.
Description
Class CChartObjectLabel provides access to "Label" object properties.
Declaration
class CChartObjectLabel : public CChartObjectText
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create Create Properties X_Distance Y_Distance X_Size Y_Size Corner Time Price Input/output virtual Save virtual Load virtual Type Derived classes: CChartObjectEdit See also Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "X_Distance" Gets/Sets property "Y_Distance" Gets/Sets property "X_Size" Gets/Sets property "Y_Size" Gets/Sets property "Corner" "Gag" for Time Coordinate change "Gag" for Price Coordinate change Creates graphic object "Label"
1357
Standard Library
Create
Creates graphic object "Label".
bool Create( long chart_id, // Chart identifier // Object name // Chart window // X coordinate // Y coordinate // X size // Y size string name, int int int int int ) window, X, Y, sizeX, sizeY
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). X [in] X coordinate. Y [in] Y coordinate. sizeX [in] X size. sizeY [in] Y size. Returned value true if successful, false if error.
1358
Standard Library
Returned value Value of "X_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters X [in] New value for "X_Distance" property. Returned value true if successful, false if property hasn't changed.
1359
Standard Library
Returned value Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters Y [in] New value for "Y_Distance" property. Returned value true if successful, false if property hasn't changed.
1360
Standard Library
X_Size
Gets the value of "X_Size" property.
int X_Size() const
Returned value Value of "X_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
1361
Standard Library
Y_Size
Gets the value of "Y_Size" property.
int Y_Size() const
Returned value Value of "Y_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
1362
Standard Library
Returned value Value of "Corner" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters corner [in] New value for "Corner" property. Returned value true if successful, false if property hasn't changed.
1363
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time( datetime time ) // any value
Parameters time [in] Any value of datetime type. Returned value always false.
1364
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price( double price ) // any value
Parameters price [in] Any value of double type. Returned value always false.
1365
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1366
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1367
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1368
Standard Library
CChartObjectEdit
Class CChartObjectEdit is a class for simplified access to "Edit" graphic object properties.
Description
Class CChartObjectEdit provides access to "Edit" object properties.
Declaration
class CChartObjectEdit : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create Create Properties X_Size Y_Size BackColor Angle Input/output virtual Save virtual Load virtual Type Derived classes: CChartObjectButton See also Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets property "X Size" Gets property "Y Size" Gets/Sets property "Background Color" Gets/Sets property "Angle" Creates graphic object "Edit"
1369
Standard Library
Create
Creates graphic object "Edit".
bool Create( long chart_id, // Chart identifier // Object name // Chart window // X coordinate // Y coordinate // X size // Y size string name, int int int int int ) window, X, Y, sizeX, sizeY
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). X [in] X coordinate. Y [in] Y coordinate. sizeX [in] X size. sizeY [in] Y size. Returned value true if successful, false if error.
1370
Standard Library
X_Size
Sets new value for "X_Size" property.
bool X_Size( int size ) // new size
Parameters size [in] New value for "X_Size" property. Returned value true if successful, false if property hasn't changed.
1371
Standard Library
Y_Size
Sets new value for "Y_Size" property.
bool Y_Size( int size ) // new size
Parameters size [in] New value for "Y_Size" property. Returned value true if successful, false if property hasn't changed.
1372
Standard Library
Returned value Value of "BackColor" property of the object, assigned to the class instance. If there is no object assigned, it returns CLR_NONE.
Parameters new_color [in] New value for "BackColor" property. Returned value true if successful, false if property hasn't changed.
1373
Standard Library
Angle
Prohibits changes of the "Angle" property.
bool Angle( double angle ) // any value
Parameters angle [in] Any value of double type. Returned value always false.
1374
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1375
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1376
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1377
Standard Library
CChartObjectButton
Class CChartObjectButton is a class for simplified access to "Button" graphic object properties.
Description
Class CChartObjectButton provides access to "Button" object properties.
Declaration
class CChartObjectButton : public CChartObjectEdit
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create Create Properties State Input/output virtual Save virtual Load virtual Type See also Object types, Object properties, Chart angle, Methods of binding sites, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets button state (Pressed/Depressed) Inherited form class CChartObjectEdit
1378
Standard Library
Returned value Value of "State" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters X [in] New value for "State" property. Returned value true if successful, false if property hasn't changed.
1379
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1380
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1381
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1382
Standard Library
CChartObjectSubChart
Class CChartObjectSubChart is a class for simplified access to "Chart" graphic object properties.
Description
Class CChartObjectSubChart provides access to "Chart" object properties.
Declaration
class CChartObjectSubChart : public CChartObject
Title
#include <ChartObjects\ChartObjectsSubChart.mqh>
Class Methods
Create Create Properties X_Distance Y_Distance Corner X_Size Y_Size Symbol Period Scale DateScale PriceScale Time Price Input/output virtual Save virtual Load virtual Type See also Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "X_Distance" Gets/Sets property "Y_Distance" Gets/Sets property "Corner" Gets/Sets property "X_Size" Gets/Sets property "Y_Size" Gets/Sets property "Symbol" Gets/Sets property "Period" Gets/Sets property "Scale" Gets/Sets property "Show date scale" Gets/Sets property "Show price scale" "Gag" for time coordinate change "Gag" for price coordinate change Creates graphic object "Chart"
1383
Standard Library Object types, Object properties, Chart angle, Graphic objects
1384
Standard Library
Create
Creates graphic object "SubChart".
bool Create( long chart_id, // Chart identifier // Object name // Chart window // X coordinate // Y coordinate // X size // Y size string name, int int int int int ) window, X, Y, sizeX, sizeY
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). X [in] X coordinate. Y [in] Y coordinate. sizeX [in] X size. sizeY [in] Y size. Returned value true if successful, false if error.
1385
Standard Library
Returned value Value of "X_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters X [in] New value for "X_Distance" property. Returned value true if successful, false if property hasn't changed.
1386
Standard Library
Returned value Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters Y [in] New value for "Y_Distance" property. Returned value true if successful, false if property hasn't changed.
1387
Standard Library
Returned value Value of "Corner" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters corner [in] New value for "Corner" property. Returned value true if successful, false if property hasn't changed.
1388
Standard Library
Returned value Value of "X_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters X [in] New value for "X_Size" property. Returned value true if successful, false if property hasn't changed.
1389
Standard Library
Returned value Value of "Y_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters Y [in] New value for "Y_Size" property. Returned value true if successful, false if property hasn't changed.
1390
Standard Library
Returned value Value of "Symbol" property of the object, assigned to the class instance. If there is no object assigned, it returns "".
Parameters symbol [in] New value for "Symbol" property. Returned value true if successful, false if property hasn't changed.
1391
Standard Library
Returned value Value of "Period" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters period [in] New value for "Period" property. Returned value true if successful, false if property hasn't changed.
1392
Standard Library
Returned value Value of "Scale" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters scale [in] New value for "Scale" property. Returned value true if successful, false if property hasn't changed.
1393
Standard Library
Returned value Value of "DateScale" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters scale [in] New value for "DateScale" property. Returned value true if successful, false if property hasn't changed.
1394
Standard Library
Returned value Value of "PriceScale" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters scale [in] New value for "PriceScale" property. Returned value true if successful, false if property hasn't changed.
1395
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time( datetime time ) // any value
Parameters time [in] Any value of datetime type. Returned value always false.
1396
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price( double price ) // any value
Parameters price [in] Any value of double type. Returned value always false.
1397
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1398
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1399
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1400
Standard Library
CChartObjectBitmap
Class CChartObjectBitmap is a class for simplified access to "Bitmap" graphic object properties.
Description
Class CChartObjectBitmap provides access to "Bitmap" object properties.
Declaration
class CChartObjectBitmap : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create Create Properties BmpFile Input/output virtual Save virtual Load virtual Type See also Object types, Object properties, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Gets/Sets property "BMP Filename" Creates graphic object "Bitmap"
1401
Standard Library
Create
Creates graphic object "Bitmap".
bool Create( long string int chart_id, name, window, // Chart identifier // Object name // Chart window // Time coordinate // Price coordinate
Parameters chart_id [in] Chart identifier (0 current chart). name [in] An unique name of the object to create. window [in] Chart window number (0 base window). time [in] Time coordinate of the anchor point. price [in] Price coordinate of the anchor point. Returned value true if successful, false if error.
1402
Standard Library
Returned value Value of "BmpFile" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters X [in] New value for "BmpFile" property. Returned value true if successful, false if property hasn't changed.
1403
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1404
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1405
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1406
Standard Library
CChartObjectBmpLabel
Class CChartObjectBmpLabel is a class for simplified access to "Bitmap Label" graphic object properties.
Description
Class CChartObjectBmpLabel provides access to "Bitmap Label" object properties.
Declaration
class CChartObjectBmpLabel : public CChartObject
Title
#include <ChartObjects\ChartObjectsBmpControls.mqh>
Class Methods
Create Create Properties X_Distance Y_Distance Corner X_Size Y_Size BmpFileOn Gets/Sets property "X_Distance" Gets/Sets property "Y_Distance" Gets/Sets property "Corner" Gets/Sets property "X_Size" Gets/Sets property "Y_Size" Gets/Sets property "BmpFileOn" for button pressed state (On) Gets/Sets property "BmpFileOff" for button depressed state (Off) Gets/Sets property "Button State" (Pressed/ Depressed) "Gag" for time coordinate change "Gag" for price coordinate change Creates graphic object "BmpLabel"
BmpFileOff
State
Time Price Input/output virtual Save virtual Load virtual Type See also
Virtual method for writing to file Virtual method for reading from file Virtual method of identification
1407
Standard Library Object types, Object properties, Chart angle, Graphic objects
1408
Standard Library
Create
Creates graphic object "BmpLabel".
bool Create( long chart_id, // Chart identifier // Object name // Chart window // X coordinate // Y coordinate string name, int int int ) window, X, Y
Parameters chart_id [in] Chart identifier (0 current chart). name [in] A unique name of the object to create. window [in] Chart window number (0 base window). X [in] X coordinate. Y [in] Y coordinate. Returned value true if successful, false if error.
1409
Standard Library
Returned value Value of "X_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters X [in] New value for "X_Distance" property. Returned value true if successful, false if property hasn't changed.
1410
Standard Library
Returned value Value of "Y_Distance" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters Y [in] New value for "Y_Distance" property. Returned value true if successful, false if property hasn't changed.
1411
Standard Library
Returned value Value of "Corner" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters corner [in] New value for "Corner" property. Returned value true if successful, false if property hasn't changed.
1412
Standard Library
X_Size
Gets the value of "X_Size" property.
int X_Size() const
Returned value Value of "X_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
1413
Standard Library
Y_Size
Gets the value of "Y_Size" property.
int Y_Size() const
Returned value Value of "Y_Size" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
1414
Standard Library
Returned value Value of "BmpFileOn" property of the object, assigned to the class instance. If there is no object assigned, it returns "".
Parameters name [in] New value for "BmpFileOn" property. Returned value true if successful, false if property hasn't changed.
1415
Standard Library
Returned value Value of "BmpFileOff" property of the object, assigned to the class instance. If there is no object assigned, it returns "".
Parameters name [in] New value for "BmpFileOff" property. Returned value true if successful, false if property hasn't changed.
1416
Standard Library
Returned value Value of "State" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters X [in] New value for "State" property. Returned value true if successful, false if property hasn't changed.
1417
Standard Library
Time
Prohibits changes of the time coordinate.
bool Time( datetime time ) // any value
Parameters time [in] Any value of datetime type. Returned value always false.
1418
Standard Library
Price
Prohibits changes of the price coordinate.
bool Price( double price ) // any value
Parameters price [in] Any value of double type. Returned value always false.
1419
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1420
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1421
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1422
Standard Library
CChartObjectRectLabel
Class CChartObjectRectLabel is a class for simplified access to "Rectangle Label" graphic object properties.
Description
Class CChartObjectRectLabel provides access to "Rectangle Label" object properties.
Declaration
class CChartObjectRectLabel : public CChartObjectLabel
Title
#include <ChartObjects\ChartObjectsTxtControls.mqh>
Class Methods
Create Create Properties X_Size Y_Size BackColor Angle BorderType Input/output virtual Save virtual Load virtual Type See also Object types, Object properties, Graphic objects Virtual method for writing to file Virtual method for reading from file Virtual method of identification Sets the horizontal size Sets the vertical size Gets/Sets the background color A gag method Gets/Sets type of the border Creates "RectLabel" graphic object
1423
Standard Library
Create
Creates the "CChartObjectRectLabel" graphic object.
bool Create( long chart_id, // Chart ID // Object name // Chart window // X coordinate // Y coordinate // Horizontal size // Vertical size string name, int int int int int ) window, X, Y, sizeX, sizeY
Parameters chart_id [in] Chart identifier (0 current chart). name [in] A unique name of the object to create. window [in] Chart window number (0 base window). X [in] X coordinate. Y [in] Y coordinate. sizeX [in] Horizontal size. sizeY [in] Vertical size. Returned value true if successful, false if error.
1424
Standard Library
X_Size
Sets the value of "X_Size" property.
bool X_Size( int size ) // Horizontal size
Parameters size [in] New horizontal size. Returned value true if successful, false if the property hasn't been changed. Note To get the values of "X_Size" and "Y_Size" properties use the X_Size and Y_Size methods of the parent CChartObjectLabel class.
1425
Standard Library
Y_Size
Sets the value of "Y_Size" property.
bool Y_Size( int size ) // Vertical size
Parameters size [in] New vertical size. Returned value true if successful, false if the property hasn't been changed. Note To get the values of "X_Size" and "Y_Size" properties use the X_Size and Y_Size methods of the parent CChartObjectLabel class.
1426
Standard Library
BackColor
Gets the background color.
color BackColor() const
Returned value Background color of the object, assigned to the class instance. If there is no object assigned, it returns 0.
BackColor
Sets the background color.
bool BackColor( color new_color ) // New color
Parameters new_color [in] New background color. Returned value true if successful, false if property hasn't been changed.
1427
Standard Library
Angle
A gag method.
bool Angle( double angle ) // any value
Parameters angle [in] Any value of double type. Returned value Always false.
1428
Standard Library
BorderType
Gets border type.
int BorderType() const
Returned value Border type of the object, assigned to the class instance. If there is no object assigned, it returns 0.
BorderType
Sets border type.
bool BorderType( int type ) // Border type
Parameters type [in] New border type. Returned value true if successful, false if property hasn't been changed.
1429
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1430
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen function. Returned value true if successful, false if error.
1431
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1432
Standard Library
CChart
Class CChart is a class for simplified access to "Chart" graphic object properties.
Description
Class CChart provides access to "Chart" object properties.
Declaration
class CChart : public CObject
Title
<Charts\Chart.mqh>
Class Methods
Access to protected data ChartID General properties Mode Gets/Sets the value of "Mode" property (bar, candle or line). Gets/Sets the value of "Foreground" property. Gets/Sets the value of "Shift" property. Gets/Sets the value of "ShiftSize" property (in percents). Gets/Sets the value of "AutoScroll" property. Gets/Sets the value of "Scale" property. Gets/Sets the value of "ScaleFix" property (fixed chart scale or not). Gets/Sets the value of "ScaleFix_11" property (chart scale is 1:1, or not). Gets/Sets the value of "FixedMax" property (fixed maximal price). Gets/Sets the value of "FixedMin" property (fixed minimal price). Gets/Sets the value of "ScalePPB" property (scale is "point per bar" or not). Gets/Sets the value of "PointsPerBar" property (in points per bar). Gets identifier of the chart.
ScaleFix_11
FixedMax
FixedMin
ScalePPB
PointsPerBar
Show properties
1433
Standard Library
Gets/Sets the value of "ShowOHLC" property. Gets/Sets the value of "ShowLineBid" property. Gets/Sets the value of "ShowLineAsk" property. Gets/Sets property. the value of "ShowLastLine"
ShowPeriodSep
Gets/Sets the value of "ShowPeriodSep" property (show period separators). Gets/Sets the value of "ShowGrid" property. Gets/Sets the value of "ColorVolumes" property (color for volumes and levels of opened positions). Gets/Sets the value of "ShowObjectDescr" property (show description for graphic objects).
ShowGrid ShowVolumes
ShowObjectDescr
Colors properties ColorBackground Gets/Sets the value of "ColorBackground" property (background color of the chart). Gets/Sets the value of "ColorForeground" property (color of axes, scale and OHLC strings of the chart). Gets/Sets the value of "ColorGrid" property (color of the grid). Gets/Sets the value of "ColorBarUp" property (color for bull bars, its shadow and candle body outlines). Gets/Sets the value of "ColorBarDown" property (color for bear bars, its shadow and candle body outlines). Gets/Sets the value of "ColorCandleBull" property (body color of the bull candle). Gets/Sets the value of "ColorCandleBear" property (body color of the bear candle). Gets/Sets the value of "ColorChartLine" property (color for line chart and Doji candles). Gets/Sets the value of "ColorVolumes" property (color for volumes and levels of opened positions). Gets/Sets the value of "ColorLineBid" property (color of Bid line). Gets/Sets the value of "ColorLineAsk" property
ColorForeground
ColorGrid
ColorBarUp
ColorBarDown
ColorCandleBull
ColorCandleBear
ColorChartLine
ColorVolumes
ColorLineBid
ColorLineAsk
1434
Standard Library
(color of Ask line). ColorLineLast Gets/Sets the value of "ColorLineLast" property (color of the last deal price line). Gets/Sets the value of "ColorStopLevels" property (color of the SL and TP levels).
ColorStopLevels
Read only properties VisibleBars WindowsTotal Gets total number of visible chart bars. Gets total number of chart windows, including the chart indicator subwindows. Gets visibility flag of the specified chart subwindow. Gets window handle of the chart (HWND). Gets the number of the first visible bar of the chart. Gets window width in bars. Gets subwindow width in pixels. Gets subwindow height in pixels. Gets minimal price of the specified subwindow. Gets maximal price of the specified subwindow.
WindowIsVisible
WindowHandle FirstVisibleBar
Assigns the current chart to the class instance. Assigns the first chart of the client terminal to the class instance. Assigns the next chart of the client terminal to the class instance. Opens chart with specified parameters and assign it to the class instance. Detaches chart from the class instance. Closes chart, assigned to the class instance.
NextChart
Open
Detach Close Navigation Navigate Access to MQL5 API Symbol Period Redraw
Gets symbol of the chart. Gets period of the chart. Redraws chart, assigned to the class instance.
1435
Standard Library
GetInteger
of
the
SetInteger
Sets new value for the property of the integer type. The function returns the value corresponding object property. of the
GetDouble
SetDouble
Sets new value for the property of the double type. The function returns the value corresponding object property. of the
GetString
SetString
Sets new value for the property of the string type. Changes symbol and period of the chart, assigned to the class instance. Applies specified template to the chart. Creates screenshot of the specified chart and saves it to .gif file. Gets chart subwindow number corresponding to the object (expert or script) drop point. Gets price coordinate corresponding to the object (expert or script) drop point. Gets time coordinate corresponding to the object (expert or script) drop point. Gets X coordinate corresponding to the object (expert or script) drop point. Gets Y coordinate corresponding to the object (expert or script) drop point.
SetSymbolPeriod
ApplyTemplate ScreenShot
WindowOnDropped
PriceOnDropped
TimeOnDropped
XOnDropped
YOnDropped
Input/Output virtual Save virtual Load virtual Type Saves object parameters to file. Loads object parameters from file. Gets graphic object type identifier.
1436
Standard Library
ChartID
Returns identifier of the chart.
long ChartID() const
Returned value Chart identifier, assigned to the class instance. If there is no object assigned, it returns -1.
1437
Standard Library
Returned value Value of "Mode" property of the object, assigned to the class instance. If there is no object assigned, it returns WRONG_VALUE.
Parameters mode [in] Chart mode (candle, bar or line) of ENUM_CHART_MODE enumeration. Returned value true if successful, false if mode hasn't changed.
1438
Standard Library
Returned value Value of "Foreground" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters foreground [in] New value for "Foreground" property. Returned value true if successful, false if property hasn't changed.
1439
Standard Library
Returned value Value of "Shift" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters shift [in] New value for "Shift" property. Returned value true if successful, false if property hasn't changed.
1440
Standard Library
Returned value Value of "ShiftSize" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters shift_size [in] New value for "ShiftSize" property (in percents). Returned value true if successful, false if property hasn't changed.
1441
Standard Library
Returned value Value of "AutoScroll" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters autoscroll [in] New value for "Autoscroll" property. Returned value true if successful, false if property hasn't changed.
1442
Standard Library
Returned value Value of "Scale" property of the object, assigned to the class instance. If there is no object assigned, it returns 0.
Parameters scale [in] New value for "Scale" property. Returned value true if successful, false if property hasn't changed.
1443
Standard Library
Returned value Value of "ScaleFix" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters scale_fix [in] New value for "ScaleFix" property. Returned value true if successful, false if property hasn't changed.
1444
Standard Library
Returned value Value of "ScaleFix_11" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters scale_11 [in] New value for "ScaleFix_11" property. Returned value true if successful, false if property hasn't changed.
1445
Standard Library
Returned value Value of "FixedMax" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters max [in] New value for "FixedMax" property. Returned value true if successful, false if property hasn't changed.
1446
Standard Library
Returned value Value of "FixedMin" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters max [in] New value for "FixedMin" property. Returned value true if successful, false if property hasn't changed.
1447
Standard Library
Returned value Value of "PointsPerBar" property of the object, assigned to the class instance. If there is no object assigned, it returns EMPTY_VALUE.
Parameters ppb [in] New value for scale (in points per bar). Returned value true if successful, false if scale hasn't changed.
1448
Standard Library
Returned value Value of "ScalePPB" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters scale_ppb [in] New value for "ScalePPB" property. Returned value true if successful, false if property hasn't changed.
1449
Standard Library
Returned value Value of "ShowOHLC" property of the object, assigned to the class instance. If there is no object assigned, it returns false.
Parameters show [in] New value for "ShowOHLC" property. Returned value true if successful, false if property hasn't changed.
1450
Standard Library
Returned value Value of "ShowLineBid" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowLineBid" property. Returned value true if successful, false if property hasn't changed.
1451
Standard Library
Returned value Value of "ShowLineAsk" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowLineAsk" property. Returned value true if successful, false if property hasn't changed.
1452
Standard Library
Returned value Value of "ShowLastLine" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowLastLine" property. Returned value true if successful, false if property hasn't changed.
1453
Standard Library
Returned value Value of "ShowPeriodSep" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowPeriodSep" property. Returned value true if successful, false if property hasn't changed.
1454
Standard Library
Returned value Value of "ShowGrid" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowGrid" property. Returned value true if successful, false if property hasn't changed.
1455
Standard Library
Returned value Value of "ShowVolumes" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowVolumes" property. Returned value true if successful, false if property hasn't changed.
1456
Standard Library
Returned value Value of "ShowObjectDescr" property of the chart, assigned to the class instance. If there is no chart assigned, it returns false.
Parameters show [in] New value for "ShowObjectDescr" property. Returned value true if successful, false if property hasn't changed.
1457
Standard Library
Returned value Value of "ColorBackground" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New background color. Returned value true if successful, false if color hasn't changed.
1458
Standard Library
Returned value Value of "ColorForeground" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color for axes, scale and OHLC string. Returned value true if successful, false if color hasn't changed.
1459
Standard Library
Returned value Value of "ColorGrid" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New grid color. Returned value true if successful, false if color hasn't changed.
1460
Standard Library
Returned value Value of "ColorBarUp" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color for bull bars. Returned value true if successful, false if color hasn't changed.
1461
Standard Library
Returned value Value of "ColorBarDown" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color for bear bars. Returned value true if successful, false if color hasn't changed.
1462
Standard Library
Returned value Value of "ColorCandleBull" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the bull candle body. Returned value true if successful, false if color hasn't changed.
1463
Standard Library
Returned value Value of "ColorCandleBear" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the bear candle body. Returned value true if successful, false if color hasn't changed.
1464
Standard Library
Returned value Value of "ColorChartLine" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the chart lines (Doji candles). Returned value true if successful, false if color hasn't changed.
1465
Standard Library
Returned value Value of "ColorVolumes" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the volumes (open position levels). Returned value true if successful, false if color hasn't changed.
1466
Standard Library
Returned value Value of "ColorLineBid" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color for Bid line. Returned value true if successful, false if color hasn't changed.
1467
Standard Library
Returned value Value of "ColorLineAsk" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color for Ask line. Returned value true if successful, false if color hasn't changed.
1468
Standard Library
Returned value Value of "ColorLineLast" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the last deal price line. Returned value true if successful, false if color hasn't changed.
1469
Standard Library
Returned value Value of "ColorStopLevels" property of the chart, assigned to the class instance. If there is no chart assigned, it returns CLR_NONE.
Parameters new_color [in] New color of the Stop Loss and Take Profit price levels. Returned value true if successful, false if color hasn't changed.
1470
Standard Library
VisibleBars
Gets total number of visible chart bars.
int VisibleBars() const
Returned value Gets total number of visible bars of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
1471
Standard Library
WindowsTotal
Gets total number of chart windows, including the chart indicator subwindows.
int WindowsTotal() const
Returned value Total number of windows, including the chart indicator subwindows, assigned to the class instance. If there is no chart assigned, it returns 0.
1472
Standard Library
WindowIsVisible
Gets visibility flag of the specified chart subwindow.
bool WindowIsVisible( int num ) const // subwindow number
Parameters num [in] Subwindow number (0 means base window). Returned value Returns visibility flag of the specified chart subwindow, assigned to the chart instance. If there is no chart assigned, it returns false.
1473
Standard Library
WindowHandle
Gets window handle of the chart (HWND).
int WindowHandle() const
Returned value Window handle of the chart, assigned to the chart instance. If there is no chart assigned, it returns INVALID_HANDLE.
1474
Standard Library
FirstVisibleBar
Gets the number of the first visible bar of the chart.
int FirstVisibleBar() const
Returned value Number of the first visible bar of the chart, assigned to the chart instance. If there is no chart assigned, it returns -1.
1475
Standard Library
WidthInBars
Gets window width in bars.
int WidthInBars() const
Returned value Window width in chart bars, assigned to the chart instance. If there is no chart assigned, it returns 0.
1476
Standard Library
WidthInPixels
Gets subwindow width in pixels.
int WidthInPixels() const
Returned value Subwindow width in chart pixels, assigned to the chart instance. If there is no chart assigned, it returns 0.
1477
Standard Library
HeightInPixels
Gets subwindow height in pixels.
int HeightInPixels( int num ) const // subwindow number
Parameters num [in] Subwindow number (0 means base window). Returned value Subwindow height in chart pixels, assigned to the chart instance. If there is no chart assigned, it returns 0.
1478
Standard Library
PriceMin
Gets minimal price of the specified subwindow.
double PriceMin( int num ) const // subwindow number
Parameters num [in] Subwindow number (0 means base window). Returned value Minimal price value of the chart, assigned to the class instance. If there is not chart assigned, it returns EMPTY_VALUE.
1479
Standard Library
PriceMax
Gets maximal price of the specified subwindow.
double PriceMax( int num ) const // subwindow number
Parameters num [in] Subwindow number (0 means base window). Returned value Maximal price value of the chart, assigned to the class instance. If there is not chart assigned, it returns EMPTY_VALUE.
1480
Standard Library
Attach
Assigns the current chart to the class instance.
void Attach()
Attach
Assigns the specified chart to the class instance.
void Attach( long chart ) // Chart identifier
1481
Standard Library
FirstChart
Assigns the first chart of the client terminal to the class instance.
void FirstChart()
1482
Standard Library
NextChart
Assigns the next chart of the client terminal to the class instance.
void NextChart()
1483
Standard Library
Open
Opens chart with specified parameters and assign it to the class instance.
long Open( const string symbol_name, // Symbol name // Period ENUM_TIMEFRAMES timeframe )
Parameters symbol_name [in] Symbol name. NULL means the symbol of the current chart (to which expert attached). timeframe [in] Chart timeframe (ENUM_TIMEFRAMES enumeration). 0 means the current timeframe. Returned value Chart identifier.
1484
Standard Library
Detach
Detaches chart from the class instance.
void Detach()
1485
Standard Library
Close
Closes chart, assigned to the class instance.
void Close()
1486
Standard Library
Navigate
Navigates the chart.
bool Navigate( ENUM_CHART_POSITION position, int ) shift=0 // Position // Shift
Parameters position [in] Value of ENUM_CHART_POSITION enumeration. shift=0 [in] Number of bars to shift. Returned value true if successful, false if chart hasn't navigated.
1487
Standard Library
Symbol
Gets symbol of the chart.
string Symbol() const
Returned value Symbol of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
1488
Standard Library
Period
Gets period of the chart.
ENUM_TIMEFRAMES Period() const
Returned value Period of the chart, assigned to the class instance. If there is no chart assigned, it returns 0.
1489
Standard Library
Redraw
Redraws chart, assigned to the class instance.
void Redraw()
1490
Standard Library
GetInteger
The function returns the value of the corresponding object property. The object property must be of the integer type. There are 2 variants of the function. 1. Immediately returns the property value.
long GetInteger( ENUM_CHART_PROPERTY_INTEGER prop_id, int ) const sub_window=0 // property identifier // subwindow number
2. If successful, puts the value of property to the specified variable of integer type, passed by reference as last parameter.
bool GetInteger( ENUM_CHART_PROPERTY_INTEGER prop_id, int long& ) const sub_window, value // property identifier // subwindow number // here we get the property value
Parameters prop_id [in] Property identifier (ENUM_CHART_PROPERTY_INTEGER enumeration). sub_window [in] Chart subwindow number. value [in] Variable of the integer type that received the value of the requested property. Return Value Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it returns -1. For the second variant the function returns true, if this property is maintained and the value has been placed into the value variable, otherwise returns false. To read more about the error call GetLastError().
1491
Standard Library
SetInteger
Sets new value for the property of the integer type.
bool SetInteger( ENUM_CHART_PROPERTY_INTEGER prop_id, long ) value // property identifier // new value
Parameters prop_id [in] Property identifier (ENUM_CHART_PROPERTY_INTEGER enumeration). value [in] New value of the property. Returned value true if successful, false if property of the integer type hasn't changed.
1492
Standard Library
GetDouble
The function returns the value of the corresponding object property. The object property must be of the double type. There are 2 variants of the function. 1. Immediately returns the property value.
double GetDouble( ENUM_CHART_PROPERTY_DOUBLE prop_id, int ) const sub_window=0 // property identifier // subwindow number
2. If successful, puts the value of property to the specified variable of double type, passed by reference as last parameter.
bool GetDouble( ENUM_CHART_PROPERTY_DOUBLE prop_id, int double& ) const sub_window, value // property identifier // subwindow number // here we get the property value
Parameters prop_id [in] Property identifier (ENUM_CHART_PROPERTY_DOUBLE enumeration). sub_window [in] Chart subwindow number. value [in] Variable of the double type that received the value of the requested property. Return Value Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it returns EMPTY_VALUE. For the second variant the function returns true, if this property is maintained and the value has been placed into the value variable, otherwise returns false. To read more about the error call GetLastError().
1493
Standard Library
SetDouble
Sets new value for the property of the double type.
bool SetDouble( ENUM_CHART_PROPERTY_DOUBLE prop_id, double ) value // property identifier // new value
Parameters prop_id [in] Property idenitifier (ENUM_CHART_PROPERTY_DOUBLE enumeration). value [in] New value for the property. Returned value true if successful, false if property of the double type hasn't changed.
1494
Standard Library
GetString
The function returns the value of the corresponding object property. The object property must be of the string type. There are 2 variants of the function. 1. Immediately returns the property value.
string GetString( ENUM_CHART_PROPERTY_STRING prop_id ) const // property identifier
2. If successful, puts the value of property to the specified variable of string type, passed by reference as last parameter.
bool GetString( ENUM_CHART_PROPERTY_STRING prop_id, string& ) const value // property identifier // here we get the property value
Parameters prop_id [in] Property identifier (ENUM_CHART_PROPERTY_STRING enumeration). sub_window [in] Chart subwindow number. value [in] Variable of the string type that received the value of the requested property. Return Value Value of property of the chart, assigned to the class instance. If there isn't any chart assigned, it returns "". For the second variant the function returns true, if this property is maintained and the value has been placed into the value variable, otherwise returns false. To read more about the error call GetLastError().
1495
Standard Library
SetString
Sets new value for the property of the string type.
bool SetString( ENUM_CHART_PROPERTY_STRING prop_id, string ) value // property identifier // new property value
Parameters prop_id [in] Property idenitifier (ENUM_CHART_PROPERTY_STRING enumeration). value [in] New value for the property. Returned value true if successful, false if property of the string type hasn't changed.
1496
Standard Library
SetSymbolPeriod
Changes symbol and period of the chart, assigned to the class instance.
bool SetSymbolPeriod( const string symbol_name, // Symbol // Period ENUM_TIMEFRAMES timeframe )
Parameters symbol_name [in] New symbol name. NULL means the symbol of the current chart (to which expert attached). timeframe [in] New chart timeframe (ENUM_TIMEFRAMES enumeration). 0 means the current timeframe. Returned value true if successful, false if property hasn't changed.
1497
Standard Library
ApplyTemplate
Applies specified template to the chart.
bool ApplyTemplate( const string filename ) // template file name
Parameters filename [in] File name of the template. Returned value true if successful, false if template hasn't applied.
1498
Standard Library
ScreenShot
Creates screenshot of the specified chart and saves it to .gif file.
bool ScreenShot( string int int filename, width, height, // File name // Width // Height // Align type
Parameters filename [in] File name for screenshot. width [in] Screenshot width in pixels. height [in] Screenshot height in pixels. align_mode=ALIGN_RIGHT [in] Align mode, if screenshot is narrow. Returned value true if successful, false if error.
1499
Standard Library
WindowOnDropped
Gets chart subwindow number corresponding to the object (expert or script) drop point.
int WindowOnDropped() const
Returned value Chart subwindow number of the object drop point. 0 means main chart window.
1500
Standard Library
PriceOnDropped
Gets price coordinate corresponding to the object (expert or script) drop point.
double PriceOnDropped() const
1501
Standard Library
TimeOnDropped
Gets time coordinate corresponding to the object (expert or script) drop point.
datetime TimeOnDropped() const
1502
Standard Library
XOnDropped
Gets X coordinate corresponding to the object (expert or script) drop point.
int XOnDropped() const
1503
Standard Library
YOnDropped
Gets Y coordinate corresponding to the object (expert or script) drop point.
int YOnDropped() const
1504
Standard Library
Save
Saves object parameters to file.
virtual bool Save( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen(...) function. Returned value true if successful, false if error.
1505
Standard Library
Load
Loads object parameters from file.
virtual bool Load( int file_handle ) // File handle
Parameters file_handle [in] handle of the binary file already opened by FileOpen(...) function. Returned value true if successful, false if error.
1506
Standard Library
Type
Returns graphic object type identifier.
virtual int Type() const
1507
Standard Library
File Operations
This section contains the technical details of the file operations classes and descriptions of the corresponding components of the standard MQL5 library. The file operations classes use will save time in developing applications which uses file input/output operations. The MQL5 Standard Library is placed in the working directory of the terminal in the Include\Files folder. Class CFile CFileBin CFileTxt Description Base file operations class Binary file operations class Text file operations class
1508
Standard Library
CFile
CFile is a base class for CFileBin and CFileTxt classes.
Description
Class CFile provides the simplified access for all of its descendants to MQL5 API file and folder functions.
Declaration
class CFile: public CObject
Title
#include <Files\File.mqh>
Class Methods
Attributes Handle Filename Flags SetUnicode SetCommon General methods for files Open Close Delete IsExist Copy Move Size Tell Seek Flush IsEnding IsLineEnding General methods for folders Opens file Closes file Deletes file Checks file for existence Copies file Renames/moves file Gets file size Gets current file position Sets current file position Flushes data on disk Checks file for end Checks line for end Gets file handle Gets file name Gets file flags Sets/Clears the FILE_UNICODE flag Sets/Clears the FILE_COMMON flag
1509
Standard Library
FolderCreate FolderDelete FolderClean Search methods FileFindFirst FileFindNext FileFindClose Derived classes: CFileBin CFileTxt
1510
Standard Library
Handle
Gets file handle of the opened file.
int Handle()
Returned value Handle of the opened file, assigned to the class instance. If there is no file assigned, it returns -1.
1511
Standard Library
FileName
Gets file name of the opened file.
string FileName()
Returned value File name of the opened file, assigned to the class instance. If there is no file assigned, it returns "".
1512
Standard Library
Flags
Gets flags of the opened file.
int Flags()
Returned value Flags of the opened file, assigned to the class instance.
1513
Standard Library
SetUnicode
Sets/Clears the FILE_UNICODE flag.
void SetUnicode( bool unicode ) // New flag value
Parameters unicode [in] New value for FILE_UNICODE flag. Note The result of string operations is dependent on the FILE_UNICODE flag. If it's false, the ANSI codes are used (one byte symbols). If it set, the UNICODE codes are used (two byte symbols). If the file has already opened, the flag cannot be changed.
1514
Standard Library
SetCommon
Sets/Clears the FILE_COMMON flag.
void SetCommon( bool common ) // New flag value
Parameters common [in] New value for FILE_COMMON flag. Note The FILE_UNICODE flag determines the current work folder. If it's false, the local terminal folder used as the current work folder. If it's true, the general folder used as the current work folder. If the file has already opened, the flag cannot be changed.
1515
Standard Library
Open
Open the specified file and if it successful, assigns it to the class instance.
int Open( const string file_name, int short ) flags, delimiter=9 // File name // Flags // Separator
Parameters file_name [in] File name to open. flags [in] File open flags. delimiter=9 [in] CSV file separator. Returned value Handle of the opened file. Note The work folder is dependent on the FILE_COMMON flag, defined by SetCommon() method.
1516
Standard Library
Close
Closes file, assigned to the class instance.
void Close()
1517
Standard Library
Delete
Deletes the file, assigned to the file instance.
void Delete()
Delete
Deletes the specified file.
void Delete( const string file_name ) // File name
Parameters file_name [in] File name of the file to delete. Note The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
1518
Standard Library
IsExist
Checks file for existence
bool IsExist( const string file_name ) // File name
Parameters file_name [in] Name of the file to check. Returned value true, if file exists.
1519
Standard Library
Copy
Copies a file.
bool Copy( const string src_name, int src_flag, // Source file name // Flag // Destination file name // Flags
Parameters src_name [in] File name of the file to copy. src_flag [in] Flags of the file to copy (only FILE_COMMON is used). dst_name [in] File name of the destination file. dst_flags [in] Flags of the destination file (only FILE_REWRITE and FILE_COMMON are used). Returned value true if successful, false if it hasn't been copied.
1520
Standard Library
Move
Renames/moves file.
bool Move( const string src_name, int src_flag, // Source file name // Flag // Destination file name // Flags
Parameters src_name [in] File name of the file to move. src_flag [in] Flags of the file to copy (only FILE_COMMON is used). dst_name [in] File name of the destination file. dst_flags [in] Flags of the destination file (only FILE_REWRITE and FILE_COMMON are used). Returned value true if successful, false if it hasn't been moved.
1521
Standard Library
Size
Gets file size in bytes.
ulong Size()
Returned value File size in bytes. If there isn't any file assigned, it returns ULONG_MAX.
1522
Standard Library
Tell
Gets the current file position.
ulong Tell()
Returned value The current file position. If there isn't any file assigned, it returns ULONG_MAX.
1523
Standard Library
Seek
Sets current file position.
void Seek( long offset, // Offset // Origin ENUM_FILE_POSITION origin )
Parameters offset [in] File offset in bytes (can be negative). origin [in] Origin of the offset. Returned value true if successful, false if file position hasn't been changed.
1524
Standard Library
Flush
Flushes all of the file input/output buffer data on disk.
void Flush()
1525
Standard Library
IsEnding
Checks file for end. It's used during the file read operations.
bool IsEnding()
Returned value true if end of file has been achieved after read or seek operation.
1526
Standard Library
IsLineEnding
Checks file for end of line. It's used during the file read operations.
bool IsLineEnding()
Returned value true if end of line has been achieved after the txt or csv file read operation (CR-LF chars).
1527
Standard Library
FolderCreate
Creates new folder.
bool FolderCreate( const string folder_name ) // Folder name
Parameters folder_name [in] Name of the folder to create. It contains path to the folder relative to the folder defined by FILE_COMMON flag. Returned value true if successful, and false if the folder hasn't been created. Note The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
1528
Standard Library
FolderDelete
Deletes specified folder.
bool FolderDelete( const string folder_name ) // Folder name
Parameters folder_name [in] Name of the folder to delete. It contains path to the folder relative to the folder defined by FILE_COMMON flag. Returned value true if successful, and false if the folder hasn't been deleted. Note The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
1529
Standard Library
FolderClean
Cleans specified folder.
bool FolderClean( const string folder_name ) // Folder name
Parameters folder_name [in] Name of the folder to delete. It contains path to the folder relative to the folder defined by FILE_COMMON flag. Returned value true if successful, and false if the folder hasn't been cleaned. Note The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
1530
Standard Library
FileFindFirst
It began file search using the filter specified.
int FileFindFirst( const string filter, string& ) file_name // Search Filter // Reference to string
Parameters filter [in] Search filter. file_name [out] The reference to string for the first file found. Returned value If successful, it returns handle, that can be used for further file search using FileFindNext, or INVALID_HANDLE if there isn't any file corresponding to the filter specified. Note The work folder is dependent on FILE_COMMON flag, defined by SetCommon() method.
1531
Standard Library
FileFindNext
It continue search, started by function FileFindFirst().
bool FileFindNext( int search_handle, // Search handle // Reference to string for the next file found string& file_name )
Parameters search_handle [in] Search handle, returned by FileFindFirst() method. file_name [in] The reference to string for the name of the file found if successful. Returned value true if successful, false if there isn't any file, corresponding to the filter specified.
1532
Standard Library
FileFindClose
Closes search handle.
void FileFindClose( int search_handle ) // Search handle
1533
Standard Library
CFileBin
CFileBin is a class for simplified access to binary files.
Description
Class CFileBin provides an access to binary files.
Declaration
class CFileBin: public CFile
Title
#include <Files\FileBin.mqh>
Class Methods
Open methods Open Write methods WriteChar WriteShort WriteInteger WriteLong WriteFloat WriteDouble WriteString WriteCharArray WriteShortArray Writes char or uchar type variable Writes short or ushort type variable Writes int or uint type variable Writes long or ulong type variable Writes float type variable Writes double type variable Writes string type variable Writes an array of char or uchar type variables Writes an array of short or ushort type variables Writes an array of int or uint type variables Writes an array of long or ulong type variables Writes an array of float variables Writes an array of double type variables Writes data of the CObject class inheritor instance Opens a binary file
Read methods ReadChar ReadShort Reads char or uchar type variable Reads short or ushort type variable
1534
Standard Library
ReadInteger ReadLong ReadFloat ReadDouble ReadString ReadCharArray ReadShortArray ReadIntegerArray ReadLongArray ReadFloatArray ReadDoubleArray ReadObject
Reads int or uint type variable Reads long or ulong type variable Reads float type variable Reads double type variable Reads string type variable Reads an array of char or uchar type variables Reads an array of short or ushort type variables Reads an array of int or uint type variables Reads an array of long or ulong type variables Reads an array of float type variables Reads an array of double type variables Reads data of the CObject class inheritor instance
1535
Standard Library
Open
Open the specified binary file and if it successful, assigns it to the class instance.
int Open( const string file_name, int ) flags // File name // Flags
Parameters file_name [in] File name of the file to open. flags [in] File open flags (there is a forced set of the FILE_BIN flag). Returned value Handle of the opened file.
1536
Standard Library
WriteChar
Writes char or uchar type variable to file.
uint WriteChar( char value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1537
Standard Library
WriteShort
Writes short or ushort type variable to file.
uint WriteShort( short value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1538
Standard Library
WriteInteger
Writes int or uint type variable to file.
uint WriteInteger( int value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1539
Standard Library
WriteLong
Writes long or ulong type variable to file.
uint WriteLong( long value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1540
Standard Library
WriteFloat
Writes float type variable to file.
uint WriteFloat( float value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1541
Standard Library
WriteDouble
Writes double type variable to file.
uint WriteDouble( double value ) // Value
Parameters value [in] Variable to write. Returned value Number of bytes written.
1542
Standard Library
WriteString
Writes string type variable to file.
uint WriteString( const string value ) // Value
Parameters value [in] String to write. Returned value Number of bytes written.
WriteString
Writes string type variable to file.
uint WriteString( const string value, int ) size // Value // Size
Parameters value [in] String to write. size [in] Number of bytes to write. Returned value Number of bytes written.
1543
Standard Library
WriteCharArray
Writes an array of char or uchar type variables to file.
uint WriteCharArray( char& array[], int int ) start_item=0, items_count=-1 // Array reference // Start element // Number of elements
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1544
Standard Library
WriteShortArray
Writes an array of short or ushort type variables to file.
uint WriteShortArray( short& array[], int int ) start_item=0, items_count=-1 // Array to write // Start element // Number of elements to write
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1545
Standard Library
WriteIntegerArray
Writes an array of int or uint type variables to file.
uint WriteIntegerArray( int& array[], int int ) start_item=0, items_count=-1 // Array to write // Start element // Number of elements to write
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1546
Standard Library
WriteLongArray
Writes an array of long or ulong type variables to file.
uint WriteLongArray( long& array[], int int ) start_item=0, items_count=-1 // Array to write // Start element // Number of elements to write
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1547
Standard Library
WriteFloatArray
Writes an array of float type variables to file.
uint WriteFloatArray( float& array[], int int ) start_item=0, items_count=-1 // Array to write // Start element // Number of elements to write
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1548
Standard Library
WriteDoubleArray
Writes an array of double type variables to file.
uint WriteDoubleArray( double& array[], int int ) start_item=0, items_count=-1 // Array to write // Start element // Number of elements to write
Parameters array[] [in] Array to write. start_item=0 [in] Start element to write from. items_count=-1 [in] Number of elements to write (-1 - for whole array). Returned value Number of bytes written.
1549
Standard Library
WriteObject
Writes data of the CObject class inheritor instance to file.
bool WriteObject( CObject* object ) // Reference to the object
Parameters object [in] Reference to the CObject class inheritor instance to write. Returned value true if successful, false if data hasn't been written.
1550
Standard Library
ReadChar
Reads char or uchar type variable from file.
bool ReadChar( char& value ) // Target variable
Parameters value [in] Target variable of type char. Returned value true if successful, false if data hasn't been read.
1551
Standard Library
ReadShort
Reads short or ushort type variable from file.
bool ReadShort( short& value )
Parameters value [in] Target variable of type short or ushort. Returned value true if successful, false if data hasn't been read.
1552
Standard Library
ReadInteger
Reads int or uint type variable from file.
bool ReadInteger( int& value ) // Target variable
Parameters value [in] Target variable of type int or uint. Returned value true if successful, false if data hasn't been read.
1553
Standard Library
ReadLong
Reads long or ulong type variable from file.
bool ReadLong( long& value )
Parameters value [in] Target variable of type long or ulong. Returned value true if successful, false if data hasn't been read.
1554
Standard Library
ReadFloat
Reads float type variable from file.
bool ReadFloat( float& value ) // Target variable
Parameters value [in] Target variable of type float. Returned value true if successful, false if data hasn't been read.
1555
Standard Library
ReadDouble
Reads double type variable from file.
bool ReadDouble( double& value )
Parameters value [in] Target variable of type double. Returned value true if successful, false if data hasn't been read.
1556
Standard Library
ReadString
Reads string type variable from file.
bool ReadString( string& value ) // Target string
Parameters value [in] Target variable of type string. Returned value true if successful, false if data hasn't been read.
ReadString
Reads string type variable from file.
bool ReadString( string& value )
Parameters value [in] Target variable of type string. Returned value true if successful, false if data hasn't been read.
1557
Standard Library
ReadCharArray
Reads an array of char or uchar type variables from file.
bool ReadCharArray( char& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type char or uchar. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1558
Standard Library
ReadShortArray
Reads an array of short or ushort type variables from file.
bool ReadShortArray( short& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type short or ushort. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1559
Standard Library
ReadIntegerArray
Reads an array of int or uint type variables from file.
bool ReadIntegerArray( int& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type int or uint. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1560
Standard Library
ReadLongArray
Reads an array of long or ulong type variables from file.
bool ReadLongArray( long& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type long or ulong. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1561
Standard Library
ReadFloatArray
Reads an array of float type variables from file.
bool ReadFloatArray( float& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type float. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1562
Standard Library
ReadDoubleArray
Reads an array of double type variables from file.
bool ReadDoubleArray( double& array[], int int ) start_item=0, items_count=-1 // Target array // Start element // Number of elements to read
Parameters array[] [in] Reference to the target array of type double. start_item=0 [in] Start element to read from. items_count=-1 [in] Number of elements to read (-1 - read to the end of file). Returned value true if successful, false if data hasn't been read.
1563
Standard Library
ReadObject
Reads data of the CObject class inheritor instance from file.
bool ReadObject( CObject* object ) // Reference to the object
Parameters object [in] Reference to the target CObject class inheritor instance for read to. Returned value true if successful, false if data hasn't been read.
1564
Standard Library
CFileTxt
CFileTxt is a class for simplified access to text files.
Description
Class CFileTxt provides an access to text files.
Declaration
class CFileTxt: public CFile
Title
#include <Files\FileTxt.mqh>
Class Methods
Open methods Open Write methods WriteString Read methods ReadString Reads string type variable from file Writes string type variable to file Open a text file
1565
Standard Library
Open
Open the specified text file and if it successful, assigns it to the class instance.
int Open( const string file_name, int ) flags // file name // flags
Parameters file_name [in] File name to open. flags [in] File open flags (there is a forced set of the FILE_TXT flag). Returned value Opened file handle.
1566
Standard Library
WriteString
Writes string type variable to file.
uint WriteString( const string value ) // String to write
Parameters value [in] String to write. Returned value Number of bytes written.
1567
Standard Library
ReadString
Reads string type variable from file.
string ReadString()
1568
Standard Library
String operations
This section contains the technical details of the string operations classes and descriptions of the corresponding components of the standard MQL5 library. The use of string operations classes will save time in developing applications which uses text processing operations. The MQL5 Standard Library is placed in the working directory of the terminal in the Include\Strings folder. Class CString Description Class for string operations
1569
Standard Library
CString
CString is a class for simplified access to the variables of string type.
Description
Class CFile provides the simplified access for all of its descendants to MQL5 API string functions.
Declaration
class CString: public CObject
Title
#include <Strings\String.mqh>
Class Methods
Data access methods Str Len Copy Fill methods Fill Assign Append Insert Compare methods Compare CompareNoCase Substring methods Left Gets a specified number of characters from the left side of a string Gets a specified number of characters from the right side of a string Gets a specified number of characters from a string Compares a string Compares a strings case insensitive Fills a string with specified char Assigns a string Appends a string Inserts a string Gets a string Gets length of a string Copies a string
Right
Mid
Trim/delete methods Trim Removes all leading and trailing occurrences of a set of specified characters from a string
1570
Standard Library
TrimLeft
Removes all leading occurrences of a set of specified characters from a string Removes all trailing occurrences of a set of specified characters from a string Clears a string
TrimRight
Clear Convert methods ToUpper ToLower Reverse Search methods Find FindRev Remove Replace
Searches for the first match of a substring Searches for the last match of a substring Deletes a substring from a string Replaces a substring
1571
Standard Library
Str
Gets a string.
string Str() const;
1572
Standard Library
Len
Gets length of a string.
uint Len() const;
1573
Standard Library
Copy
Copies a string by reference.
void Copy( string& copy ) const; // Reference
Copy
Copies a string to the CString class instance.
void Copy( CString* copy ) const; // Object descriptor
1574
Standard Library
Fill
Fills a string with specified char.
bool Fill( short character ) // Character
Parameters character [in] Character for filling. Returned value true if successful, false if a string hasn't been filled.
1575
Standard Library
Assign
Assigns a string.
void Assign( const string str ) // String to assign
Assign
Assigns a string to the CString class instance.
void Assign( CString* str ) // Object descriptor
1576
Standard Library
Append
Appends a string.
void Append( const string str ) // String to append
Append
Appends a string to the CString class instance.
void Append( CString* string ) // Object descriptor
1577
Standard Library
Insert
Inserts a string to the specified position.
uint Insert( uint pos, // Position // String to insert const string str )
Parameters pos [in] Insert position. str [in] String to insert. Returned value Resulted string length.
Insert
Inserts a string to the specified position to the CString class instance.
uint Insert( uint pos, // Position // Object descriptor CString* str )
Parameters pos [in] Insert position. str [in] CString class object descriptor to insert. Returned value Resulted string length.
1578
Standard Library
Compare
Compares a string.
int Compare( const string str ) const; // String to compare
Parameters str [in] String to compare. Returned value I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if the class string greater than a string to compare.
Compare
Compares a string with a string of the CString class instance.
int Compare( CString* str ) const; // Object descriptor
Parameters str [in] CString class object descriptor to compare. Returned value I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if the class string greater than a string to compare.
1579
Standard Library
CompareNoCase
Compares a strings case insensitive.
int CompareNoCase( const string str ) const; // String to compare
Parameters str [in] String to compare. Returned value I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if the class string greater than a string to compare.
CompareNoCase
Compares a string (case insensitive) with a string of the CString class instance.
int CompareNoCase( CString* str ) const; // Object descriptor
Parameters str [in] CString class object descriptor to compare. Returned value I returns 0 if a strings are equal, -1 if a string of the class is lower than a string to compare, -1 if the class string greater than a string to compare.
1580
Standard Library
Left
Gets a specified number of characters from the left side of a string.
string Left( uint count ) // Number of characters
1581
Standard Library
Right
Gets a specified number of characters from the right side of a string.
string Right( uint count ) // Number of characters
1582
Standard Library
Mid
Gets a specified number of characters from a string.
string Mid( uint pos, uint count ) // Position // Number of characters
Parameters pos [in] Position of a string. count [in] Number of characters. Returned value Resulted substring.
1583
Standard Library
Trim
Removes all leading and trailing occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int Trim( const string targets ) // Set of characters to remove
Parameters targets [in] Set of characters to remove. Returned value Number of characters removed.
Example:
//--- example for CString::Trim #include <Strings\String.mqh> //--void OnStart() { CString str; //--str.Assign(" //--str.Trim("DA-DA-DA"); printf("Result string '%s'",str.Str()); } \t\tABCD\r\n"); printf("Source string '%s'",str.Str());
1584
Standard Library
TrimLeft
Removes all leading occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimLeft( const string targets ) // Set of characters to remove
Parameters targets [in] Set of characters to remove. Returned value Number of characters removed.
1585
Standard Library
TrimRight
Removes all trailing occurrences of a set of specified characters (and ' ','\t','\r','\n') from a string.
int TrimRight( const string targets ) // Set of characters to remove
Parameters targets [in] Set of characters to remove. Returned value Number of characters removed.
1586
Standard Library
Clear
Clears a string.
bool Clear()
1587
Standard Library
ToUpper
Converts a string to uppercase.
bool ToUpper()
1588
Standard Library
ToLower
Converts a string to lowercase.
bool ToLower()
1589
Standard Library
Reverse
Reverses of a string.
void Reverse()
1590
Standard Library
Find
Searches for the first match of a substring.
int Find( uint start, // Position // Substring to search for const string substring ) const;
Parameters start [in] The index of the character in the string to begin the search with, or 0 to start from the beginning. substring [in] Substring to search for. Returned value The index of the first character that matches the requested substring; -1 if the substring is not found.
1591
Standard Library
FindRev
Searches for the last match of a substring.
int FindRev( const string substring ) const; // Substring
Parameters substring [in] A substring to search for. Returned value The index of the last character that matches the requested substring; -1 if the substring is not found.
1592
Standard Library
Remove
Deletes a substring from a string.
uint Remove( const string substring ) // Substring to remove
Parameters substring [in] A substring to search for. Returned value Number of substrings deleted.
1593
Standard Library
Replace
Replaces a substring from a string.
uint Replace( const string substring, const string newstring ) // Substring to replace // New substring
Parameters substring [in] A substring to search for. newstring [in] A substring to replace for. Returned value Number of substrings replaced.
1594
Standard Library
1595
Standard Library
1596
Standard Library
CSpreadBuffer
CSpreadBuffer is a class for simplified access to spreads of the bars in the history.
Description
The CSpreadBuffer class provides an access to spreads of the bars in the history.
Declaration
class CSpreadBuffer: public CArrayInt
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes Size Settings SetSymbolPeriod Data Access Methods At Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value Gets the buffer element by index Sets symbol and period Sets buffer size
1597
Standard Library
Size
Sets buffer size.
void Size( int size ) // new size
1598
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] New symbol. period [in] New period (ENUM_TIMEFRAMES enumeration).
1599
Standard Library
At
Gets the buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1600
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1601
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1602
Standard Library
CTimeBuffer
CTimeBuffer is a class for simplified access to opening times of the bars in the history.
Description
The CTimeBuffer class provides an access to opening times of the bars in the history.
Declaration
class CTimeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes Size Settings SetSymbolPeriod Data Access Methods At Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value Gets the buffer element by index Sets symbol and period Sets buffer size
1603
Standard Library
Size
Sets buffer size.
void Size( int size ) // new size
1604
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] New symbol. period [in] New period (ENUM_TIMEFRAMES enumeration).
1605
Standard Library
At
Gets the buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1606
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1607
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1608
Standard Library
CTickVolumeBuffer
CTickVolumeBuffer is a class for simplified access to tick volumes of bars in the history.
Description
The CTickVolumeBuffer class provides an access to tick volumes of bars in the history.
Declaration
class CTickVolumeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes Size Settings SetSymbolPeriod Data Access Methods At Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value Gets the buffer element by index Sets symbol and period Sets buffer size
1609
Standard Library
Size
Sets buffer size.
void Size( int size ) // new size
1610
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] New symbol. period [in] New period (ENUM_TIMEFRAMES enumeration).
1611
Standard Library
At
Gets the buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1612
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1613
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1614
Standard Library
CRealVolumeBuffer
CRealVolumeBuffer is a class for simplified access to real volumes of bars in the history.
Description
The CTickVolumeBuffer class provides an access to real volumes of bars in the history.
Declaration
class CRealVolumeBuffer: public CArrayLong
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes Size Settings SetSymbolPeriod Data Access Methods At Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value Gets the buffer element by index Sets symbol and period Sets buffer size
1615
Standard Library
Size
Sets buffer size.
void Size( int size ) // new size
1616
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] New symbol. period [in] New period (ENUM_TIMEFRAMES enumeration).
1617
Standard Library
At
Gets the buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1618
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1619
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1620
Standard Library
CDoubleBuffer
CDoubleBuffer is a base class for simplified access to data buffers of double type.
Description
The CDoubleBuffer class provides an access to the data of the buffer of double type.
Declaration
class CDoubleBuffer: public CArrayDouble
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Attributes Size Settings SetSymbolPeriod Data Access Methods At Data Update Methods virtual Refresh virtual RefreshCurrent Data Search Methods Minimum Gets index of the lowest element of the buffer in the specified range Gets index of the highest element of the buffer in the specified range Updates the buffer Updates the current value Gets the buffer element Sets symbol and period Sets buffer size
Maximum
1621
Standard Library
Size
Sets buffer size.
void Size( int size ) // new size
1622
Standard Library
SetSymbolPeriod
Sets symbol and period.
void SetSymbolPeriod( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] New symbol. period [in] New period (ENUM_TIMEFRAMES enumeration).
1623
Standard Library
At
Gets the buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1624
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1625
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1626
Standard Library
Minimum
Gets index of the lowest element of the buffer in the specified range.
int Minimum( int start, int count ) const // starting index // number of elements to proceed
Parameters start [in] Starting index of the array. count [in] Number of elements to proceed. Returned value Index of the lowest element of the buffer in the specified range.
1627
Standard Library
Maximum
Gets index of the highest element of the buffer in the specified range.
int Maximum( int start, int count ) const // starting index // number of elements to proceed
Parameters start [in] Starting index of the array. count [in] Number of elements to proceed. Returned value Index of the highest element of the buffer in the specified range.
1628
Standard Library
COpenBuffer
COpenBuffer is a class for simplified access to open prices of bars in the history.
Description
The COpenBuffer class provides an access to open prices of bars in the history.
Declaration
class COpenBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value
1629
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1630
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1631
Standard Library
CHighBuffer
CHighBuffer is a class for simplified access to high prices of bars in the history.
Description
The CHighBuffer class provides an access to high prices of bars in the history.
Declaration
class CHighBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value
1632
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1633
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1634
Standard Library
CLowBuffer
CLowBuffer is a class for simplified access to low prices of bars in the history.
Description
The CLowBuffer class provides an access to low prices of bars in the history.
Declaration
class CLowBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value
1635
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1636
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1637
Standard Library
CCloseBuffer
CCloseBuffer is a class for simplified access to close prices of bars in the history.
Description
The CCloseBuffer class provides an access to close prices of bars in the history.
Declaration
class CCloseBuffer: public CDoubleBuffer
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Data Update Methods virtual Refresh virtual RefreshCurrent Updates the buffer Updates the current value
1638
Standard Library
Refresh
Updates the buffer.
virtual bool Refresh()
Returned value true if successful, false if the buffer hasn't been updated.
1639
Standard Library
RefreshCurrent
Updates the current (zeroth) element of the buffer.
virtual bool RefreshCurrent()
Returned value true if successful, false if the buffer hasn't been updated.
1640
Standard Library
CIndicatorBuffer
CIndicatorBuffer is a class for simplified access to the data of the indicator's buffer.
Description
The CIndicatorBuffer class provides the simplified access to the data buffer of technical indicator.
Declaration
class CIndicatorBuffer: public CDoubleBuffer
Title
#include <Indicators\Indicator.mqh>
Class Methods
Attributes Offset Name Data Access Methods At Data Update Methods Refresh RefreshCurrent Updates the buffer Updates only current value Gets buffer's element Gets/Sets offset of the buffer Gets/Sets buffer name
1641
Standard Library
Offset
Gets offset of the buffer.
int Offset() const
Offset ()
Sets offset of the buffer.
void Offset( int offset ) // offset
1642
Standard Library
Name
Gets the name of the buffer.
string Name() const
Name
Sets the name of the buffer.
void Name( string name ) // name
1643
Standard Library
At
Gets buffer element by index.
long At( int index ) // index
Parameters index [in] Index of buffer element. Returned value Buffer element with the specified index.
1644
Standard Library
Refresh
Updates the whole buffer.
bool Refresh( int handle, int num ) // handle // buffer number
Parameters handle [in] Handle of the indicator. num [in] Buffer index of the indicator. Returned value true if successful, false if the buffer hasn't been updated.
1645
Standard Library
RefreshCurrent
Updates the current (zeroth) buffer element.
bool RefreshCurrent( int handle, int num ) // handle of the indicator // buffer number
Parameters handle [in] Handle of the indicator. num [in] Buffer number. Returned value true if successful, false if the buffer hasn't been updated.
1646
Standard Library
CSeries
CSeries is a base class for an access to the timeseries data of the Standard Library.
Description
The CSeries class provides the simplified access to MQL5 timeseries functions to all its descendants.
Declaration
class CSeries: public CArrayObj
Title
#include <Indicators\Series.mqh>
Class Methods
Attributes Name BuffersTotal Gets the name of timeseries or indicator Gets the number of buffers of timeseries or indicator Gets the timeframe flag of timeseries or indicator Gets the symbol of timeseries or indicator Gets the period of timeseries or indicator Gets/Sets the flag of updating the current data
Timeframe
Symbol Period RefreshCurrent Data Access Methods virtual BufferResize Data Update Methods virtual Refresh PeriodDescription
1647
Standard Library
Name
Gets the name of timeseries or indicator
string Name() const
1648
Standard Library
BuffersTotal
Gets the number of buffers of timeseries or indicator.
int BuffersTotal() const
Returned value The number of buffers of timeseries or indicator. Note The timeseries has an only one buffer.
1649
Standard Library
Timeframe
Gets the timeframe flag of timeseries or indicator.
int Timeframe() const
Returned value The timeframe flag of timeseries or indicator. Note It's the visibility flag of some timeframes.
1650
Standard Library
Symbol
Gets the symbol of timeseries or indicator.
string Symbol() const
1651
Standard Library
Period
Gets the period of timeseries or indicator.
ENUM_TIMEFRAMES Period() const
1652
Standard Library
RefreshCurrent
Sets a flag to update the current values of timeseries or indicator.
string RefreshCurrent( bool flag ) // new flag
1653
Standard Library
BufferResize
Sets buffer size of timeseries or indicator.
virtual void BufferResize( int size ) // new size
Parameters size [in] New size of the buffers. Note All the buffers have the same buffer size.
1654
Standard Library
Refresh
Updates the data of timeseries or indicator.
virtual void Refresh( int flags ) // flags
1655
Standard Library
PeriodDescription
Gets the string representation of the specified ENUM_TIMEFRAMES enumeration.
string PeriodDescription( int val==0 ) const // value
Parameters val==0 [in] Value to convert. Returned value The string representation of the specified ENUM_TIMEFRAMES enumeration. Note If the value isn't specified or equal to zero, it returns the timeframe of timeseries or indicator.
1656
Standard Library
CPriceSeries
CPriceSeries is a base class for access to the price data.
Description
The CSeries class provides the simplified access to MQL5 functions for working with price data to all its descendants.
Declaration
class CPriceSeries: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods virtual BufferResize Data Access Methods virtual GetData Data Update Methods virtual Refresh Data Search Methods virtual MinIndex Gets the index of minimal element in the specified range Gets the value and index of minimal element in the specified range Gets the index of maximal element in the specified range Gets the value and index of maximal element in the specified range Updates timeseries data Gets the specified buffer element by index Sets size of the buffer
virtual MinValue
virtual MaxIndex
virtual MaxValue
1657
Standard Library
BufferResize
Sets new size of the buffer.
virtual void BufferResize( int size ) // new size
1658
Standard Library
GetData
Gets the specified buffer element by index.
virtual double GetData( int index ) const // index
Parameters index [in] Index of buffer element. Returned value The buffer element with the specified index or EMPTY_VALUE.
1659
Standard Library
Refresh
Updates the timeseries data
virtual void Refresh( int flags ) // timeframe flags
1660
Standard Library
MinIndex
Gets the index of minimal element in the specified range.
virtual int MinIndex( int start, int count ) const // starting index // number of elements to scan
Parameters start [in] Starting index. count [in] Number of elements to proceed. Returned value The index of minimal element in the specified range, or -1 in the case of error.
1661
Standard Library
MinValue
Gets the value and index of minimal element in the specified range.
virtual double MinValue( int int start, count, // starting index // number of elements to scan // reference to the variable for index
Parameters start [in] Starting index. count [in] Number of elements to proceed. index [out] Reference to the variable of integer type. Returned value The value of minimal element of the buffer in the specified range, or EMPTY_VALUE if error. Note The index of minimal element is stored in the variable index.
1662
Standard Library
MaxIndex
Gets the index of maximal element in the specified range.
virtual int MaxIndex( int start, int count ) const // starting index // number of elements to scan
Parameters start [in] Starting index. count [in] Number of elements to proceed. Returned value The index of the maximal element in the specified range, or -1 in the case of error.
1663
Standard Library
MaxValue
Gets the value and index of maximal element in the specified range.
virtual double MaxValue( int int start, count, // starting index // number of elements to scan // reference to the variable for index
Parameters start [in] Starting index. count [in] Number of elements to proceed. index [out] Reference to the variable of integer type. Returned value The value of maximal element of the buffer in the specified range, or EMPTY_VALUE if error. Note The index of maximal element is stored in the variable index.
1664
Standard Library
CIndicator
CIndicator is a base class for technical indicator classes of the standard MQL Library.
Description
The CIndicator class provides the simplified access for all of its descendants to MQL5 API technical indicator functions.
Declaration
class CIndicator: public CSeries
Title
#include <Indicators\Indicator.mqh>
Class Methods
Attributes Handle Status FullRelease Gets the indicator's handle. Gets the status of the indicator. Sets a flag to release the handle of the indicator.
Creation Create BufferResize Data Access Methods GetData Data Update Methods Refresh Finding Min/Max Values Minimum Gets the index of minimal element of the specified buffer in a specified range. Gets the value and index of minimal element of the specified buffer in a specified range. Gets the index of maximal element of the specified buffer in a specified range. Gets the value and index of maximal element of the specified buffer in a specified range. Updates the indicator's data Copying the data from the indicator's buffer Creates the indicators Sets new buffer size
MinValue
Maximum
MaxValue
Conversion of Enumerations
1665
Standard Library
MethodDescription
Gets the value of enumeration as string Gets the value of enumeration as string
ENUM_MA_METHOD
PriceDescription
ENUM_APPLIED_PRICE
VolumeDescription
Derived classes: CiAC CiAD CiADX CiADXWilder CiAlligator CiAMA CiAO CiATR CiBands CiBearsPower CiBullsPower CiBWMFI CiCCI CiChaikin CiDEMA CiDeMarker CiEnvelopes CiForce CiFractals CiFrAMA CiGator CiIchimoku CiMA CiMACD CiMFI CiMomentum CiOBV CiOsMA CiRSI CiRVI CiSAR
1666
1667
Standard Library
Handle
Gets the indicator's handle.
int Handle() const
1668
Standard Library
Status
Gets the status of the indicator.
string Status() const
1669
Standard Library
FullRelease
Sets a flag to release the handle of the indicator.
void FullRelease( bool flag ) // flag
1670
Standard Library
Create
Creates the indicator with specified parameters.
bool Create( string symbol, // symbol // period // type // number of parameters // reference to the parameters array ENUM_TIMEFRAMES period, ENUM_INDICATOR int MqlParam& ) type, num_params, params
Parameters symbol [in] Symbol name. period [in] Period (ENUM_TIMEFRAMES enumeration). type [in] Indicator's type (ENUM_INDICATOR enumeration). num_params [in] Number of indicator's parameters. params [in] Reference to the parameters array for the indicator. Returned value true if successful, false if indicator hasn't been created.
1671
Standard Library
BufferResize
Sets the size of the indicator's buffer.
void BufferResize( int size ) // new size
Parameters size [in] New buffer size. Note All the indicator's buffers have the same size.
1672
Standard Library
GetData
Gets the specified element from the specified buffer of the indicator.
double GetData( int buffer_num, int index ) const // buffer number // element index
Parameters buffer_num [in] Buffer number. index [in] Element index. Returned value The numerical value of element if successful, or EMPTY_VALUE in the case of error.
GetData
Gets the data from the indicator's buffer by starting position and number of necessary data.
int GetData( int int int start_pos, count, buffer_num, // position // number of elements needed // buffer number // target array for data
Parameters start_pos [in] Starting position of the indicator's buffer. count [in] Number of elements needed. buffer_num [in] Number of the indicator's buffer. buffer [in] Referencet to the target array for the data. Returned value true if successful, false if data hasn't been provided.
GetData
Gets the data from the indicator's buffer by start time and number of necessary data.
1673
Standard Library
int GetData( datetime start_time, int int double& ) const count, buffer_num, buffer // starting time // number of elements needed // buffer number // target array for data
Parameters start_time [in] Starting time. count [in] Number of elements needed. buffer_num [in] Number of the indicator's buffer. buffer [in] Reference to the target array. Returned value true if successful, false if data hasn't been provided.
GetData
Gets the data from the indicator's buffer by start and stop time and number of necessary data.
int GetData( datetime start_time, datetime stop_time, int double& ) const buffer_num, buffer // start time // stop time // number of buffer // target array for data
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer_num [in] Number of the indicator's buffer. buffer [in] Reference to the target array. Returned value true if successful, false if data hasn't been provided.
1674
Standard Library
1675
Standard Library
Refresh
Updates the indicator's data.
void Refresh( int flags ) // flags
1676
Standard Library
Minimum
Returns the index of minimal element of the specified buffer in a specified range.
int Minimum( int buffer_num, int start, int count ) const // buffer number // starting index // number of elements to proceed
Parameters buffer_num [in] Buffer number to search the value in. start [in] Starting index of the search. count [in] Number of elements to search. Returned value Index of the minimal element of the specified buffer in a specified range.
1677
Standard Library
MinValue
Returns the value and index of minimal element of the specified buffer in a specified range.
double MinValue( int int int buffer_num, start, count, // buffer number // starting index // number of elements to proceed // reference
Parameters buffer_num [in] Buffer number to search the value in. start [in] Starting index. count [in] Number of elements to proceed. index [out] Reference to the variable of int type for the minimal element index. Returned value The value of the minimal element of the specified buffer in a specified range. Note The index of minimal buffer element is stored into the variable index, passed by reference.
1678
Standard Library
Maximum
Returns the index of maximal element of the specified buffer in a specified range.
int Maximum( int buffer_num, int start, int count ) const // buffer number // starting index // number of elements to proceed
Parameters buffer_num [in] Buffer number to search the value in. start [in] Starting index of the search. count [in] Number of elements to search. Returned value Index of the maximal element of the specified buffer in a specified range.
1679
Standard Library
MaxValue
Returns the value and index of maximal element of the specified buffer in a specified range.
double MaxValue( int int int buffer_num, start, count, // buffer number // starting index // number of elements to proceed // reference
Parameters buffer_num [in] Buffer number to search the value in. start [in] Starting index. count [in] Number of elements to proceed. index [out] Reference to the variable of int type for the maximal element index. Returned value The value of the maximal element of the specified buffer in a specified range. Note The index of maximal buffer element is stored into the variable index, passed by reference.
1680
Standard Library
MethodDescription
The function returns the value of ENUM_MA_METHOD enumeration as a string.
string MethodDescription( int val==0 ) const // value
Parameters val==0 [in] Value of ENUM_MA_METHOD enumeration. Returned value The value of ENUM_MA_METHOD enumeration as a string.
1681
Standard Library
PriceDescription
The method returns the value of ENUM_APPLIED_PRICE enumeration as a string.
string PriceDescription( int val==0 ) const // value
Parameters val==0 [in] Value of ENUM_APPLIED_PRICE enumeration. Returned value The value of ENUM_APPLIED_PRICE enumeration as a string.
1682
Standard Library
VolumeDescription
The method returns the value of ENUM_APPLIED_VOLUME enumeration as a string.
string VolumeDescription( int val==0 ) const // value
Parameters val==0 [in] Value of ENUM_APPLIED_VOLUME enumeration. Returned value The value of ENUM_APPLIED_VOLUME enumeration as a string.
1683
Standard Library
CIndicators
The CIndicators is a class for collecting instances of timeseries and technical indicators classes.
Description
The CIndicators class provides creation of the technical indicators class instances, their storage and management (data synchronization, handle and memory management).
Declaration
class CIndicators: public CArrayObj
Title
#include <Indicators\Indicators.mqh>
Class Methods
Create Methods Create Data Update Methods Refresh Updates data for all technical indicators in the collection Creates technical indicator
1684
Standard Library
Create
It creates the indicator with the specified parameters.
CIndicator* Create( string symbol, // Symbol name // Period // Indicator's type // Number of parameters // Parameters array reference ENUM_TIMEFRAMES period, ENUM_INDICATOR int MqlParam& ) type, count, params
Parameters symbol [in] Symbol name. period [in] Period (ENUM_TIMEFRAMES enumeration). type [in] Indicator's type (ENUM_INDICATOR). count [in] Number of parameters for the indicator. params [in] Reference to the parameters array for the indicator. Returned value If successful, it returns the reference to the created indicator, and NULL if the indicator hasn't been created.
1685
Standard Library
Refresh
Updates data for all technical indicators in the collection.
int Refresh()
Returned value It returns the updated timeframe flags (formed as an object visibility flags).
1686
Standard Library
Timeseries classes
This group of chapters contains technical details of timeseries classes of the MQL5 Standard Library and descriptions of all its key components. Class CiSpread CiTime Description Provides an access to spread historical data Provides an access to open times of the bars in the history Provides an access to tick volumes of the bars in the history Provides an access to real volumes of the bars in the history Provides an access to open prices of the bars in the history Provides an access to high prices of the bars in the history Provides an access to low prices of the bars in the history Provides an access to close prices of the bars in the history
CiTickVolume
CiRealVolume
CiOpen
CiHigh
CiLow
CiClose
1687
Standard Library
CiSpread
CiSpread is a class designed for access to spreads of the bars in the history.
Description
The CiSpread class provides an access to spread historical data.
Declaration
class CiSpread: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create BufferResize Data Access Methods GetData Data Update Methods Refresh Updates the data Gets the data Creates a timeseries Sets buffer size
1688
Standard Library
Create
Creates a timeseries with the specified parameters for access to the spreads history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1689
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize( int size ) // new size
1690
Standard Library
GetData
Gets the element of timeseries by index.
int GetData( int index ) const // index
Parameters index [in] Index of the element needed. Returned value The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int int& ) const count, buffer // starting time // number of elements // target array
Parameters
1691
Standard Library start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData( datetime start_time, datetime stop_time, int& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1692
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh( int flags ) // flags
1693
Standard Library
CiTime
CiTime is a class designed for access to open times of the bars in the history.
Description
The CiTime class provides an access to open times of the bars in the history.
Declaration
class CiTime: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create BufferResize Data Access Methods GetData Data Update Methods Refresh Updates the data Gets the data Creates a timeseries Sets buffer size
1694
Standard Library
Create
Creates a timeseries with the specified parameters for access to the opening times of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1695
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize( int size ) // new size
1696
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData( int index ) const // index
Parameters index [in] Index of the element needed. Returned value The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int long& ) const count, buffer // starting time // number of elements // target array
Parameters
1697
Standard Library start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData( datetime start_time, datetime stop_time, long& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1698
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh( int flags ) // flags
1699
Standard Library
CiTickVolume
CiTickVolume is a class designed for access to tick volumes of the bars in the history.
Description
The CiTickVolume class provides an access to tick volumes of the bars in the history.
Declaration
class CiTickVolume: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create BufferResize Data Access Methods GetData Data Update Methods Refresh Updates the data Gets the data Creates a timeseries Sets buffer size
1700
Standard Library
Create
Creates a timeseries with the specified parameters for access to the tick volumes of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1701
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize( int size ) // new size
1702
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData( int index ) const // index
Parameters index [in] Index of the element needed. Returned value The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int long& ) const count, buffer // starting time // number of elements // target array
Parameters
1703
Standard Library start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData( datetime start_time, datetime stop_time, long& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1704
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh( int flags ) // flags
1705
Standard Library
CiRealVolume
CiRealVolume is a class designed for access to real volumes of the bars in the history.
Description
The CiRealVolume class provides an access to real volumes of the bars in the history.
Declaration
class CiRealVolume: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create BufferResize Data Access Methods GetData Data Update Methods Refresh Updates the data Gets the data Creates a timeseries Sets buffer size
1706
Standard Library
Create
Creates a timeseries with the specified parameters for access to the real volumes of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1707
Standard Library
BufferResize
Sets new size of the series.
virtual void BufferResize( int size ) // new size
1708
Standard Library
GetData
Gets the element of timeseries by index.
datetime GetData( int index ) const // index
Parameters index [in] Index of the element needed. Returned value The timeseries buffer element, or 0.
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int long& ) const count, buffer // starting time // number of elements // target array
Parameters
1709
Standard Library start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
int GetData( datetime start_time, datetime stop_time, long& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1710
Standard Library
Refresh
Updates the data of timeseries.
virtual void Refresh( int flags ) // flags
1711
Standard Library
CiOpen
CiOpen is a class designed for access to open prices of the bars in the history.
Description
The CiOpen class provides an access to open prices of the bars in the history.
Declaration
class CiOpen: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create Data Access Methods GetData Gets the data Creates a timeseries
1712
Standard Library
Create
Creates a timeseries with the specified parameters for access to the open prices of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1713
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int double& ) const count, buffer // starting time // number of elements // target array
Parameters start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
1714
Standard Library
int GetData( datetime start_time, datetime stop_time, double& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1715
Standard Library
CiHigh
CiHigh is a class designed for access to high prices of the bars in the history.
Description
The CiHigh class provides an access to high prices of the bars in the history.
Declaration
class CiHigh: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create Data Access Methods GetData Gets the data Creates a timeseries
1716
Standard Library
Create
Creates a timeseries with the specified parameters for access to the high prices of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1717
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int double& ) const count, buffer // starting time // number of elements // target array
Parameters start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
1718
Standard Library
int GetData( datetime start_time, datetime stop_time, double& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1719
Standard Library
CiLow
CiLow is a class designed for access to low prices of the bars in the history.
Description
The CiLow class provides an access to low prices of the bars in the history.
Declaration
class CiLow: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create Data Access Methods GetData Gets the data Creates a timeseries
1720
Standard Library
Create
Creates a timeseries with the specified parameters for access to the low prices of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1721
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int double& ) const count, buffer // starting time // number of elements // target array
Parameters start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
1722
Standard Library
int GetData( datetime start_time, datetime stop_time, double& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1723
Standard Library
CiClose
CiClose is a class designed for access to close prices of the bars in the history.
Description
The CiClose class provides an access to close prices of the bars in the history.
Declaration
class CiClose: public CSeries
Title
#include <Indicators\TimeSeries.mqh>
Class Methods
Create Methods Create Data Access Methods GetData Gets the data Creates a timeseries
1724
Standard Library
Create
Creates a timeseries with the specified parameters for access to the closing prices of the bars in the history.
bool Create( string symbol, // symbol // period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if timeseries hasn't been created.
1725
Standard Library
GetData
Gets the element of timeseries by starting position and number of elements.
int GetData( int int start_pos, count, // starting position // number of elements to get // target array
Parameters start_pos [in] Starting position of timeseries. count [in] Number of elements needed. buffer [in] Reference to the target array for the data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting time and number of elements.
int GetData( datetime start_time, int double& ) const count, buffer // starting time // number of elements // target array
Parameters start_time [in] Starting time. count [in] Number of elements needed. buffer [in] Reference to the target array for data. Returned value >=0 if successful, -1 in the case of error.
GetData
Gets the element of timeseries by starting and stop times.
1726
Standard Library
int GetData( datetime start_time, datetime stop_time, double& ) const buffer // starting time // stop time // target array
Parameters start_time [in] Starting time. stop_time [in] Stop time. buffer [in] Reference to the target array for data Returned value >=0 if successful, -1 in the case of error.
1727
Standard Library
1728
Standard Library
CiADX
CiADX is a class intended for using the Average Directional Index technical indicator.
Description
The CiADX class provides the creation and access to the data of the Average Directional Index indicator.
Declaration
class CiADX: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Plus Minus Input/output virtual Type Returns the object type identifier Returns the buffer element of the main line Returns the buffer element of the +DI line Returns the buffer element of the -DI line Creates the indicator Returns the averaging period
1729
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1730
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1731
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1732
Standard Library
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1733
Standard Library
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1734
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1735
Standard Library
CiADXWilder
CiADXWilder is a class intended for using the Average Directional Index by Welles Wilder technical indicator.
Description
The CiADXWilder class provides the creation and access to the data of the Average Directional Index by Welles Wilder indicator.
Declaration
class CiADXWilder: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Plus Minus Input/output virtual Type Returns the object type identifier Returns the buffer element of the main line Returns the buffer element of the +DI line Returns the buffer element of the -DI line Creates the indicator Returns the averaging period
1736
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1737
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1738
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1739
Standard Library
Plus
Returns the buffer element of the +DI line by the specified index.
double Plus( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the +DI line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1740
Standard Library
Minus
Returns the buffer element of the -DI line by the specified index.
double Minus( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the -DI line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1741
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1742
Standard Library
CiBands
CiBands is a class intended for using the Bollinger Bands technical indicator.
Description
The CiBands class provides the creation and access to the data of the Bollinger Bands indicator.
Declaration
class CiBands: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod MaShift Deviation Applied Create Methods Create Data Access Methods Main Upper Lower Input/output virtual Type Returns the object type identifier Returns the buffer element of the base line Returns the buffer element of the upper line Returns the buffer element of the lower line Creates the indicator Returns the averaging period Returns the horizontal shift Returns the deviation Returns the price type or handle to apply
1743
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1744
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1745
Standard Library
Deviation
Returns the deviation.
double Deviation() const
1746
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1747
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Shift // Deviation // applied price, or handle ENUM_TIMEFRAMES period, int int double int ) ma_period, ma_shift, deviation, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift of the indicator. deviation [in] Deviation. applied [in] Volume type to apply. Returned value true if successful, false if indicator hasn't been created.
1748
Standard Library
Base
Returns the buffer element of the base line by the specified index.
double Base( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the Base line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1749
Standard Library
Upper
Returns the buffer element of the upper line by the specified index.
double Upper( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1750
Standard Library
Lower
Returns the buffer element of the lower line by the specified index.
double Lower( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1751
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1752
Standard Library
CiEnvelopes
CiEnvelopes is a class intended for using the Envelopes technical indicator.
Description
The CiEnvelopes class provides the creation and access to the data of the Envelopes indicator.
Declaration
class CiEnvelopes: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod MaShift MaMethod Deviation Applied Create Methods Create Data Access Methods Upper Lower Input/output virtual Type Returns the object type identifier Returns the buffer element of the upper line Returns the buffer element of the lower line Creates the indicator Returns the averaging period Returns the horizontal shift Returns the averaging method Returns the deviation Returns the price type or handle to apply
1753
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1754
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1755
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1756
Standard Library
Deviation
Returns the value of deviation.
double Deviation() const
Returned value Returns the value of deviation, defined at the indicator creation.
1757
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1758
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Horizontal shift // Averaging method // Price type or handle to apply // Deviation ENUM_TIMEFRAMES period, int int ENUM_MA_METHOD int double ) ma_period, ma_shift, ma_method, applied, deviation
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Price type of handle to apply. deviation [in] Deviation. Returned value true if successful, false if indicator hasn't been created.
1759
Standard Library
Upper
Returns the buffer element of the upper line by the specified index.
double Upper( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the upper line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1760
Standard Library
Lower
Returns the buffer element of the lower line by the specified index.
double Lower( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the lower line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1761
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1762
Standard Library
CiIchimoku
CiIchimoku is a class intended for using the Ichimoku Kinko Hyo technical indicator.
Description
The CiIchimoku class provides the creation, setup and access to the data of the Ichimoku Kinko Hyo indicator.
Declaration
class CiIchimoku: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes TenkanSenPeriod KijunSenPeriod SenkouSpanBPeriod Create Methods Create Data Access Methods TenkanSen Returns the buffer element of the TenkanSen line Returns the buffer element of the KijunSen line Returns the buffer element of the SenkouSpanA line Returns the buffer element of the SenkouSpanB line Returns the buffer element of the ChinkouSpan line Creates the indicator Returns the TenkanSen period Returns the KijunSen period Returns the SenkouSpanB period
KijunSen SenkouSpanA
SenkouSpanB
ChinkouSpan
1763
Standard Library
TenkanSenPeriod
Returns the TenkanSen period.
int TenkanSenPeriod() const
Returned value Returns the TenkanSen period, defined at the indicator creation.
1764
Standard Library
KijunSenPeriod
Returns the KijunSen period.
int KijunSenPeriod() const
Returned value Returns the KijunSen period, defined at the indicator creation.
1765
Standard Library
SenkouSpanBPeriod
Returns the SenkouSpanB period.
int SenkouSpanBPeriod() const
Returned value Returns the SenkouSpanB period, defined at the indicator creation.
1766
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Period of TenkanSen // Period of KijunSen // Period of SenkouSpanB ENUM_TIMEFRAMES period, int int int ) tenkan_sen, kijun_sen, senkou_span_b
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). tenkan_sen [in] Period of TenkanSen. kijun_sen [in] Period of KijunSen. senkou_span_b [in] Period of SenkouSpanB. Returned value true if successful, false if indicator hasn't been created.
1767
Standard Library
TenkanSen
Returns the buffer element of the TenkanSen line by the specified index.
double TenkanSen( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the TenkanSen line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1768
Standard Library
KijunSen
Returns the buffer element of the KijunSen line by the specified index.
double KijunSen( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the KijunSen line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1769
Standard Library
SenkouSpanA
Returns the buffer element of the SenkouSpanA line by the specified index.
double SenkouSpanA( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the SenkouSpanA line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1770
Standard Library
SenkouSpanB
Returns the buffer element of the SenkouSpanB line by the specified index.
double SenkouSpanB( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the SenkouSpanB line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1771
Standard Library
ChinkouSpan
Returns the buffer element of the ChinkouSpan line by the specified index.
double ChinkouSpan( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the ChinkouSpan line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1772
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1773
Standard Library
CiMA
CiMA is a class intended for using the Moving Average technical indicator.
Description
The CiMA class provides the creation, setup and access to the data of the Moving Average indicator.
Declaration
class CiMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod MaShift MaMethod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the horizontal shift Returns the averaging method Returns the price type or handle to apply
1774
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1775
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1776
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator creation.
1777
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1778
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string string, // Symbol // Period // Averaging period // Horizontal shift // Averaging method // Price type of handle to apply ENUM_TIMEFRAMES period, int int ENUM_MA_METHOD int ) ma_period, ma_shift, ma_method, applied
Parameters string [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1779
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1780
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1781
Standard Library
CiSAR
CiSAR is a class intended for using the Parabolic Stop And Reverse System technical indicator.
Description
The CiSAR class provides the creation, setup and access to the data of the Parabolic Stop And Reverse System indicator.
Declaration
class CiSAR: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes SarStep Maximum Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the step for the velocity increasing Returns the coefficient of price following
1782
Standard Library
SarStep
Returns the step for the velocity increasing (acceleration coefficient).
double SarStep() const
Returned value The step for the velocity increasing, defined at the indicator creation.
1783
Standard Library
Maximum
Returns the coefficient of price following.
double Maximum() const
Returned value The price following coefficient, defined at the indicator creation.
1784
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Step // Coefficient ENUM_TIMEFRAMES period, double double ) step, maximum
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). step [in] Step for the velocity increasing. maximum [in] Price following coefficient. Returned value true if successful, false if indicator hasn't been created.
1785
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1786
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1787
Standard Library
CiStdDev
CiStdDev is a class intended for using the Standard Deviation technical indicator.
Description
The CiStdDev class provides the creation, setup and access to the data of the Standard Deviation indicator.
Declaration
class CiStdDev: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod MaShift MaMethod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the horizontal shift Returns the averaging method Returns the price type or handle to apply
1788
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1789
Standard Library
MaShift
Returns the horizontal shift of the indicator.
int MaShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1790
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method (value of ENUM_MA_METHOD enumeration), defined at the indicator creation.
1791
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1792
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Horizontal shift // Averaging method // Price type or handle to apply ENUM_TIMEFRAMES period, int int ENUM_MA_METHOD int ) ma_period, ma_shift, ma_method, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1793
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1794
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1795
Standard Library
CiDEMA
CiDEMA is a class intended for using the Double Exponential Moving Average technical indicator.
Description
The CiDEMA class provides the creation, setup and access to the data of the Double Exponential Moving Average indicator.
Declaration
class CiDEMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod IndShift Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the horizontal shift Returns the price type or handle to apply
1796
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1797
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1798
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1799
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string string, // Symbol // Period // Averaging period // Shift // Price type of handle to apply ENUM_TIMEFRAMES period, int int int ) ma_period, ind_shift, applied
Parameters string [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ind_shift [in] Horizontal shift. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1800
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1801
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1802
Standard Library
CiTEMA
CiTEMA is a class intended for using the Triple Exponential Moving Average technical indicator.
Description
The CiTEMA class provides the creation, setup and access to the data of the Triple Exponential Moving Average indicator.
Declaration
class CiTEMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod IndShift Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the horizontal shift Returns the price type or handle to apply
1803
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1804
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1805
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1806
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Offset // Price type of handle to apply ENUM_TIMEFRAMES period, int int int ) ma_period, ma_shift, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1807
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1808
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1809
Standard Library
CiFrAMA
CiFrAMA is a class intended for using the Fractal Adaptive Moving Average technical indicator.
Description
The CiFrAMA class provides the creation, setup and access to the data of the Fractal Adaptive Moving Average indicator.
Declaration
class CiFrAMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod IndShift Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the horizontal shift Returns the price type or handle to apply
1810
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1811
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1812
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1813
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Offset // Price type of handle to apply ENUM_TIMEFRAMES period, int int int ) ma_period, ma_shift, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_shift [in] Horizontal shift. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1814
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1815
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1816
Standard Library
CiAMA
CiAMA is a class intended for using the Adaptive Moving Average technical indicator.
Description
The CiAMA class provides the creation, setup and access to the data of the Adaptive Moving Average indicator.
Declaration
class CiAMA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes MaPeriod FastEmaPeriod SlowEmaPeriod IndShift Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the averaging period for the fast EMA Returns the averaging period for the slow EMA Returns the horizontal shift Returns the price type or handle to apply
1817
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1818
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Returned value Returns the averaging period for the fast EMA, defined at the indicator creation.
1819
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Returned value Returns the averaging period for the slow EMA, defined at the indicator creation.
1820
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1821
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1822
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string string, // Symbol // Period // Averaging period // Fast EMA period // Slow EMA period // Shift // Price type or handle to apply ENUM_TIMEFRAMES period, int int int int int ) ma_period, fast_ema_period, slow_ema_period, ind_shift, applied
Parameters string [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. fast_ema_period [in] Fast EMA averaging period. slow_ema_period [in] Slow EMA averaging period. ind_shift [in] Horizontal shift. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1823
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1824
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1825
Standard Library
CiVIDyA
CiVIDyA is a class intended for using the Variable Index DYnamic Average technical indicator.
Description
The CiVIDyA class provides the creation, setup and access to the data of the Variable Index DYnamic Average indicator.
Declaration
class CiVIDyA: public CIndicator
Title
#include <Indicators\Trend.mqh>
Class Methods
Attributes CmoPeriod EmaPeriod IndShift Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the period for Momentum Returns the averaging period for EMA Returns the horizontal shift Returns the price type or handle to apply
1826
Standard Library
CmoPeriod
Returns the period for Momentum.
int CmoPeriod() const
Returned value Returns the period for Momentum, defined at the indicator creation.
1827
Standard Library
EmaPeriod
Returns the averaging period for EMA.
int EmaPeriod() const
Returned value Returns the averaging period for EMA, defined at the indicator creation.
1828
Standard Library
IndShift
Returns the horizontal shift of the indicator.
int IndShift() const
Returned value Returns the horizontal shift value, defined at the indicator creation.
1829
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1830
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Momentum period // Averaging period // Shift // Price type or handle to apply ENUM_TIMEFRAMES period, int int int int ) cmo_period, ema_period, ind_shift, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). cmo_period [in] Momentum period. ema_period [in] Averaging period. ind_shift [in] Horizontal shift. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1831
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1832
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1833
Standard Library
Oscillators
This group of chapters contains the technical details of Oscillators classes of the MQL5 Standard Library and descriptions of all its key components. Class/group CiATR CiBearsPower CiBullsPower CiCCI CiChaikin CiDeMarker CiForce CiMACD CiMomentum CiOsMA CiRSI CiRVI CiStochastic CiWPR CiTriX Description Average True Range Bears Power Bulls Power Commodity Channel Index Chaikin Oscillator DeMarker Force Index Moving Averages Convergence-Divergence Momentum Moving Average of Oscillator (MACD histogram) Relative Strength Index Relative Vigor Index Stochastic Oscillator Williams' Percent Range Triple Exponential Moving Averages Oscillator
1834
Standard Library
CiATR
CiATR is a class intended for using the Average True Range technical indicator.
Description
The CiATR class provides the creation, setup and access to the data of the Average True Range indicator.
Declaration
class CiATR: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period
1835
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1836
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1837
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1838
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1839
Standard Library
CiBearsPower
CiBearsPower is a class intended for using the Bears Power technical indicator.
Description
The CiBearsPower class provides the creation, setup and access to the data of the Bears Power indicator.
Declaration
class CiBearsPower: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period
1840
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1841
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1842
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1843
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1844
Standard Library
CiBullsPower
CiBullsPower is a class intended for using the Bulls Power technical indicator.
Description
The CiBullsPower class provides the creation, setup and access to the data of the Bulls Power indicator.
Declaration
class CiBullsPower: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period
1845
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1846
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1847
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1848
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1849
Standard Library
CiCCI
CiCCI is a class intended for using the Commodity Channel Index technical indicator.
Description
The CiCCI class provides the creation, setup and access to the data of the Commodity Channel Index indicator.
Declaration
class CiCCI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the price type or handle to apply
1850
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1851
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1852
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Price type or handle to apply ENUM_TIMEFRAMES period, int int ) ma_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1853
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1854
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1855
Standard Library
CiChaikin
CiChaikin is a class intended for using the Chaikin Oscillator technical indicator.
Description
The CiChaikin class provides the creation, setup and access to the data of the Chaikin Oscillator indicator.
Declaration
class CiChaikin: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes FastMaPeriod SlowMaPeriod MaMethod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period for the fast MA Returns the averaging period for the slow MA Returns the averaging method Returns the price type or handle to apply
1856
Standard Library
FastMaPeriod
Returns the averaging period for the fast EMA.
int FastMaPeriod() const
Returned value Returns the averaging period for the fast EMA, defined at the indicator creation.
1857
Standard Library
SlowMaPeriod
Returns the averaging period for the slow EMA.
int SlowMaPeriod() const
Returned value Returns the averaging period for the slow EMA, defined at the indicator creation.
1858
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1859
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1860
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES int int ENUM_MA_METHOD symbol, period, fast_ma_period, slow_ma_period, ma_method, // Symbol // Period // Fast EMA period // Slow EMA period // Averaging method // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). fast_ma_period [in] Period for fast EMA. slow_ma_period [in] Period for slow EMA. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1861
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1862
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1863
Standard Library
CiDeMarker
CiDeMarker is a class intended for using the DeMarker technical indicator.
Description
The CiDeMarker class provides the creation, setup and access to the data of the DeMarker indicator.
Declaration
class CiDeMarker: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period
1864
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1865
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1866
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1867
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1868
Standard Library
CiForce
CiForce is a class intended for using the Force Index technical indicator.
Description
The CiForce class provides the creation, setup and access to the data of the Force Index indicator.
Declaration
class CiForce: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod MaMethod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the averaging method Returns the price type or handle to apply
1869
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1870
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1871
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1872
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES int ENUM_MA_METHOD symbol, period, ma_period, ma_method, // Symbol // Period // Averaging period // Averaging method // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1873
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1874
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1875
Standard Library
CiMACD
CiMACD is a class intended for using the Moving Averages Convergence-Divergence technical indicator.
Description
The CiMACD class provides the creation, setup and access to the data of the Moving Averages Convergence-Divergence indicator.
Declaration
class CiMACD: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes FastEmaPeriod Returns the averaging period fofor the fast EMA Returns the averaging period of the slow EMA Returns the averaging period of the signal line Returns the price type or handle to apply
SlowEmaPeriod SignalPeriod Applied Create Methods Create Data Access Methods Main Signal Input/output virtual Type
Returns the buffer element of the main line Returns the buffer element of the signal line
1876
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Returned value Returns the averaging period for the fast EMA, defined at the indicator creation.
1877
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Returned value Returns the averaging period for the slow EMA, defined at the indicator creation.
1878
Standard Library
SignalPeriod
Returns the averaging period for the signal line.
int SignalPeriod() const
Returned value Returns the averaging period for the signal line, defined at the indicator creation.
1879
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1880
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Fast EMA period // Slow EMA period // Signal period // Price type or handle to apply ENUM_TIMEFRAMES period, int int int int ) fast_ema_period, slow_ema_period, signal_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). fast_ema_period [in] Fast EMA period. slow_ema_period [in] Slow EMA period. signal_period [in] Signal line period. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1881
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1882
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1883
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1884
Standard Library
CiMomentum
CiMomentum is a class intended for using the Momentum technical indicator.
Description
The CiMomentum class provides the creation, setup and access to the data of the Momentum indicator.
Declaration
class CiMomentum: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the price type or handle to apply
1885
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1886
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1887
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Price type or handle to apply ENUM_TIMEFRAMES period, int int ) ma_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1888
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1889
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1890
Standard Library
CiOsMA
CiOsMA is a class intended for using the Moving Average of Oscillator (MACD histogram) technical indicator.
Description
The CiOsMA class provides the creation, setup and access to the data of the Moving Average of Oscillator (MACD histogram) indicator.
Declaration
class CiOsMA: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes FastEmaPeriod SlowEmaPeriod SignalPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period of the fast EMA Returns the averaging period of the slow EMA Returns the averaging period of the signal line Returns the price type or handle to apply
1891
Standard Library
FastEmaPeriod
Returns the averaging period for the fast EMA.
int FastEmaPeriod() const
Returned value Returns the averaging period for the fast EMA, defined at the indicator creation.
1892
Standard Library
SlowEmaPeriod
Returns the averaging period for the slow EMA.
int SlowEmaPeriod() const
Returned value Returns the averaging period for the slow EMA, defined at the indicator creation.
1893
Standard Library
SignalPeriod
Returns the averaging period for the signal line.
int SignalPeriod() const
Returned value Returns the averaging period for the signal line, defined at the indicator creation.
1894
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1895
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Fast EMA period // Slow EMA period // Signal line period // Price type or handle to apply ENUM_TIMEFRAMES period, int int int int ) fast_ema_period, slow_ema_period, signal_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). fast_ema_period [in] Fast EMA period. slow_ema_period [in] Slow EMA period. signal_period [in] Signal line period. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1896
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1897
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1898
Standard Library
CiRSI
CiRSI is a class intended for using the Relative Strength Index technical indicator.
Description
The CiRSI class provides the creation, setup and access to the data of the Relative Strength Index indicator.
Declaration
class CiRSI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the price type or handle to apply
1899
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1900
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1901
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Price type or handle to apply ENUM_TIMEFRAMES period, int int ) ma_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. applied [in] Price type or handle to apply. Returned value true if successful, false if indicator hasn't been created.
1902
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1903
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1904
Standard Library
CiRVI
CiRVI is a class intended for using the Relative Vigor Index technical indicator.
Description
The CiRVI class provides the creation, setup and access to the data of the Relative Vigor Index indicator.
Declaration
class CiRVI: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Create Methods Create Data Access Methods Main Signal Input/output virtual Type Returns the object type identifier Returns the buffer element of the base line Returns the buffer element of the signal line Creates the indicator Returns the averaging period
1905
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1906
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period ENUM_TIMEFRAMES period, int ) ma_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. Returned value true if successful, false if indicator hasn't been created.
1907
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1908
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1909
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1910
Standard Library
CiStochastic
CiStochastic is a class intended for using the Stochastic Oscillator technical indicator.
Description
The CiStochastic class provides the creation, setup and access to the data of the Stochastic Oscillator indicator.
Declaration
class CiStochastic: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes Kperiod Dperiod Slowing MaMethod PriceField Create Methods Create Data Access Methods Main Signal Input/output virtual Type Returns the object type identifier Returns the buffer element of the base line Returns the buffer element of the signal line Creates the indicator Returns the averaging period for the %K line Returns the averaging period for the %D line Returns the slowing period Returns the averaging method Price type (Low/High ore Close/Close) to apply
1911
Standard Library
Kperiod
Returns the averaging period for the %K line.
int Kperiod() const
Returned value Returns the averaging period for the %K line, defined at the indicator creation.
1912
Standard Library
Dperiod
Returns the averaging period for the %D line.
int Dperiod() const
Returned value Returns the averaging period for the %D line, defined at the indicator creation.
1913
Standard Library
Slowing
Returns the period of slowing.
int Slowing() const
Returned value Returns the period of slowing, defined at the indicator creation.
1914
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1915
Standard Library
PriceField
Returns the price type (Low/High or Close/Close) to apply.
ENUM_STO_PRICE PriceField() const
Returned value The price type to apply, defined at the indicator creation.
1916
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period of %K // Averaging period of %D // Slowing period // Averaging method // Price type to apply ENUM_TIMEFRAMES period, int int int ENUM_MA_METHOD ENUM_STO_PRICE ) Kperiod, Dperiod, slowing, ma_method, price_field
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Kperiod [in] Averaging period of %K line. Dperiod [in] Averaging period of %D line. slowing [in] Slowing period. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). price_field [in] Price type (Low/High or Close/Close) to apply (ENUM_STO_PRICE enumeration). Returned value true if successful, false if indicator hasn't been created.
1917
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1918
Standard Library
Signal
Returns the buffer element of the signal line by the specified index.
double Signal( int index ) // Index
Signal
Returns the buffer element of the signal line by the specified index.
double Signal( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the signal line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1919
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1920
Standard Library
CiTriX
CiTriX is a class intended for using the Triple Exponential Moving Averages Oscillator technical indicator.
Description
The CiTriX class provides the creation, setup and access to the data of the Triple Exponential Moving Averages Oscillator indicator.
Declaration
class CiTriX: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes MaPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the price type or handle to apply
1921
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1922
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1923
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Averaging period // Price type or handle ENUM_TIMEFRAMES period, int int ) ma_period, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. applied [in] Price type of handle to apply. Returned value true if successful, false if indicator hasn't been created.
1924
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1925
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1926
Standard Library
CiWPR
CiWPR is a class intended for using the Williams' Percent Range technical indicator.
Description
The CiWPR class provides the creation, setup and access to the data of the Williams' Percent Range indicator.
Declaration
class CiWPR: public CIndicator
Title
#include <Indicators\Oscilators.mqh>
Class Methods
Attributes CalcPeriod Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the calculation period
1927
Standard Library
CalcPeriod
Returns the period for calculation.
int CalcPeriod() const
Returned value Returns the the period for calculation, defined at the indicator creation.
1928
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Calculation period ENUM_TIMEFRAMES period, int ) calc_period
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). calc_period [in] Period for calculation. Returned value true if successful, false if indicator hasn't been created.
1929
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1930
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1931
Standard Library
Volume Indicators
This group of chapters contains technical details of Volume Indicator classes of the MQL5 Standard Library and descriptions of all its key components. Class/group CiAD CiMFI CiOBV CiVolumes Description Accumulation/Distribution Money Flow Index On Balance Volume Volumes
1932
Standard Library
CiAD
CiAD is a class intended for using the Accumulation/Distribution technical indicator.
Description
The CiAD class provides the creation, setup and access to the data of the Accumulation/Distribution indicator.
Declaration
class CiAD: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the volume type to apply
1933
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1934
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES symbol, period, // Symbol // Period // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1935
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1936
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1937
Standard Library
CiMFI
CiMFI is a class intended for using the Money Flow Index technical indicator.
Description
The CiMFI class provides the creation, setup and access to the data of the Money Flow Index indicator.
Declaration
class CiMFI: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes MaPeriod Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the averaging period Returns the volume type to apply
1938
Standard Library
MaPeriod
Returns the averaging period.
int MaPeriod() const
Returned value Returns the averaging period, defined at the indicator creation.
1939
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1940
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES int symbol, period, ma_period, // Symbol // Period // Averaging period // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). ma_period [in] Averaging period. applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1941
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1942
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1943
Standard Library
CiOBV
CiOBV is a class intended for using the On Balance Volume technical indicator.
Description
The CiOBV class provides the creation, setup and access to the data of the On Balance Volume indicator.
Declaration
class CiOBV: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the volume type to apply
1944
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1945
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES symbol, period, // Symbol // Period // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1946
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1947
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1948
Standard Library
CiVolumes
CiVolumes is a class intended for using the Volumes technical indicator.
Description
The CiVolumes class provides the creation, setup and access to the data of the Volumes indicator.
Declaration
class CiVolumes: public CIndicator
Title
#include <Indicators\Volumes.mqh>
Class Methods
Attributes Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the volume type to apply
1949
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1950
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES symbol, period, // Symbol // Period // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1951
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1952
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1953
Standard Library
1954
Standard Library
CiAC
CiAC is a class intended for using the Accelerator Oscillator technical indicator.
Description
The CiAC class provides the creation, setup and access to the data of the Accelerator Oscillator indicator.
Declaration
class CiAC: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator
1955
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if indicator hasn't been created.
1956
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1957
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1958
Standard Library
CiAlligator
CiAlligator is a class intended for using the Alligator technical indicator.
Description
The CiAlligator class provides the creation, setup and access to the data of the Alligator indicator.
Declaration
class CiAlligator: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes JawPeriod JawShift TeethPeriod Returns the averaging period for the Jaws line Returns the horizontal shift of the Jaws line Returns the averaging period for the Teeths line Returns the horizontal shift of the Teeths line Returns the averaging period for the Lips line Returns the horizontal shift of the Lips line Returns the averaging method Returns the price type or handle to apply
TeethShift LipsPeriod LipsShift MaMethod Applied Create Methods Create Data Access Methods Jaw
Returns the buffer element of the Jaws line buffer Returns the buffer element of the Teeths line buffer Returns the buffer element of the Lips line buffer
Teeth
Lips
1959
Standard Library
JawPeriod
Returns the averaging period for the Jaw line.
int JawPeriod() const
Returned value Returns the averaging period for the Jaw line, defined at the indicator creation.
1960
Standard Library
JawShift
Returns the horizontal shift of the Jaws line.
int JawShift() const
Returned value Horizontal shift of the Jaws line, defined at the indicator creation.
1961
Standard Library
TeethPeriod
Returns the averaging period for the Teeth line.
int TeethPeriod() const
Returned value Returns the averaging period for the Teeth line, defined at the indicator creation.
1962
Standard Library
TeethShift
Returns the horizontal shift of the Teeths line.
int TeethShift() const
Returned value Horizontal shift of the Teeths line, defined at the indicator creation.
1963
Standard Library
LipsPeriod
Returns the averaging period for the Lips line.
int LipsPeriod() const
Returned value Returns the averaging period for the Lips line, defined at the indicator creation.
1964
Standard Library
LipsShift
Returns the horizontal shift of the Lips line.
int LipsShift() const
Returned value Horizontal shift of the Lips line, defined at the indicator creation.
1965
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1966
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1967
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Jaws period // Jaws shift // Teeths period // Teeths shift // Lips period // Lips shift // Averaging method // Volume type to apply ENUM_TIMEFRAMES period, int int int int int int ENUM_MA_METHOD int ) jaw_period, jaw_shift, teeth_period, teeth_shift, lips_period, lips_shift, ma_method, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). jaw_period [in] Jaws period. jaw_shift [in] Jaws shift. teeth_period [in] Teeths period. teeth_shift [in] Teeths shift. lips_period [in] Lips period. lips_shift [in] Lips shift. ma_method [in] Moving average method (ENUM_MA_METHOD enumeration). applied [in] Volume type to apply. Returned value true if successful, false if indicator hasn't been created.
1968
Standard Library
Jaw
Returns the buffer element of the Jaws line by the specified index.
double Jaw( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the Jaws line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1969
Standard Library
Teeth
Returns the buffer element of the Teeths line by the specified index.
double Teeth( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the Teeths line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1970
Standard Library
Lips
Returns the buffer element of the Lips line by the specified index.
double Lips( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the Lips line of the specified index, or EMPTY_VALUE if there isn't any correct data.
1971
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1972
Standard Library
CiAO
CiAO is a class intended for using the Awesome Oscillator technical indicator.
Description
The CiAO class provides the creation, setup and access to the data of the Awesome Oscillator indicator.
Declaration
class CiAO: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator
1973
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if indicator hasn't been created.
1974
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1975
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1976
Standard Library
CiFractals
CiFractals is a class intended for using the Fractals technical indicator.
Description
The CiFractals class provides the creation, setup and access to the data of the Fractals indicator.
Declaration
class CiFractals: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Create Methods Create Data Access Methods Upper Lower Input/output virtual Type Returns the object type identifier Returns the buffer element of the upper buffer Returns the buffer element of the lower buffer Creates the indicator
1977
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period ENUM_TIMEFRAMES period )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). Returned value true if successful, false if indicator hasn't been created.
1978
Standard Library
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any correct data.
1979
Standard Library
Lower
Returns the buffer element of the lower buffer by the specified index.
double Lower( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any correct data.
1980
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1981
Standard Library
CiGator
CiGator is a class intended for using the Gator Oscillator technical indicator.
Description
The CiGator class provides the creation, setup and access to the data of the Gator Oscillator indicator.
Declaration
class CiGator: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes JawPeriod JawShift TeethPeriod Returns the averaging period for the Jaws line Returns the horizontal shift of the Jaws line Returns the averaging period for the Teeths line Returns the horizontal shift of the Teeths line Returns the averaging period for the Lips line Returns the horizontal shift of the Lips line Returns the averaging method Returns the price type or handle to apply
TeethShift LipsPeriod LipsShift MaMethod Applied Create Methods Create Data Access Methods Upper Lower Input/output virtual Type
Returns the buffer element of the upper buffer Returns the buffer element of the lower buffer
1982
Standard Library
JawPeriod
Returns the averaging period for the Jaws line.
int JawPeriod() const
Returned value Returns the averaging period for the Jaws line, defined at the indicator creation.
1983
Standard Library
JawShift
Returns the horizontal shift of the Jaws line.
int JawShift() const
Returned value Horizontal shift of the Jaws line, defined at the indicator creation.
1984
Standard Library
TeethPeriod
Returns the averaging period for the Teeth line.
int TeethPeriod() const
Returned value Returns the averaging period for the Teeth line, defined at the indicator creation.
1985
Standard Library
TeethShift
Returns the horizontal shift of the Teeths line.
int TeethShift() const
Returned value Horizontal shift of the Teeths line, defined at the indicator creation.
1986
Standard Library
LipsPeriod
Returns the averaging period for the Lips line.
int LipsPeriod() const
Returned value Returns the averaging period for the Lips line, defined at the indicator creation.
1987
Standard Library
LipsShift
Returns the horizontal shift of the Lips line.
int LipsShift() const
Returned value Horizontal shift of the Lips line, defined at the indicator creation.
1988
Standard Library
MaMethod
Returns the averaging method.
ENUM_MA_METHOD MaMethod() const
Returned value Returns the averaging method, defined at the indicator creation.
1989
Standard Library
Applied
Returns the price type or handle to apply.
int Applied() const
Returned value Price type or handle to apply, defined at the indicator creation.
1990
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string symbol, // Symbol // Period // Jaws period // Jaws shift // Teeths period // Teeths shift // Lips period // Lips shift // Averaging method // Volume type to apply ENUM_TIMEFRAMES period, int int int int int int ENUM_MA_METHOD int ) jaw_period, jaw_shift, teeth_period, teeth_shift, lips_period, lips_shift, ma_method, applied
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). jaw_period [in] Jaws period. jaw_shift [in] Jaws shift. teeth_period [in] Teeths period. teeth_shift [in] Teeths shift. lips_period [in] Lips period. lips_shift [in] Lips shift. ma_method [in] Averaging method (ENUM_MA_METHOD enumeration). applied [in] Volume type to apply. Returned value true if successful, false if indicator hasn't been created.
1991
Standard Library
Upper
Returns the buffer element of the upper buffer by the specified index.
double Upper( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the upper buffer of the specified index, or EMPTY_VALUE if there isn't any correct data.
1992
Standard Library
Lower
Returns the buffer element of the lower buffer by the specified index.
double Upper( int index ) // Index
Parameters index [in] Element index. Returned value The buffer element of the lower buffer of the specified index, or EMPTY_VALUE if there isn't any correct data.
1993
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1994
Standard Library
CiBWMFI
CiBWMFI is a class intended for using the Market Facilitation Index by Bill Williams technical indicator.
Description
The CiBWMFI class provides the creation, setup and access to the data of the Market Facilitation Index by Bill Williams indicator.
Declaration
class CiBWMFI: public CIndicator
Title
#include <Indicators\BillWilliams.mqh>
Class Methods
Attributes Applied Create Methods Create Data Access Methods Main Input/output virtual Type Returns the object type identifier Returns the buffer element Creates the indicator Returns the volume type to apply
1995
Standard Library
Applied
Returns the volume type to apply.
ENUM_APPLIED_VOLUME Applied() const
1996
Standard Library
Create
It creates the indicator with specified parameters.
bool Create( string ENUM_TIMEFRAMES symbol, period, // Symbol // Period // Volume type to apply
ENUM_APPLIED_VOLUME applied )
Parameters symbol [in] Symbol. period [in] Timeframe (ENUM_TIMEFRAMES enumeration). applied [in] Volume type to apply (ENUM_APPLIED_VOLUME enumeration). Returned value true if successful, false if indicator hasn't been created.
1997
Standard Library
Main
Returns the buffer element by the specified index.
double Main( int index ) // Index
Parameters index [in] Element index. Returned value Buffer element of the specified index if successful, or EMPTY_VALUE if there isn't any correct data.
1998
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
1999
Standard Library
CiCustom
CiCustom is a class intended for using the custom technical indicators.
Description
The CiCustom class provides the creation, setup and access to the data of the custom indicator.
Declaration
class CiCustom: public CIndicator
Title
#include <Indicators\Custom.mqh>
Class Methods
Attributes NumBuffers NumParams ParamType ParamLong Sets the number of buffers Gets the number of parameters Gets the type of the specified parameter Gets the value of the specified parameter of integer type Gets the value of the specified parameter of double type Gets the value of the specified parameter of string type
ParamDouble
ParamString
2000
Standard Library
NumBuffers
Sets the number of buffers.
bool NumBuffers( int buffers ) // number of buffers
2001
Standard Library
NumParams
Gets the number of parameters.
int NumParams() const
2002
Standard Library
ParamType
Gets a type of the parameter with specified index.
ENUM_DATATYPE ParamType( int index ) const // parameter index
Parameters index [in] Parameter index. Returned value Returns the data type (value of ENUM_DATATYPE enumeration) of the parameter with specified index, used in indicator creation. Note If parameter index is invalid, it returns WRONG_VALUE.
2003
Standard Library
ParamLong
Gets the value of specified parameter of long type.
long ParamLong( int index ) const // index
Parameters index [in] Parameter index. Returned value The value of specified parameter of long type, used in creation of the indicator. Note If the number is invalid, it returns 0.
2004
Standard Library
ParamDouble
Gets the value of specified parameter of double type.
double ParamDouble( int index ) const // index
Parameters index [in] Parameter index. Returned value The value of specified parameter of double type, used in creation of the indicator. Note If the number is invalid, it returns EMPTY_VALUE.
2005
Standard Library
ParamString
Gets the value of specified parameter of string type.
string ParamString( int index ) const // index
Parameters index [in] Parameter index. Returned value The value of specified string parameter, used in creation of the indicator. Note If the number is invalid, it returns an empty string.
2006
Standard Library
Type
Returns the object type identifier.
virtual int Type() const
2007
Standard Library
Trade Classes
This section contains technical details of working with trade classes and description of the relevant components of the MQL5 standard library. Using trade classes will save time when creating custom programs (experts). MQL5 Standard Library (in terms of data sets) is placed in the terminal working directory, in the Include\Arrays folder. Class/Group CAccountInfo CSymbolInfo Description Class for working with trade account properties Class for working properties with trade instrument
Class for working with pending order properties Class for working with history order properties Class for working with open position properties Class for working with history deal properties Class for trade operations execution
2008
Standard Library
CAccountInfo
CAccountInfo is a class for easy access to the currently opened trade account properties.
Description
CAccountInfo class provides easy access to the currently opened trade account properties.
Declaration
class CAccountInfo : public CObject
Title
#include <Trade\AccountInfo.mqh>
Access to double type properties Balance Credit Profit Equity Margin FreeMargin MarginLevel MarginCall MarginStopOut Gets the balance of account Gets the amount of given credit Gets the amount of current profit on account Gets the amount of current equity on account Gets the amount of reserved margin Gets the amount of free margin Gets the level of margin Gets the level of margin for deposit Gets the level of margin for Stop Out
2009
Standard Library
Access to text properties Name Server Currency Company Gets the client name Gets the trade server name Gets the deposit currency name Gets the company name, that serves an account
Access to MQL5 API functions Integer Gets the value of specified integer type property Gets the value of specified double type property Gets value of specified string type property
Gets the evaluated profit, based on the parameters passed Gets the amount of margin, required to execute trade operation Gets the amount of free margin, left after execution of trade operation Gets the maximal possible volume of trade operation
MarginCheck
FreeMarginCheck
MaxLotCheck
2010
Standard Library
Login
Gets the account number.
long Login() const
2011
Standard Library
TradeMode
Gets the trade mode.
ENUM_ACCOUNT_TRADE_MODE TradeMode() const
2012
Standard Library
TradeModeDescription
Gets the trade mode as a string.
string TradeModeDescription() const
2013
Standard Library
Leverage
Gets the amount of given leverage.
long Leverage() const
2014
Standard Library
MarginMode
Gets the mode of account Stop Out.
ENUM_ACCOUNT_STOPOUT_MODE MarginMode() const
2015
Standard Library
MarginModeDescription
Gets the mode of setting minimal margin level as a string.
string MarginModeDescription() const
2016
Standard Library
TradeAllowed
Gets the flag of trade allowance.
bool TradeAllowed() const
2017
Standard Library
TradeExpert
Gets the flag of automated trade allowance.
bool TradeExpert() const
2018
Standard Library
LimitOrders
Gets the maximal number of allowed pending orders
int LimitOrders() const
Returned value The maximal number of allowed pending orders. Note 0 - no limits.
2019
Standard Library
Balance
Gets the balance of account.
double Balance() const
2020
Standard Library
Credit
Gets the amount of given credit.
double Credit() const
2021
Standard Library
Profit
Gets the amount of current profit on account.
double Profit() const
2022
Standard Library
Equity
Gets the amount of current equity on account.
double Equity() const
2023
Standard Library
Margin
Gets the amount of reserved margin.
double Margin() const
2024
Standard Library
FreeMargin
Gets the amount of free margin.
double FreeMargin() const
2025
Standard Library
MarginLevel
Gets the level of margin.
double MarginLevel() const
2026
Standard Library
MarginCall
Gets the level of margin for a deposit.
double MarginCall() const
2027
Standard Library
MarginStopOut
Gets the level of margin for Stop Out.
double MarginStopOut() const
2028
Standard Library
Name
Gets the client name.
string Name() const
2029
Standard Library
Server
Gets the trade server name.
string Server() const
2030
Standard Library
Currency
Gets the deposit currency name.
string Currency() const
2031
Standard Library
Company
Gets the company name, that serves an account.
string Company() const
2032
Standard Library
InfoInteger
Gets the value of specified integer type property.
long InfoInteger( ENUM_ACCOUNT_INFO_INTEGER prop_id ) const // property ID
Parameters prop_id [in] Identifier of the property. The ENUM_ACCOUNT_INFO_INTEGER enumeration. Returned value Value of long type. value can be one of the values of
2033
Standard Library
InfoDouble
Gets the value of specified double type property.
double InfoDouble( ENUM_ACCOUNT_INFO_DOUBLE prop_id ) const // property ID
Parameters prop_id [in] Identifier of the property. The ENUM_ACCOUNT_INFO_DOUBLE enumeration. Returned value Value of double type. value can be one of the values of
2034
Standard Library
InfoString
Gets the value of specified string type property.
string InfoString( ENUM_ACCOUNT_INFO_STRING prop_id ) const // property ID
Parameters prop_id [in] Identifier of the property. The ENUM_ACCOUNT_INFO_STRING enumeration. Returned value Value of string type. value can be one of the values of
2035
Standard Library
OrderProfitCheck
The function calculates the profit for the current account, based on the parameters passed. The function is used for pre-evaluation of the result of a trade operation. The value is returned in the account currency.
double OrderProfitCheck( const string ENUM_ORDER_TYPE double double double ) const symbol, trade_operation, volume, price_open, price_close // symbol // operation type (ORDER_TYPE_BUY or ORDER_TYPE_SELL) // volume // open price // close price
Parameters symbol [in] Symbol for trade operation. trade_operation [in] Type of trade operation (ENUM_ORDER_TYPE enumeration). volume [in] Volume of trade operation. price_open [in] Open price. price_close [in] Close price. Returned value If successful, it returns amount of profit or EMPTY_VALUE in the case of error.
2036
Standard Library
MarginCheck
Gets the amount of margin, required for trade operation.
double MarginCheck( const string ENUM_ORDER_TYPE double double ) const symbol, trade_operation, volume, price // symbol // operation // volume // price
Parameters symbol [in] Symbol for trade operation. trade_operation [in] Type of trade operation (ENUM_ORDER_TYPE enumeration). volume [in] Volume of trade operation. price [in] Price of trade operation. Returned value Amount of margin, required for trade operation.
2037
Standard Library
FreeMarginCheck
Gets the amount of free margin, left after trade operation.
double FreeMarginCheck( const string ENUM_ORDER_TYPE double double ) const symbol, trade_operation, volume, price // symbol // operation // volume // price
Parameters symbol [in] Symbol for trade operation. trade_operation [in] Type of trade operation (ENUM_ORDER_TYPE enumeration). volume [in] Volume of trade operation. price [in] Price of trade operation. Returned value Amount of free margin, left after trade operation.
2038
Standard Library
MaxLotCheck
Gets the maximal possible volume of trade operation.
double MaxLotCheck( const string ENUM_ORDER_TYPE double ) const symbol, trade_operation, price // symbol // operation // price
Parameters symbol [in] Symbol for trade operation. trade_operation [in] Type of trade operation (ENUM_ORDER_TYPE enumeration). price [in] Price of trade operation. Returned value Maximal possible volume of trade operation.
2039
Standard Library
CSymbolInfo
CSymbolInfo is a class for easy access to the symbol properties.
Description
CSymbolInfo class provides access to the symbol properties.
Declaration
class CSymbolInfo : public CObject
Title
#include <Trade\SymbolInfo.mqh>
2040
Standard Library
(in points) Bid prices Bid BidHigh BidLow Ask prices Ask AskHigh AskLow Prices Last LastHigh LastLow Trade modes TradeCalcMode TradeCalcModeDescription Gets the mode of contract cost calculation Gets the mode of contract cost calculation as a string Gets the type of order execution Gets the type of order execution as a string Gets the closing of deals mode Gets the closing of deals mode as a string Gets the current Last price Gets the maximal Last price for a day Gets the minimal Last price for a day Gets the current Ask price Gets the maximal Ask price for a day Gets the minimal Ask price for a day Gets the current Bid price Gets the maximal Bid price for a day Gets the minimal Bid price for a day
TradeMode TradeModeDescription TradeExecution TradeExecutionDescription Swaps SwapMode SwapModeDescription SwapRollover3days SwapRollover3daysDescription Margins and flags MarginInitial MarginMaintenance MarginLong
Gets the swap calculation model Gets the swap calculation model as a string Gets the day of triple swap charge Gets the day of triple swap charge as a string
Gets the value of initial margin Gets the value of maintenance margin Gets the rate of margin charging for long positions Gets the rate of margin charging for short positions
MarginShort
2041
Standard Library
MarginLimit
Gets the rate of margin charging for Limit orders Gets the rate of margin charging for Stop orders Gets the rate of margin charging for StopLimit orders Gets the flags of the order expiration allowed modes Gets the flags of the order filling allowed modes
MarginStop
MarginStopLimit
TradeTimeFlags
Gets the number of digits after period Gets the value of one point Gets the cost of tick (minimal change of price) Gets the calculated tick price for a profitable position Gets the calculated tick price for a losing position Gets the minimal change of price
TickValueLoss
Gets the amount of trade contract Gets the minimal volume to close a deal Gets the maximal volume to close a deal Gets the minimal step of volume change to close a deal Gets the maximal allowed volume of opened position and pending orders (direction insensitive) for one symbol
LotsLimit
Swaps sizes SwapLong SwapShort Text properties CurrencyBase CurrencyProfit CurrencyMargin Bank Description Gets the name of symbol base currency Gets the profit currency name Gets the margin currency name Gets the name of current quote source Gets the string description of symbol Gets the value of long position swap Gets the value of short position swap
2042
Standard Library
Gets the value of specified integer type property Gets the value of specified double type property Gets the value of specified string type property
2043
Standard Library
Refresh
Refreshes the symbol data.
void Refresh()
Returned value None. Note The symbol should be selected by Name method.
2044
Standard Library
RefreshRates
Refreshes the symbol quotes data.
bool RefreshRates()
Returned value true in case of success, false if unable to refresh quotes. Note The symbol should be selected by Name method.
2045
Standard Library
Name
Gets symbol name.
string Name() const
Name
Sets symbol name.
void Name(string name)
2046
Standard Library
Select
Gets the "Market Watch" symbol flag.
bool Select() const
Select
Sets the "Market Watch" symbol flag.
bool Select()
2047
Standard Library
IsSynchronized
Checks the symbol synchronization with server.
bool IsSynchronized() const
Returned value true if the symbol is synchronized with server, false if not. Note The symbol should be selected by Name method.
2048
Standard Library
Volume
Gets the volume of last deal.
long Volume() const
Returned value Volume of last deal. Note The symbol should be selected by Name method.
2049
Standard Library
VolumeHigh
Gets the maximal volume of the day.
long VolumeHigh() const
Returned value Maximal volume of the day. Note The symbol should be selected by Name method.
2050
Standard Library
VolumeLow
Gets the minimal volume of the day.
long VolumeLow() const
Returned value Minimal volume of the day. Note The symbol should be selected by Name method.
2051
Standard Library
VolumeBid
Gets the volume of the current Bid.
long VolumeBid() const
Returned value Volume of the current Bid. Note The symbol should be selected by Name method.
2052
Standard Library
VolumeAsk
Gets the volume of the current Ask.
long VolumeAsk() const
Returned value Volume of the current Ask. Note The symbol should be selected by Name method.
2053
Standard Library
Time
Gets the time of last quote.
datetime Time() const
Returned value Time of last quote. Note The symbol should be selected by Name method.
2054
Standard Library
Spread
Gets the amount of spread (in points).
int Spread() const
Returned value Gets the amount of spread (in points). Note The symbol should be selected by Name method.
2055
Standard Library
SpreadFloat
Gets the flag of floating spread.
bool SpreadFloat() const
Returned value Flag of floating spread. Note The symbol should be selected by Name method.
2056
Standard Library
TickBookDepth
Gets the depth of ticks saving.
int TickBookDepth() const
Returned value Depth of ticks saving. Note The symbol should be selected by Name method.
2057
Standard Library
StopsLevel
Gets the minimal stop level for orders (in points).
int StopsLevel() const
Returned value Minimal stop level for orders (in points). Note The symbol should be selected by Name method.
2058
Standard Library
FreezeLevel
Gets the freeze level (in points).
int FreezeLevel() const
Returned value Distance of freeze level (in points). Note The symbol should be selected by Name method.
2059
Standard Library
Bid
Gets the current Bid price.
double Bid() const
Returned value Current Bid price. Note The symbol should be selected by Name method.
2060
Standard Library
BidHigh
Gets the maximal Bid price of the day.
double BidHigh() const
Returned value Maximal Bid price of the day. Note The symbol should be selected by Name method.
2061
Standard Library
BidLow
Gets the minimal Bid price of the day.
double BidLow() const
Returned value Minimal Bid price of the day. Note The symbol should be selected by Name method.
2062
Standard Library
Ask
Gets the current Ask price.
double Ask() const
Returned value Current Ask price. Note The symbol should be selected by Name method.
2063
Standard Library
AskHigh
Gets the maximal Ask price for a day.
double AskHigh() const
Returned value Maximal Ask price of the day. Note The symbol should be selected by Name method.
2064
Standard Library
AskLow
Gets the minimal Ask price for a day.
double AskLow() const
Returned value Minimal Ask price of the day. Note The symbol should be selected by Name method.
2065
Standard Library
Last
Gets the current Last price.
double Last() const
2066
Standard Library
LastHigh
Gets the maximal Last price of the day.
double LastHigh() const
Returned value Maximal Last price of the day. Note The symbol should be selected by Name method.
2067
Standard Library
LastLow
Gets the minimal Last price of the day.
double LastLow() const
Returned value Minimal Last price of the day. Note The symbol should be selected by Name method.
2068
Standard Library
TradeCalcMode
Gets the mode of contract cost calculation.
ENUM_SYMBOL_CALC_MODE TradeCalcMode() const
Returned value Mode of contract cost calculation (value of ENUM_SYMBOL_CALC_MODE enumeration). Note The symbol should be selected by Name method.
2069
Standard Library
TradeCalcModeDescription
Gets the mode of contract cost calculation as a string.
string TradeCalcModeDescription() const
Returned value Mode of contract cost calculation as a string. Note The symbol should be selected by Name method.
2070
Standard Library
TradeMode
Gets the order execution type.
ENUM_SYMBOL_TRADE_MODE TradeMode() const
Returned value Order execution type (value of ENUM_SYMBOL_TRADE_MODE enumeration). Note The symbol should be selected by Name method.
2071
Standard Library
TradeModeDescription
Gets the trade mode as a string.
string TradeModeDescription() const
Returned value Trade mode as a string. Note The symbol should be selected by Name method.
2072
Standard Library
TradeExecution
Gets the trade execution mode.
ENUM_SYMBOL_TRADE_EXECUTION TradeExecution() const
Returned value Trade execution mode (value of ENUM_SYMBOL_TRADE_EXECUTION enumeration). Note The symbol should be selected by Name method.
2073
Standard Library
TradeExecutionDescription
Gets the description of trade execution mode as a string.
string TradeExecutionDescription() const
Returned value Trade execution mode as a string. Note The symbol should be selected by Name method.
2074
Standard Library
SwapMode
Gets the swap calculation mode.
ENUM_SYMBOL_SWAP_MODE SwapMode() const
Returned value Swap calculation mode (value of ENUM_SYMBOL_SWAP_MODE enumeration). Note The symbol should be selected by Name method.
2075
Standard Library
SwapModeDescription
Gets the swap mode description as a string.
string SwapModeDescription() const
Returned value Swap mode descriprion as a string. Note The symbol should be selected by Name method.
2076
Standard Library
SwapRollover3days
Gets the swap rollover day.
ENUM_DAY_OF_WEEK SwapRollover3days() const
Returned value Swap rollover day (value of ENUM_DAY_OF_WEEK enumeration). Note The symbol should be selected by Name method.
2077
Standard Library
SwapRollover3daysDescription
Gets the swap rollover day as a string.
string SwapRollover3daysDescription() const
Returned value Swap rollover day as a string. Note The symbol should be selected by Name method.
2078
Standard Library
MarginInitial
Gets the value of initial margin.
double MarginInitial()
Returned value Value of initial margin. Note It points the amount of margin (in margin currency of instrument), that is charged from one lot. Used to check client's equity, when he enters the market. The symbol should be selected by Name method.
2079
Standard Library
MarginMaintenance
Gets the value of maintenance margin.
double MarginMaintenance()
Returned value Value of maintenance margin. Note It points the amount of margin (in margin currency of instrument), that is charged from one lot. Used to check client's equity, when the account state is changed. If the maintenance margin is equal to 0, then the initial margin is used. The symbol should be selected by Name method.
2080
Standard Library
MarginLong
Gets the rate of margin charging on long positons.
double MarginLong() const
Returned value Rate of margin charging on long positons. Note The symbol should be selected by Name method.
2081
Standard Library
MarginShort
Gets the rate of margin charging on short positons.
double MarginShort() const
Returned value Rate of margin charging on short positons. Note The symbol should be selected by Name method.
2082
Standard Library
MarginLimit
Gets the rate of margin charging on Limit orders.
double MarginLimit() const
Returned value Rate of margin charging on Limit orders. Note The symbol should be selected by Name method.
2083
Standard Library
MarginStop
Gets the rate of margin charging on Stop orders.
double MarginStop() const
Returned value Rate of margin charging on Stop orders. Note The symbol should be selected by Name method.
2084
Standard Library
MarginStopLimit
Gets the rate of margin charging on Stop Limit orders.
double MarginStopLimit() const
Returned value Rate of margin charging on Stop Limit orders. Note The symbol should be selected by Name method.
2085
Standard Library
TradeTimeFlags
Gets the flags of the order expiration allowed modes.
int TradeTimeFlags() const
Returned value Flags of the order expiration allowed modes. Note The symbol should be selected by Name method.
2086
Standard Library
TradeFillFlags
Gets the flags of the order filling allowed modes.
int TradeFillFlags() const
Returned value Flags of the order filling allowed modes. Note The symbol should be selected by Name method.
2087
Standard Library
Digits
Gets the number of digits after period.
int Digits() const
Returned value Gets the number of digits after period. Note The symbol should be selected by Name method.
2088
Standard Library
Point
Gets the value of one point.
double Point() const
Returned value Value of one point. Note The symbol should be selected by Name method.
2089
Standard Library
TickValue
Gets the cost of tick (minimal change of price).
double TickValue() const
Returned value Cost of tick (minimal change of price). Note The symbol should be selected by Name method.
2090
Standard Library
TickValueProfit
Gets the calculated tick price for a profitable position.
double TickValueProfit() const
Returned value The calculated tick price for a profitable position. Note The symbol should be selected by Name method.
2091
Standard Library
TickValueLoss
Gets the calculated tick price for a losing position.
double TickValueLoss() const
Returned value The calculated tick price for a losing position. Note The symbol should be selected by Name method.
2092
Standard Library
TickSize
Gets the minimal change of price.
double TickSize() const
Returned value Minimal change of price. Note The symbol should be selected by Name method.
2093
Standard Library
ContractSize
Gets the amount of trade contract.
double ContractSize() const
Returned value Amount of trade contract. Note The symbol should be selected by Name method.
2094
Standard Library
LotsMin
Gets the minimal volume to close a deal.
double LotsMin() const
Returned value Minimal volume to close a deal. Note The symbol should be selected by Name method.
2095
Standard Library
LotsMax
Gets the maximal volume to close a deal.
double LotsMax() const
Returned value Maximal volume to close a deal. Note The symbol should be selected by Name method.
2096
Standard Library
LotsStep
Gets the minimal step of volume change to close a deal.
double LotsStep() const
Returned value Minimal step of volume change to close a deal. Note The symbol should be selected by Name method.
2097
Standard Library
LotsLimit
Gets the maximal allowed volume of opened position and pending orders (direction insensitive) for one symbol.
double LotsLimit() const
Returned value The maximal allowed volume of opened position and pending orders (direction insensitive) for one symbol. Note The symbol should be selected by Name method.
2098
Standard Library
SwapLong
Gets the value of long position swap.
double SwapLong() const
Returned value Value of long position swap. Note The symbol should be selected by Name method.
2099
Standard Library
SwapShort
Gets the value of short position swap.
double SwapShort() const
Returned value Value of short position swap. Note The symbol should be selected by Name method.
2100
Standard Library
CurrencyBase
Gets the name of symbol base currency.
string CurrencyBase() const
Returned value Name of symbol base currency. Note The symbol should be selected by Name method.
2101
Standard Library
CurrencyProfit
Gets the profit currency name.
string CurrencyProfit() const
Returned value Profit currency name. Note The symbol should be selected by Name method.
2102
Standard Library
CurrencyMargin
Gets the margin currency name.
string CurrencyMargin() const
Returned value Margin currency name. Note The symbol should be selected by Name method.
2103
Standard Library
Bank
Gets the name of current quote source.
string Bank() const
Returned value Name of current quote source. Note The symbol should be selected by Name method.
2104
Standard Library
Description
Gets the string description of symbol.
string Description() const
Returned value String description of symbol. Note The symbol should be selected by Name method.
2105
Standard Library
Path
Gets the path in symbols tree.
string Path() const
Returned value Gets the path in symbols tree. Note The symbol should be selected by Name method.
2106
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger( ENUM_SYMBOL_INFO_INTEGER prop_id, long& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of integer type property (value of ENUM_SYMBOL_INFO_INTEGER enumeration). var [out] Reference to long type variable to place result. Returned value true in case of success, false if unable to get property value. Note The symbol should be selected by Name method.
2107
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble( ENUM_SYMBOL_INFO_DOUBLE prop_id, double& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of double type property (value of ENUM_SYMBOL_INFO_DOUBLE enumeration). var [out] Reference to double type variable to place result. Returned value true in case of success, false if unable to get property value. Note The symbol should be selected by Name method.
2108
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString( ENUM_SYMBOL_INFO_STRING prop_id, string& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of text property. var [out] Reference to string type variable to place result. Returned value true in case of success, false if unable to get property value. Note The symbol should be selected by Name method.
2109
Standard Library
NormalizePrice
Returns the value of price, normalized using the symbol properties.
double NormalizePrice( double ) const price // price
Parameters price [in] Price. Returned value Normalized price. Note The symbol should be selected by Name method.
2110
Standard Library
COrderInfo
COrderInfo is a class for easy access to the pending order properties.
Description
COrderInfo class provides access to the pending order properties.
Declaration
class COrderInfo : public CObject
Title
#include <Trade\OrderInfo.mqh>
TypeTime
TypeTimeDescription
Gets the initial volume of order Gets the unfilled volume of order
2111
Standard Library
PriceOpen StopLoss TakeProfit PriceCurrent PriceStopLimit Access to text properties Symbol Comment Access to MQL5 API functions InfoInteger
Gets the order price Gets the order's Stop Loss Gets the order's Take Profit Gets the current price by order symbol Gets the price of setting limit order
Gets the value of specified integer type property Gets the value of specified double type property Gets value of specified string type property
Saves the order parameters Checks the current parameters against the saved parameters
Selection Select Selects an order by ticket for further access to its properties Selects an order by index for further access to its properties
SelectByIndex
2112
Standard Library
Ticket
Gets the ticket of an order, previously selected for access using the Select method.
ulong Ticket() const
Returned value Order ticket if successful, otherwise - ULONG_MAX. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2113
Standard Library
TimeSetup
Gets the time of order placement.
datetime TimeSetup() const
Returned value Time of order placement. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2114
Standard Library
OrderType
Gets the order type.
ENUM_ORDER_TYPE OrderType()
Returned value Order type (value of ENUM_ORDER_TYPE enumeration). Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2115
Standard Library
TypeDescription
Gets the order type as a string.
string TypeDescription() const
Returned value Order type as a string. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2116
Standard Library
State
Gets the order state.
ENUM_ORDER_STATE State() const
Returned value Order state (value of ENUM_ORDER_STATE enumeration). Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2117
Standard Library
StateDescription
Gets the order state as a string.
string StateDescription() const
Returned value Order state as a string. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2118
Standard Library
TimeExpiration
Gets the order expiration time.
datetime TimeExpiration() const
Returned value Order expiration time, set on its placement. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2119
Standard Library
TimeDone
Gets the time of order execution or cancellation.
datetime TimeDone() const
Returned value Time of order execution or cancellation. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2120
Standard Library
TypeFilling
Gets the order filling type.
ENUM_ORDER_TYPE_FILLING TypeFilling() const
Returned value Order filling type (value of ENUM_ORDER_TYPE_FILLING enumeration). Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2121
Standard Library
TypeFillingDescription
Gets the order filling type as a string.
string TypeFillingDescription() const
Returned value Order filling type as a string. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2122
Standard Library
TypeTime
Gets the type of order at the time of the expiration.
ENUM_ORDER_TYPE_TIME TypeTime() const
Returned value Type of order at the time of the expiration. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2123
Standard Library
TypeTimeDescription
Gets the order type by expiration time as a string.
string TypeTimeDescription() const
Returned value Order type by expiration time as a string. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2124
Standard Library
Magic
Gets the ID of expert, that placed the order.
long Magic() const
Returned value ID of expert, that placed the order. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2125
Standard Library
PositionId
Gets the ID of position.
long PositionId() const
Returned value ID of position, in which the order was involved. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2126
Standard Library
VolumeInitial
Gets the initial volume of order.
double VolumeInitial() const
Returned value Initial volume of order. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2127
Standard Library
VolumeCurrent
Gets the unfilled volume of order.
double VolumeCurrent() const
Returned value Unfilled volume of order. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2128
Standard Library
PriceOpen
Gets the order price.
double PriceOpen() const
Returned value Price of order placement. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2129
Standard Library
StopLoss
Gets the order's Stop Loss.
double StopLoss() const
Returned value Order's Stop Loss. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2130
Standard Library
TakeProfit
Gets the order's Take Profit.
double TakeProfit() const
Returned value Order's Take Profit. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2131
Standard Library
PriceCurrent
Gets the current price by order symbol.
double PriceCurrent() const
Returned value Current price by order symbol. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2132
Standard Library
PriceStopLimit
Gets the price of setting limit order.
double PriceStopLimit() const
Returned value Price of setting limit order. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2133
Standard Library
Symbol
Gets the name of order symbol.
string Symbol() const
Returned value Name of order symbol. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2134
Standard Library
Comment
Gets the order comment.
string Comment() const
Returned value Order comment. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2135
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger( ENUM_ORDER_PROPERTY_INTEGER prop_id, long& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of integer type property (value of ENUM_ORDER_PROPERTY_INTEGER enumeration). var [out] Reference to long type variable to place result. Returned value true in case of success, false if unable to get property value. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2136
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble( ENUM_ORDER_PROPERTY_DOUBLE prop_id, double& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of double type property (value of ENUM_ORDER_PROPERTY_DOUBLE enumeration). var [out] Reference to double type variable to place result. Returned value true in case of success, false if unable to get property value. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2137
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString( ENUM_ORDER_PROPERTY_STRING prop_id, string& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of text property. var [out] Reference to string type variable to place result. Returned value true in case of success, false if unable to get property value. Note The order should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2138
Standard Library
StoreState
Saves the order parameters.
void StoreState()
2139
Standard Library
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Returned value true - if the order parameters have changed since the last call of the StoreState() method, otherwise - false.
2140
Standard Library
Select
Selects an order by ticket for further access to its properties.
bool Select( ulong ) ticket // order ticket
2141
Standard Library
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex( int ) index // order index
2142
Standard Library
CHistoryOrderInfo
CHistoryOrderInfo is a class for easy access to the history order properties.
Description
CHistoryOrderInfo class provides easy access to the history order properties.
Declaration
class CHistoryOrderInfo : public CObject
Title
#include <Trade\HistoryOrderInfo.mqh>
TypeFilling TypeFillingDescription
Gets the type of order execution by remainder Gets the type of order execution by remainder as a string Gets the type of order at the time of the expiration Gets the order type by expiration time as a string Gets the ID of expert, that placed the order Gets the ID of position
TypeTime
TypeTimeDescription
Gets the initial volume of order Gets the unfilled volume of order Gets the order price
2143
Standard Library
StopLoss TakeProfit PriceCurrent PriceStopLimit Access to text properties Symbol Comment Access to MQL5 API functions InfoInteger
Gets the order's Stop Loss Gets the order's Take Profit Gets the current price by order symbol Gets the price of setting limit order
Gets the value of specified integer type property Gets the value of specified double type property Gets value of specified string type property
2144
Standard Library
TimeSetup
Gets the time of order placement.
datetime TimeSetup() const
Returned value Time of order placement. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2145
Standard Library
OrderType
Gets the order type.
ENUM_ORDER_TYPE OrderType() const
Returned value Order type (value of ENUM_ORDER_TYPE enumeration). Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2146
Standard Library
TypeDescription
Gets the order type as a string.
string TypeDescription() const
Returned value Order type as a string. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2147
Standard Library
State
Gets the order state.
ENUM_ORDER_STATE State() const
Returned value Order state (value of ENUM_ORDER_STATE enumeration). Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2148
Standard Library
StateDescription
Gets the order state as a string.
string StateDescription() const
Returned value Order state as a string. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2149
Standard Library
TimeExpiration
Gets the time of order expiration.
datetime TimeExpiration() const
Returned value Time of order expiration, set on its placement. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2150
Standard Library
TimeDone
Gets the time of order execution or cancellation.
datetime TimeDone() const
Returned value Time of order execution or cancellation. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2151
Standard Library
TypeFilling
Gets the type of order execution by remainder.
ENUM_ORDER_TYPE_FILLING TypeFilling() const
Returned value Type of order execution by remainder (value of ENUM_ORDER_TYPE_FILLING enumeration). Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2152
Standard Library
TypeFillingDescription
Gets the type of order execution by remainder as a string.
string TypeFillingDescription() const
Returned value Type order of execution by remainder as a string. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2153
Standard Library
TypeTime
Gets the type of order at the time of the expiration.
ENUM_ORDER_TYPE_TIME TypeTime() const
Returned value Type of order at the time of the expiration (value of ENUM_ORDER_TYPE_TIME enumeration). Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2154
Standard Library
TypeTimeDescription
Gets the order type by expiration time as a string.
string TypeTimeDescription() const
Returned value Order type by expiration time as a string. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2155
Standard Library
Magic
Gets the ID of the Expert Advisor, that placed the order.
long Magic() const
Returned value ID of the Expert Advisor, that placed the order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2156
Standard Library
PositionId
Gets the ID of position.
long PositionId() const
Returned value ID of position, in which the order was involved. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2157
Standard Library
VolumeInitial
Gets the initial volume of order.
double VolumeInitial() const
Returned value Initial volume of order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2158
Standard Library
VolumeCurrent
Gets the unfilled volume of order.
double VolumeCurrent() const
Returned value Unfilled volume of order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2159
Standard Library
PriceOpen
Gets the order price.
double PriceOpen() const
Returned value Price of order placement. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2160
Standard Library
StopLoss
Gets the Stop Loss price of the order.
double StopLoss() const
Returned value Stop Loss price of the order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2161
Standard Library
TakeProfit
Gets the the Take Profit price of the order.
double TakeProfit() const
Returned value The Take Profit price of the order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2162
Standard Library
PriceCurrent
Gets the current price of the order's symbol.
double PriceCurrent() const
Returned value The current price of order's symbol. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2163
Standard Library
PriceStopLimit
Gets the stop limit price of the order.
double PriceStopLimit() const
Returned value Stop Limit price of the order. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2164
Standard Library
Symbol
Gets the name of order symbol.
string Symbol() const
Returned value Name of order symbol. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2165
Standard Library
Comment
Gets the order comment.
string Comment() const
Returned value Order comment. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2166
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger( ENUM_ORDER_PROPERTY_INTEGER prop_id, long& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of integer type property (value of ENUM_ORDER_PROPERTY_INTEGER enumeration). var [out] Reference to long type variable to place result. Returned value true in case of success, false if unable to get property value. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2167
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble( ENUM_ORDER_PROPERTY_DOUBLE prop_id, double& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of double type property (value of ENUM_ORDER_PROPERTY_DOUBLE enumeration). var [out] Reference to double type variable to place result. Returned value true in case of success, false if unable to get property value. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2168
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString( ENUM_ORDER_PROPERTY_STRING prop_id, string& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of text property (value of ENUM_ORDER_PROPERTY_STRING enumeration). var [out] Reference to string type variable to place result. Returned value true in case of success, false if unable to get property value. Note The historical order should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2169
Standard Library
2170
Standard Library
SelectByIndex
Selects an order by index for further access to its properties.
bool SelectByIndex( int ) index // order index
2171
Standard Library
CPositionInfo
CPositionInfo is a class for easy access to the open position properties.
Description
CPositionInfo class provides easy access to the open position properties.
Declaration
class CPositionInfo : public CObject
Title
#include <Trade\PositionInfo.mqh>
InfoDouble
2172
Standard Library
Saves the position parameters Checks the current parameters against the saved parameters
2173
Standard Library
Time
Gets the time of position opening.
datetime Time() const
Returned value Time of position opening. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2174
Standard Library
PositionType
Gets the position type.
ENUM_POSITION_TYPE PositionType() const
Returned value Position type (value of ENUM_POSITION_TYPE enumeration). Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2175
Standard Library
TypeDescription
Gets the position type as a string.
string TypeDescription() const
Returned value Position type as a string. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2176
Standard Library
Magic
Gets the ID of Expert Advisor, opened the position.
long Magic() const
Returned value ID of the Expert Advisor, opened the position. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2177
Standard Library
Identifier
Gets the ID of position.
long Identifier() const
Returned value ID of position. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2178
Standard Library
Volume
Gets the volume of position.
double Volume() const
Returned value Volume of position. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2179
Standard Library
PriceOpen
Gets the price of position opening.
double PriceOpen() const
Returned value Position open price. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2180
Standard Library
StopLoss
Gets the Stop Loss price of the position.
double StopLoss() const
Returned value The Stop Loss price of the position. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2181
Standard Library
TakeProfit
Gets the Take Profit price of the position.
double TakeProfit() const
Returned value The Take Profit price of the position. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2182
Standard Library
PriceCurrent
Gets the current price by position symbol.
double PriceCurrent() const
2183
Standard Library
Commission
Gets the amount of commission of the position.
double Commission() const
Returned value Amount of commission of the position (in deposit currency). Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2184
Standard Library
Swap
Gets the amount of swap of the position.
double Swap() const
Returned value Amount of swap of the position (in deposit currency). Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2185
Standard Library
Profit
Gets the amount of current profit of the position.
double Profit() const
Returned value Amount of current profit of the position (in deposit currency). Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2186
Standard Library
Symbol
Gets the name of position symbol.
string Symbol() const
Returned value Name of position symbol. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2187
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger( ENUM_POSITION_PROPERTY_INTEGER prop_id, long& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of integer type property (value of ENUM_POSITION_PROPERTY_INTEGER enumeration). var [out] Reference to long type variable to place result. Returned value true in case of success, false if unable to get property value. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2188
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble( ENUM_POSITION_PROPERTY_DOUBLE prop_id, double& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of double type property (value of ENUM_POSITION_PROPERTY_DOUBLE enumeration). var [in] Reference to double type variable to place result. Returned value true in case of success, false if unable to get property value. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2189
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString( ENUM_POSITION_PROPERTY_STRING prop_id, string& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of text property (value of ENUM_POSITION_PROPERTY_STRING enumeration). var [out] Reference to string type variable to place result. Returned value true in case of success, false if unable to get property value. Note The position should be selected using the Select (by ticket) or SelectByIndex (by index) methods.
2190
Standard Library
Select
Select the position for further work.
bool Select( const string symbol ) // symbol
2191
Standard Library
SelectByIndex
Selects the position by index for further access to its properties.
bool SelectByIndex( int ) index // position index
2192
Standard Library
StoreState
Saves the position parameters.
void StoreState()
2193
Standard Library
CheckState
Checks the current parameters against the saved parameters.
bool CheckState()
Returned value true - if the position parameters have changed since the last call of the StoreState() method, otherwise - false.
2194
Standard Library
CDealInfo
CDealInfo is a class for easy access to the deal properties.
Description
CDealInfo class provides access to the deal properties.
Declaration
class CDealInfo : public CObject
Title
#include <Trade\DealInfo.mqh>
Access to double type properties Volume Price Commision Swap Gets the volume of deal Gets the deal price Gets the amount of commission by deal Gets the amount of swap when position is closed Gets the financial result of deal
Profit Access to text properties Symbol Comment Access to MQL5 API functions InfoInteger
2195
Standard Library
property InfoDouble InfoString Selection Ticket SelectByIndex Gets ticket/selects the deal Selects the deal by index Gets the value of specified double type property Gets value of specified string type property
2196
Standard Library
Order
Gets the order by which the deal is executed.
long Order() const
Returned value Order by which the deal is executed. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2197
Standard Library
Time
Gets the time of deal execution.
datetime Time() const
Returned value Time of deal execution. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2198
Standard Library
DealType
Gets the deal type.
ENUM_DEAL_TYPE DealType() const
Returned value Deal type (value of ENUM_DEAL_TYPE enumeration). Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2199
Standard Library
TypeDescription
Gets the deal type as a string.
string TypeDescription() const
Returned value Deal type as a string. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2200
Standard Library
Entry
Gets the deal direction.
ENUM_DEAL_ENTRY Entry() const
Returned value Deal direction (value of ENUM_DEAL_ENTRY enumeration.). Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2201
Standard Library
EntryDescription
Gets the deal direction as a string.
string EntryDescription() const
Returned value Deal direction as a string. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2202
Standard Library
Magic
Gets the ID of the Expert Advisor, that executed the deal.
long Magic() const
Returned value ID of the Expert Advisor, that executed the deal. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2203
Standard Library
PositionId
Gets the ID of position, in which the deal was involved.
long PositionId() const
Returned value ID of position, in which the deal was involved. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2204
Standard Library
Volume
Gets the volume of deal.
double Volume() const
Returned value Volume of deal. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2205
Standard Library
Price
Gets the deal price.
double Price() const
Returned value Deal price. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2206
Standard Library
Commission
Gets the amount of commission of the deal.
double Commission() const
Returned value Amount of commission of the deal. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2207
Standard Library
Swap
Gets the amount of swap when position is closed.
double Swap() const
Returned value Amount of swap when position is closed. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2208
Standard Library
Profit
Gets the financial result of the deal.
double Profit() const
Returned value Financial result of the deal (in deposit currency). Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2209
Standard Library
Symbol
Gets the name of the deal symbol.
string Symbol() const
Returned value Name of the deal symbol. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2210
Standard Library
Comment
Gets the deal comment.
string Comment() const
Returned value Deal comment. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2211
Standard Library
InfoInteger
Gets the value of specified integer type property.
bool InfoInteger( ENUM_DEAL_PROPERTY_INTEGER prop_id, long& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of integer type property (value of ENUM_DEAL_PROPERTY_INTEGER enumeration). var [out] Reference to long type variable to place result. Returned value true in case of success, false if unable to get property value. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2212
Standard Library
InfoDouble
Gets the value of specified double type property.
bool InfoDouble( ENUM_DEAL_PROPERTY_DOUBLE prop_id, double& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of double type property (value of ENUM_DEAL_PROPERTY_DOUBLE enumeration). var [in] Reference to double type variable to place result. Returned value true in case of success, false if unable to get property value. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2213
Standard Library
InfoString
Gets the value of specified string type property.
bool InfoString( ENUM_DEAL_PROPERTY_STRING prop_id, string& ) const var // property ID // reference to variable
Parameters prop_id [in] ID of text property (value of ENUM_DEAL_PROPERTY_STRING enumeration). var [out] Reference to string type variable to place result. Returned value true in case of success, false if unable to get property value. Note The deal should be selected using the Ticket (by ticket) or SelectByIndex (by index) methods.
2214
Standard Library
2215
Standard Library
SelectByIndex
Selects the deal by index for further access to its properties.
bool SelectByIndex( int ) index // order index
Returned value true in case of success, false if unable to select the deal.
2216
Standard Library
CTrade
CTrade is a class for easy access to the trade functions.
Description
CTrade class provides easy access to the trade functions.
Declaration
class CTrade : public CObject
Title
#include <Trade\Trade.mqh>
Sell
position
with
specified
BuyLimit
Places the pending order of Buy Limit type with specified parameters Places the pending order of Buy Stop type with specified parameters
BuyStop
2217
Standard Library
SellLimit
Places the pending order of Sell Limit type with specified parameters Places the pending order of Sell Stop type with specified parameters
SellStop
Access to the last request parameters Request RequestAction RequestActionDescription RequestMagic RequestOrder RequestSymbol Gets the copy of the last request structure Gets the trade operation type Gets the trade operation type as string Gets the magic number of the Expert Advisor Gets the order ticket, used in the last request Gets the name of the symbol, used in the last request Gets the trade volume (in lots), used in the last request Gets the price, used in the last request Gets the price of pending order of Stop Limit type, used in the last request Gets the Stop Loss price of the order, used in the last request Gets the Take Profit price of the order, used in the last request Gets the price deviation of the order, used in the last request Gets the type of the order, used in the last request Gets the type of the order (as string) , used in the last request Gets the filling type of the order, used in the last request Gets the filling type of the order (as string), used in the last request Gets the validity period of the order, used in the last request Gets the validity period of the order (as string), used in the last request Gets the expiration time of the order, used in the last request Gets the comment of the order, used in the last
RequestVolume
RequestPrice RequestStopLimit
RequestSL
RequestTP
RequestDeviation
RequestType
RequestTypeDescription
RequestTypeFilling
RequestTypeFillingDescription
RequestTypeTime
RequestTypeTimeDescription
RequestExpiration
RequestComment
2218
Standard Library
request Access to the last request checking results CheckResult Gets the copy of the structure of the last request check result. Gets the value of the retcode field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the string description of the retcode field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the balance field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the equity field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the profit field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the margin field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the margin_free field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the margin_level field of MqlTradeCheckResult type, filled while checking of the request correctness Gets the value of the comment field of MqlTradeCheckResult type, filled while checking of the request correctness
CheckResultRetcode
CheckResultRetcodeDescription
CheckResultBalance
CheckResultEquity
CheckResultProfit
CheckResultMargin
CheckResultMarginFree
CheckResultMarginLevel
CheckResultComment
Access to the last request execution results Result Gets the copy of the structure of the last request result Gets the code of request result Gets the code of request result as text Gets the deal ticket Gets the order ticket Gets the volume of deal or order
2219
Standard Library
Gets the price, confirmed by broker Gets the current bid price (the requote) Gets the current ask price (the requote) Gets the broker comment
Prints the last request parameters into journal Prints the results of the last request into journal Prepares the formatted string with last request parameters Prepares the formatted string with results of the last request execution
FormatRequest
FormatRequestResult
2220
Standard Library
LogLevel
Sets logging level for messages.
void LogLevel( int log_level ) // logging level
Parameters log_level [in] Logging level. Returned value None. Note Log_level = 0 - logging disabled (used in optimization mode). Log_level = 1 - logging error messages (default). Log_level = 2 - logging all messages (used in testing mode).
2221
Standard Library
SetExpertMagicNumber
Sets the expert ID.
void SetExpertMagicNumber( ulong magic ) // ID
2222
Standard Library
SetDeviationInPoints
Sets the allowed deviation.
void SetDeviationInPoints( ulong deviation ) // deviation
2223
Standard Library
SetTypeFilling
Sets filling type of the order.
void SetTypeFilling( ENUM_ORDER_TYPE_FILLING filling ) // order filling type
Parameters filling [in] Order filling type (value of ENUM_ORDER_TYPE_FILLING enumeration). Returned value None.
2224
Standard Library
OrderOpen
Places the pending order with set parameters.
bool OrderOpen( const string ENUM_ORDER_TYPE double double double double double symbol, order_type, volume, limit_price, price, sl, tp, // symbol // order type // order volume // StopLimit price // execution price // Stop Loss price // Take Profit price // type by expiration // expiration // comment
Parameters symbol [in] Name of trade instrument. order_type [in] Type of order trade operation (value of ENUM_ORDER_TYPE enumeration). volume [in] Requested order volume. limit_price [in] Price at which the StopLimit order will be placed. price [in] Price at which the order must be executed. sl [in] Price at which the Stop Loss will trigger. tp [in] Price at which the Take Profit will trigger. type_time [in] Order type by execution (value of ENUM_ORDER_TYPE_TIME enumeration). expiration [in] Expiration date of pending order. comment="" [in] Order comment. Returned value true - in case of successful check of the basic structures, otherwise - false.
2225
Standard Library
Note Successful completion of the OrderSend(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultOrder().
2226
Standard Library
OrderModify
Modifies the pending order parameters.
bool OrderModify( ulong double double double ticket, price, sl, tp, // order ticket // execution price // Stop Loss price // Take Profit price // type by expiration // expiration
Parameters ticket [in] Order ticket. price [in] The new price by which the order must be executed (or the previous value, if the change is not necessary). sl [in] The new price by which the Stop Loss will trigger (or the previous value, if the change is not necessary). tp [in] The new price by which the Take Profit will trigger (or the previous value, if the change is not necessary). type_time [in] The new type of order by expiration (or the previous value, if the change is not necessary), value of ENUM_ORDER_TYPE_TIME enumeration. expiration [in] The new expiration date of pending order (or the previous value, if the change is not necessary). Returned value true - in case of successful check of the basic structures, otherwise - false. Note Successful completion of the OrderModify(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode().
2227
Standard Library
OrderDelete
Deletes the pending order.
bool OrderDelete( ulong ticket ) // order ticket
Parameters ticket [in] Order ticket. Returned value true - in case of successful check of the basic structures, otherwise - false. Note Successful completion of the OrderDelete(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode().
2228
Standard Library
PositionOpen
Opens the position with set parameters.
bool PositionOpen( const string symbol, // symbol // position type // position volume // execution price // Stop Loss price // Take Profit price // comment ENUM_ORDER_TYPE order_type, double double double double const string ) volume, price, sl, tp, comment=""
Parameters symbol [in] Name of trade instrument, by which it is intended to open position. order_type [in] Type of position trade operation (value of ENUM_ORDER_TYPE enumeration). volume [in] Requested position volume. price [in] Price at which the position must be opened. sl [in] Price at which the Stop Loss will trigger. tp [in] Price at which the Take Profit will trigger. comment="" [in] Position comment. Returned value true - in case of successful check of the basic structures, otherwise - false. Note Successful completion of the PositionOpen(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2229
Standard Library
PositionModify
Modifies the position parameters by specified symbol.
bool PositionModify( const string symbol, double double ) sl, tp // symbol // Stop Loss price // Take Profit price
Parameters symbol [in] Name of trade instrument, by which it is intended to modify position. sl [in] The new price by which the Stop Loss will trigger (or the previous value, if the change is not necessary). tp [in] The new price by which the Take Profit will trigger (or the previous value, if the change is not necessary). Returned value true - in case of successful check of the basic structures, otherwise - false. Note Successful completion of the PositionModify(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode().
2230
Standard Library
PositionClose
Closes the position by specified symbol.
bool PositionClose( const string symbol, ulong ) deviation=ULONG_MAX // symbol // deviation
Parameters symbol [in] Name of trade instrument, by which it is intended to close position. deviation=ULONG_MAX [in] Maximal deviation from the current price (in points). Returned value true - in case of successful check of the basic structures, otherwise - false. Note Successful completion of the PositionClose(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode().
2231
Standard Library
Buy
Opens a long position with specified parameters.
bool Buy( double volume, // position volume // symbol // price // stop loss price // take profit price // comment const string symbol=NULL, double double double price=0.0, sl=0.0, tp=0.0,
Parameters volume [in] Position volume. symbol=NULL [in] Position symbol. If the symbol isn't specified, the current symbol will be used. price=0.0 [in] Price. If the price isn't specified, the current market Ask price will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. comment="" [in] Comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the Buy(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2232
Standard Library
Sell
Opens a short position with specified parameters.
bool Sell( double volume, // position volume // symbol // price // stop loss price // take profit price // comment const string symbol=NULL, double double double price=0.0, sl=0.0, tp=0.0,
Parameters volume [in] Position volume. symbol=NULL [in] Position symbol. If the symbol isn't specified, the current symbol will be used. price=0.0 [in] Price. If the price isn't specified, the current market Bid price will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. comment="" [in] Comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the Sell(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2233
Standard Library
BuyLimit
Places the pending order of Buy Limit type (buy at the price, lower than current market price) with specified parameters.
bool BuyLimit( double double const string double double volume, price, symbol=NULL, sl=0.0, tp=0.0, // order volume // order price // symbol // stop loss price // take profit price // order lifetime // order expiration time // comment
Parameters volume [in] Order volume. price [in] Order price. symbol=NULL [in] Order symbol. If the symbol isn't specified, the current symbol will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. type_time=ORDER_TIME_GTC [in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration). expiration=0 [in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED). comment="" [in] Order comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the BuyLimit(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2234
Standard Library
BuyStop
Places the pending order of Buy Stop type (buy at the price, higher than current market price) with specified parameters.
bool BuyStop( double double const string double double volume, price, symbol=NULL, sl=0.0, tp=0.0, // order volume // order price // symbol // stop loss price // take profit price // order lifetime // order expiration time // comment
Parameters volume [in] Order volume. price [in] Order price. symbol=NULL [in] Order symbol. If the symbol isn't specified, the current symbol will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. type_time=ORDER_TIME_GTC [in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration). expiration=0 [in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED). comment="" [in] Order comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the BuyStop(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2235
Standard Library
SellLimit
Places the pending order of Sell Limit type (sell at the price, higher than current market price) with specified parameters.
bool SellLimit( double double const string double double volume, price, symbol=NULL, sl=0.0, tp=0.0, // order volume // order price // symbol // stop loss price // take profit price // order lifetime // order expiration time // comment
Parameters volume [in] Order volume. price [in] Order price. symbol=NULL [in] Order symbol. If the symbol isn't specified, the current symbol will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. type_time=ORDER_TIME_GTC [in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration). expiration=0 [in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED). comment="" [in] Order comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the SellLimit(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2236
Standard Library
SellStop
Places the pending order of Buy Stop type (sell at the price, lower than current market price) with specified parameters.
bool SellStop( double double const string double double volume, price, symbol=NULL, sl=0.0, tp=0.0, // order volume // order price // symbol // stop loss price // take profit price // order lifetime // order expiration time // comment
Parameters volume [in] Order volume. price [in] Order price. symbol=NULL [in] Order symbol. If the symbol isn't specified, the current symbol will be used. sl=0.0 [in] Stop Loss price. tp=0.0 [in] Take Profit price. type_time=ORDER_TIME_GTC [in] Order lifetime (value of ENUM_ORDER_TYPE_TIME enumeration). expiration=0 [in] Order expiration time (used only if type_time=ORDER_TIME_SPECIFIED). comment="" [in] Order comment. Returned value true - in case of successful check of the structures, otherwise - false. Note Successful completion of the SellStop(...) method does not always mean successful execution of the trade operation. It's necessary to check the result of trade request (trade server return code) using ResultRetcode() and value, returned by ResultDeal().
2237
Standard Library
Request
Gets the copy of the last request structure.
void Request( MqlTradeRequest& request ) const // target structure
Parameters request [out] Reference to the structure of MqlTradeRequest type. Returned value None.
2238
Standard Library
RequestAction
Gets the trade operation type.
ENUM_TRADE_REQUEST_ACTIONS RequestAction() const
2239
Standard Library
RequestActionDescription
Gets the trade operation type as string.
string RequestActionDescription() const
Returned value Trade operation type (as string), used in the last request.
2240
Standard Library
RequestMagic
Gets the magic number of the Expert Advisor.
ulong RequestMagic() const
Returned value The magic number (ID) of the Expert Advisor, used in the last request.
2241
Standard Library
RequestOrder
Gets the order ticket, used in the last request.
ulong RequestOrder() const
2242
Standard Library
RequestSymbol
Gets the name of the symbol, used in the last request.
string RequestSymbol() const
Returned value The name of the symbol, used in the last request.
2243
Standard Library
RequestVolume
Gets the trade volume (in lots), used in the last request.
double RequestVolume() const
Returned value The trade volume (in lots), used in the last request.
2244
Standard Library
RequestPrice
Gets the price, used in the last request.
double RequestPrice() const
2245
Standard Library
RequestStopLimit
Gets the price of pending order of Stop Limit type, used in the last request.
double RequestStoplimit() const
Returned value The price of pending order of Stop Limit type, used in the last request.
2246
Standard Library
RequestSL
Gets the Stop Loss price of the order, used in the last request.
double RequestSL() const
Returned value The Stop Loss price, used in the last request.
2247
Standard Library
RequestTP
Gets the Take Profit price of the order, used in the last request.
double RequestTP() const
Returned value The Take Profit price, used in the last request.
2248
Standard Library
RequestDeviation
Gets the price deviation of the order, used in the last request.
ulong RequestDeviation() const
Returned value The price deviation of the order, used in the last request.
2249
Standard Library
RequestType
Gets the type of the order, used in the last request.
ENUM_ORDER_TYPE RequestType() const
Returned value Order type, used in the last request (value of ENUM_ORDER_TYPE enumeration).
2250
Standard Library
RequestTypeDescription
Gets the type of the order (as string) , used in the last request.
string RequestTypeDescription() const
Returned value The order type (as string), used in the last request.
2251
Standard Library
RequestTypeFilling
Gets the filling type of the order, used in the last request.
ENUM_ORDER_TYPE_FILLING RequestTypeFilling() const
Returned value The filling type of the order (value of ENUM_ORDER_TYPE_FILLING), used in the last request.
2252
Standard Library
RequestTypeFillingDescription
Gets the filling type of the order (as string), used in the last request.
string RequestTypeFillingDescription() const
Returned value The filling type (as string) of the order, used in the last request.
2253
Standard Library
RequestTypeTime
Gets the validity period of the order, used in the last request.
ENUM_ORDER_TYPE_TIME RequestTypeTime() const
Returned value The validity period of the order (value of ENUM_ORDER_TYPE_TIME enumeration), used in the last request.
2254
Standard Library
RequestTypeTimeDescription
Gets the validity period of the order (as string), used in the last request.
string RequestTypeTimeDescription() const
Returned value The validity period of the order (as string), used in the last request.
2255
Standard Library
RequestExpiration
Gets the expiration time of the order, used in the last request.
datetime RequestExpiration() const
Returned value The expiration time of the order, used in the last request.
2256
Standard Library
RequestComment
Gets the comment of the order, used in the last request.
string RequestComment() const
Returned value The comment of the order, used in the last request.
2257
Standard Library
Result
Gets the copy of the structure of the last request result.
void Result( MqlTradeResult& result ) const // reference
Parameters result [out] Reference to the structure of MqlTradeRequest type. Returned value None.
2258
Standard Library
ResultRetcode
Gets the code of request result.
uint ResultRetcode() const
2259
Standard Library
ResultRetcodeDescription
Gets the code of request result as text.
string ResultRetcodeDescription() const
2260
Standard Library
ResultDeal
Gets the deal ticket.
ulong ResultDeal() const
2261
Standard Library
ResultOrder
Gets the order ticket.
ulong ResultOrder() const
2262
Standard Library
ResultVolume
Gets the volume of deal or order.
double ResultVolume() const
2263
Standard Library
ResultPrice
Gets the price, confirmed by broker.
double ResultPrice() const
2264
Standard Library
ResultBid
Gets the current bid price (the requote).
double ResultBid() const
2265
Standard Library
ResultAsk
Gets the current ask price (the requote).
double ResultAsk() const
2266
Standard Library
ResultComment
Gets the broker comment.
string ResultComment() const
2267
Standard Library
CheckResult
Gets the copy of the structure of the last request check result.
void CheckResult( MqlTradeCheckResult& check_result ) const // reference
Parameters check_result [out] Reference to the target structure of the MqlTradeCheckResult type. Returned value None.
2268
Standard Library
CheckResultRetcode
Gets the value of the retcode field of MqlTradeCheckResult type, filled while checking of the request correctness.
uint CheckResultRetcode() const
Returned value The value of the retcode field (error code) of MqlTradeCheckResult type, filled while checking of the request correctness.
2269
Standard Library
CheckResultRetcodeDescription
Gets the string description of the retcode field of MqlTradeCheckResult type, filled while checking of the request correctness.
string ResultRetcodeDescription() const
Returned value The string description of the retcode field (Error code) of MqlTradeCheckResult type, filled while checking of the request correctness.
2270
Standard Library
CheckResultBalance
Gets the value of the balance field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultBalance() const
Returned value The value of the balance field (balance value that will be after the execution of the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2271
Standard Library
CheckResultEquity
Gets the value of the equity field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultEquity() const
Returned value The value of the equity field (equity value that will be after the execution of the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2272
Standard Library
CheckResultProfit
Gets the value of the profit field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultProfit() const
Returned value The value of the profit field (profit value that will be after the execution of the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2273
Standard Library
CheckResultMargin
Gets the value of the margin field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultMargin() const
Returned value The value of the margin field (margin required for the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2274
Standard Library
CheckResultMarginFree
Gets the value of the margin_free field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultMarginFree() const
Returned value The value of the margin_free field (free margin that will be left after the execution of the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2275
Standard Library
CheckResultMarginLevel
Gets the value of the margin_level field of MqlTradeCheckResult type, filled while checking of the request correctness.
double CheckResultMarginLevel() const
Returned value The value of the margin_level field (margin level that will be set after the execution of the trade operation) of MqlTradeCheckResult type, filled while checking of the request correctness.
2276
Standard Library
CheckResultComment
The value of the comment field of MqlTradeCheckResult type, filled while checking of the request correctness.
string CheckResultComment() const
Returned value The value of the comment field (Comment to the reply code, error description) of MqlTradeCheckResult type, filled while checking of the request correctness.
2277
Standard Library
PrintRequest
Prints the last request parameters into journal.
void PrintRequest() const
2278
Standard Library
PrintResult
Prints the results of the last request into journal.
void PrintResult() const
2279
Standard Library
FormatRequest
Prepares the formatted string with last request parameters.
string FormatRequest( string& str, // target string // request const MqlTradeRequest& request ) const
Parameters str [in] Target string, passed by reference. request [in] A structure of MqlTradeRequest type with parameters of the last request. Returned value None.
2280
Standard Library
FormatRequestResult
Prepares the formatted string with results of the last request execution.
string FormatRequestResult( string& str, // string // request structure // result structure const MqlTradeRequest& request, const MqlTradeResult& ) const result
Parameters str [in] Target string, passed by reference. request [in] A structure of MqlTradeRequest type with parameters of the last request. result [in] A structure of MqlTradeResult type with results of the last request. Returned value None.
2281
Standard Library
Description This class implements trading signals based on the strategy that uses three exponentially smoothed moving averages This class implements trading signals based on the strategy when price crossovers the exponentially smoothed moving average confirmed by ADX indicator This class implements trading signals based on the strategy when price crossovers the lines of the Alligator indicator This class implements trading signals based on the reversal candlestick pattern This class implements trading signals based on the reversal candlestick pattern confirmed by RSI indicator This class implements trading signals based on the reversal candlestick pattern confirmed by Stochastic indicator This class implements trading signals based on the crossover of two exponentially smoothed moving averages This class implements trading signals based on the crossover of two moving averages This class implements trading signals based on the price crossover with moving average
CSignalADX_MA
CSignalAlligator
CSignalCandles
CSignalCandlesRSI
CSignalCandlesStoch
CSignalCrossEMA
CSignalCrossMA
CSignalMA
2282
Standard Library
CSignalMACD
This class implements trading signals based on the crossover of main and signal lines of MACD indicator This class implements trading signals based on the price crossover with simple moving average This class implements filtration of signals, based on specified time periods trade
CSignalMovingAverage
CSignalITF
CSignal2EMA_ITF
This class implements trading signal algorithm, based on crossover of two exponentially smoothed moving averages with signal filtration, based on specified time periods
Description This class implements Trailing Stop algorithm based on fixed points This class implements Trailing Stop algorithm based on the values of Moving Average indicator A gag class, it doesn't uses any Trailing Stop algorithm This class implements Trailing Stop algorithm based on the values of Parabolic SAR indicator
CTrailingMA
CTrailingNone
CTrailingPSAR
Description A class with an algorithm, based on trading with predefined fixed lot size. A class with an algorithm, based on trading with predefined fixed margin. A class with an algorithm, based on trading with predefined risk. A class with an algorithm, based on trading with minimal allowed lot size. A class with an algorithm, based on trading with variable lot size, depending on the results of the previous deals.
CMoneyFixedMargin
CMoneyFixedRisk
CMoneyNone
CMoneySizeOptimized
2283
Standard Library
2284
Standard Library
CExpert
CExpert is a base class for trading strategies. It has built-in algorithms for working with time series and indicators and a set of virtual methods for trading strategy. How to use it: 1. Prepare an algorithm of the strategy; 2. Create your own class, inherited from CExpert class; 3. Override the virtual methods in your class with your own algorithms.
Description
The CExpert class is a set of virtual methods for implementation of trading strategies.
Declaration
class CExpert : public CObject
Title
#include <Expert\CExpert.mqh>
Protected methods:
Initialization/Deinitialization
2285
Standard Library
virtual InitParameters virtual InitIndicators virtual InitTrade virtual DeinitTrade virtual DeinitSignal virtual DeinitTrailing virtual DeinitMoney virtual DeinitIndicators Update Methods virtual Refresh Processing Methods virtual Processing Market Entry Methods virtual CheckOpen virtual CheckOpenLong virtual CheckOpenShort virtual OpenLong virtual CheckOpenShort Market Exit Methods virtual CheckClose virtual CheckCloseLong virtual CheckCloseShort virtual CloseAll virtual Close virtual CloseLong virtual CloseShort Position Reverse Methods virtual CheckReverse virtual CheckReverseLong virtual CheckReverseShort virtual ReverseLong virtual ReverseShort
Parameters initialization method Indicators initialization method Initializes Trade object Deinitializes Trade object Deinitializes Trading Signal object Deinitializes Trailing Stop object Deinitializes Money Management object Deinitializes Indicators
Checks position opening conditions Checks conditions to open long position Checks conditions to open short position Opens the long position Opens the short position
Checks conditions to close current position Checks conditions to close long position Checks conditions to close short position Closes the opened position and delete all orders Closes the opened position Closes the long position Closes the short position
Checks conditions to reverse opened position Checks conditions to reverse long position Checks conditions to reverse short position Perform reverse operation of long position Perform reverse operation of short position
2286
Standard Library
Checks Trailing Stop conditions of long position Checks Trailing Stop conditions position of short
Performs Trailing Stop for long position Performs Trailing Stop for short position Checks Trailing Stop conditions of buy limit/ stop pending order Checks Trailing Stop conditions of sell limit/ stop pending order Performs Trailing Stop for buy limit/stop pending order Performs Trailing Stop for sell limit/stop pending order
virtual CheckTrailingOrderShort
virtual TrailingOrderLong
virtual TrailingOrderShort
Order Delete Methods virtual CheckDeleteOrderLong virtual CheckDeleteOrderShort virtual DeleteOrders virtual DeleteOrder virtual DeleteOrderLong virtual DeleteOrderShort Trade Volume Methods LotOpenLong LotOpenShort LotReverse Gets trade volume for buy operation Gets trade volume for sell operation Gets trade operation volume for position reverse Checks conditions to delete buy pending order Checks conditions to delete sell pending order Deletes all orders Deletes the stop/limit pending order Deletes the buy limit/stop pending order Deletes the sell limit/stop pending order
Trade History Methods PrepareHistoryDate HistoryPoint Sets starting date for trade history tracking Creates checkpoint of trade history (saves number of positions, orders, deals and historical orders) Compares the current state with the saved one and calls the corresponding event handle
CheckTradeState
Event flags
2287
Standard Library
Sets event waiting flag Resets event waiting flag Gets the flag of "Position opened" event tracking Gets the flag of "Volume changed" event tracking Gets the flag of "Position modified" event tracking Gets the flag of "Position closed" event tracking Gets the flag of "Position Stop Loss/Take Profit triggered" event tracking Gets the flag of "Pending order placed" event tracking Gets the flag of "Pending order modified" event tracking Gets the flag of "Pending order deleted" event tracking Gets the flag of "Pending order triggered" event tracking
IsWaitingPositionVolumeChanged
IsWaitingPositionModified
IsWaitingPositionClosed IsWaitingPositionStopTake
IsWaitingOrderPlaced
IsWaitingOrderModified
IsWaitingOrderDeleted
IsWaitingOrderTriggered
Event Processing Methods virtual TradeEventPositionStopTake "Position Stop Loss/Take Profit triggered" event handler "Pending order triggered" event handler "Position opened" event handler "Position volume changed" event handler "Position modified" event handler "Position closed" event handler "Pending order placed" event handler "Pending order modified" event handler "Pending order deleted" event handler Event handler of the non-identified event
virtual TradeEventOrderTriggered virtual TradeEventPositionOpened virtual TradeEventPositionVolumeChanged virtual TradeEventPositionModified virtual TradeEventPositionClosed virtual TradeEventOrderPlaced virtual TradeEventOrderModified virtual TradeEventOrderDeleted virtual TradeEventNotIdentified Service methods TimeframeAdd TimeframesFlags
Adds a timeframe to track Gets the flag indicating timeframes with a new bar
2288
Standard Library
Init
Class instance initialization method.
bool Init( string symbol, // Symbol // Period // Flag // Magic number ENUM_TIMEFRAMES period, bool long ) every_tick, magic==0
Parameters symbol [in] Symbol. period [in] Period (ENUM_TIMEFRAMES enumeration). every_tick [in] Flag. magic==0 [in] Expert Advisor ID (Magic number). Returned value true if successful, overwise false.
2289
Standard Library
InitSignal
Initializes Trading Signal object.
virtual bool InitSignal( CExpertSignal* signal==NULL ) // Pointer
Parameters signal==NULL [in] Pointer to the CExpertSignal class object (or its heir). Returned value true if successful, overwise false. Note If signal is NULL, the CExpertSignal class will be used, it does nothing.
2290
Standard Library
InitTrailing
Initializes Trailing Stop object.
virtual bool InitTrailing( CExpertTrailing* trailing==NULL ) // pointer
Parameters trailing==NULL [in] Pointer to the CExpertTrailing class object (or its heir). Returned value true if successful, overwise false. Note If trailing is NULL, the ExpertTrailing class will be used, it does nothing.
2291
Standard Library
InitMoney
Initializes the Money Management object.
virtual bool InitMoney( CExpertMoney* money==NULL ) // pointer
Parameters money==NULL [in] Pointer to the CExpertMoney class object (or its heir). Returned value true if successful, overwise false. Note If money is NULL, the ExpertMoney class will be used, it does nothing.
2292
Standard Library
Deinit
Class instance deinitialization method.
virtual void Deinit()
2293
Standard Library
Parameters max_orders [in] New value of maximal allowed number of orders. Note By default, the maximal allowed number of orders is equal to 1.
2294
Standard Library
OnTick
The OnTick event handler.
virtual void OnTick()
Returned value None. Note It calls Refresh and Processing virtual methods.
2295
Standard Library
OnTrade
The OnTrade event handler.
virtual void OnTrade()
2296
Standard Library
OnTimer
The OnTimer event handler.
virtual void OnTimer()
2297
Standard Library
InitParameters
Initializes parameters.
virtual bool InitParameters()
Returned value true if successful, overwise false. Note The InitParameters() function of CExpert base class does nothing and always returns true.
2298
Standard Library
InitIndicators
Initializes all indicators and time series.
virtual bool InitIndicators()
Returned value true if successful, overwise false. Note It calls consequentially InitIndicators() virtual methods of trading signal, trailing stop and money management objects.
2299
Standard Library
InitTrade
Initializes Trade object.
virtual bool InitTrade( long magic ) // Magic number
Parameters magic [in] Magic number of Expert Advisor, it will be used in trade operations. Returned value true if successful, overwise false.
2300
Standard Library
DeinitTrade
Deinitializes Trade object.
virtual void DeinitTrade()
2301
Standard Library
DeinitSignal
Deinitializes Expert Signal object.
virtual void DeinitSignal()
2302
Standard Library
DeinitTrailing
Deinitializes Trailing Stop object.
virtual void DeinitTrailing()
2303
Standard Library
DeinitMoney
Deinitializes Money Management object.
virtual void DeinitMoney()
2304
Standard Library
DeinitIndicators
Deinitializes all indicators and time series.
virtual void DeinitIndicators()
2305
Standard Library
Refresh
Updates all data.
virtual bool Refresh()
Returned value true if tick processing is needed, overwise false. Note It allows to determine the need of tick processing. If it needed, it updates all quotes and time series and indicators data and returns true.
2306
Standard Library
Processing
Main processing algorithm.
virtual bool Processing()
Returned value true if trade operation has been executed, overwise false. Note It does the following steps: 1. Checks the presence of the opened position on the symbol. If there isn't opened position, skip steps 2, 3 and 4. 2. Checks conditions to reverse opened position (calls CheckReverse method). If position has been "reversed", exit. 3. Checks conditions to close position (calls CheckClose method). If position has been closed, skip step 4. 4. Checks conditions to modify position parameters (calls CheckTrailingStop method). If position parameters has been modified, exit. 5. Check the presence of pending orders on the symbol. If there isn't any pending orders, go to step 9. 6. Checks condition to delete order (calls CheckDeleteOrderLong for buy pending orders or CheckDeleteOrderShort for sell pending orders). If the order has been deleted, go to step 9. 7. Check conditions to modify pending order parameters (calls CheckTrailingOrderLong for buy orders or CheckTrailingOrderShort for sell orders). If the order parameters has been modified, exit. 8. Exit. 9. Checks conditions to open position (calls CheckOpen method).
Implementation
//+------------------------------------------------------------------+ //| Main function //| INPUT: no. //| OUTPUT: true-if any trade operation processed, false otherwise. //| REMARK: no. bool CExpert::Processing() { //--- check if open positions if(m_position.Select(m_symbol.Name())) { //--- open position is available //--- check the possibility of closing the position/delete pending orders if(!CheckClose()) { //--- check the possibility of modifying the position if(CheckTrailingStop()) return(true); } | | | |
//+------------------------------------------------------------------+
2307
Standard Library
} //--- check the possibility of opening a position/setting pending order if(CheckOpen()) return(true); //--- check if plased pending orders int total=OrdersTotal(); if(total!=0) { for(int i=total-1;i>=0;i--) { m_order.Select(OrderGetTicket(i)); if(m_order.Symbol()!=m_symbol.Name()) continue; if(m_order.Type()==ORDER_TYPE_BUY_LIMIT || m_order.Type()==ORDER_TYPE_BUY_STOP) { //--- check the ability to delete a pending order to buy if(CheckDeleteOrderLong()) return(true); //--- check the possibility of modifying a pending order to buy if(CheckTrailingOrderLong()) return(true); } else { //--- check the ability to delete a pending order to sell if(CheckDeleteOrderShort()) return(true); //--- check the possibility of modifying a pending order to sell if(CheckTrailingOrderShort()) return(true); } } } //--- return without operations return(false); }
2308
Standard Library
CheckOpen
Checks conditions to open position.
virtual bool CheckOpen()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to open long (CheckOpenLong) and short (CheckOpenShort) positions.
Implementation
//+------------------------------------------------------------------+ //| Check for position open or limit/stop order set //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckOpen() { if(CheckOpenLong()) return(true); if(CheckOpenShort()) return(true); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2309
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to open long position (by calling CheckOpenLong method of Expert Signal object) and opens the long position (by calling OpenLong method) if necessary.
Implementation
//+------------------------------------------------------------------+ //| Check for long position open or limit/stop order set //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckOpenLong() { double price,sl,tp; datetime expiration=TimeCurrent(); //--- check signal for long enter operations if(m_signal.CheckOpenLong(price,sl,tp,expiration)) { if(!m_trade.SetOrderExpiration(expiration)) { m_expiration=expiration; } return(OpenLong(price,sl,tp)); } //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2310
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to open short position (by calling CheckOpenShort method of Expert Signal object) and opens the short position (by calling OpenShort method) if necessary.
Implementation
//+------------------------------------------------------------------+ //| Check for short position open or limit/stop order set //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckOpenShort() { double price,sl,tp; datetime expiration=TimeCurrent(); //--- check signal for short enter operations if(m_signal.CheckOpenShort(price,sl,tp,expiration)) { if(!m_trade.SetOrderExpiration(expiration)) { m_expiration=expiration; } return(OpenShort(price,sl,tp)); } //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2311
Standard Library
OpenLong
Opens the long position.
virtual bool OpenLong( double price, double sl, double tp ) // Price // Stop Loss price // Take Profit price
Parameters price [in] Price. sl [in] Stop Loss price. tp [in] Take Profit price. Returned value true if trade operation has been executed, overwise false. Note It gets trading volume (by calling LotOpenLong method) and opens the long position (by calling Buy method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+ //| Long position open or limit/stop order set //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::OpenLong(double price,double sl,double tp) { //--- get lot for open double lot=LotOpenLong(price,sl); //--- check lot for open if(lot==0.0) return(false); //--return(m_trade.Buy(lot,price,sl,tp)); } | | | |
//+------------------------------------------------------------------+
2312
Standard Library
OpenShort
Opens the short position.
virtual bool OpenShort( double price, double sl, double tp ) // Price // Stop Loss price // Take Profit price
Parameters price [in] Price. sl [in] Stop Loss price. tp [in] Take Profit price. Returned value true if trade operation has been executed, overwise false. Note It gets trading volume (by calling LotOpenShort method) and opens the short position (by calling Sell method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+ //| Short position open or limit/stop order set //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::OpenShort(double price,double sl,double tp) { //--- get lot for open double lot=LotOpenShort(price,sl); //--- check lot for open if(lot==0.0) return(false); //--return(m_trade.Sell(lot,price,sl,tp)); } | | | |
//+------------------------------------------------------------------+
2313
Standard Library
CheckClose
Checks conditions to close position.
virtual bool CheckClose()
Returned value true if trade operation has been executed, overwise false. Note 1. It checks Expert Advisor Stop Out conditions (by calling CheckClose method of money management object). If condition is satisfied, it closes the position and deletes all orders (by calling CloseAll) and exit. 2. It checks conditions to close long or short position (by calling CheckCloseLong or CheckCloseShort methods) and if position is closed, it deletes all orders (by calling DeleteOrders method).
Implementation
//+------------------------------------------------------------------+ //| Check for position close or limit/stop order delete //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckClose() { double lot; //--- position must be selected before call if((lot=m_money.CheckClose(GetPointer(m_position)))!=0.0) return(CloseAll(lot)); //--- check for position type if(m_position.Type()==POSITION_TYPE_BUY) { //--- check the possibility of closing the long position / delete pending orders to buy if(CheckCloseLong()) { DeleteOrders(); return(true); } } else { //--- check the possibility of closing the short position / delete pending orders to sell if(CheckCloseShort()) { DeleteOrders(); return(true); | | | |
//+------------------------------------------------------------------+
2314
Standard Library
} } //--- return without operations return(false); }
2315
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to close long position (by calling CheckCloseLong method of Expert Signal object) and if it satisfied, it closes the opened position (by calling CloseLong method).
Implementation
//+------------------------------------------------------------------+ //| Check for long position close or limit/stop order delete //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckCloseLong() { double price; //--- check for long close operations if(m_signal.CheckCloseLong(price)) return(CloseLong(price)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2316
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to close short position (by calling CheckCloseShort method of Expert Signal object) and if it satisfied, it closes the position (by calling CloseShort method).
Implementation
//+------------------------------------------------------------------+ //| Check for short position close or limit/stop order delete //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckCloseShort() { double price; //--- check for short close operations if(m_signal.CheckCloseShort(price)) return(CloseShort(price)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2317
Standard Library
CloseAll
It performs partial of full position closing.
virtual bool CloseAll( double lot ) // Lots to close
Parameters lot [in] Number of lots to reduce the position. Returned value true if trade operation has been executed, overwise false. Note It performs partial of full position closing (by calling the Sell and Buy methods of CTrade class object for the long/short positions) and deletes all orders (by calling the DeleteOrders method).
Implementation
//+------------------------------------------------------------------+ //| Position close and orders delete //| INPUT: lot. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CloseAll(double lot) { bool result; //--- check for close operations if(m_position.Type()==POSITION_TYPE_BUY) result=m_trade.Sell(lot,0,0,0); else result|=DeleteOrders(); //--return(result); } result=m_trade.Buy(lot,0,0,0); | | | |
//+------------------------------------------------------------------+
2318
Standard Library
Close
Closes the opened position.
virtual bool Close()
Returned value true if trade operation has been executed, overwise false. Note Closes the position (by calling PositionClose method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Position close //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::Close() { return(m_trade.PositionClose(m_symbol.Name())); } | | | |
//+------------------------------------------------------------------+
2319
Standard Library
CloseLong
Closes the long position.
virtual bool CloseLong( double price ) // price
Parameters price [in] Closing price. Returned value true if trade operation has been executed, overwise false. Note Closes the long position (by calling Sell method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Long position close //| INPUT: price. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CloseLong(double price) { return(m_trade.Sell(m_position.Volume(),price,0,0)); } | | | |
//+------------------------------------------------------------------+
2320
Standard Library
CloseShort
Closes the short position.
virtual bool CloseShort( double price ) // price
Parameters price [in] Closing price. Returned value true if trade operation has been executed, overwise false. Note Closes the short position (by calling Buy method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Short position close //| INPUT: price. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::CloseShort(double price) { return(m_trade.Buy(m_position.Volume(),price,0,0)); } | | | |
//+------------------------------------------------------------------+
2321
Standard Library
CheckReverse
Checks conditions to reverse opened position.
virtual bool CheckReverse()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to reverse long (CheckReverseLong) and short (CheckReverseShort) positions.
Implementation
//+------------------------------------------------------------------+ //| Check for position reverse //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckReverse() { if(m_position.Type()==POSITION_TYPE_BUY) { //--- check the possibility of reverse the long position if(CheckReverseLong()) } else //--- check the possibility of reverse the short position if(CheckReverseShort()) return(true); //--- return without operations return(false); } return(true); | | | |
//+------------------------------------------------------------------+
2322
Standard Library
CheckReverseLong
Checks conditions to reverse long position.
virtual bool CheckReverseLong()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to reverse long position (by calling CheckReverseLong method of Expert Signal object) and perform reverse operation of the current long position (by calling ReverseLong method) if necessary.
Implementation
//+------------------------------------------------------------------+ //| Check for long position reverse //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckReverseLong() { double price,sl,tp; datetime expiration=TimeCurrent(); //--- check signal for long reverse operations if(m_signal.CheckReverseLong(price,sl,tp,expiration)) return(ReverseLong(price,sl,tp)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2323
Standard Library
CheckReverseShort
Checks conditions to reverse short position.
virtual bool CheckReverseShort()
Returned value true if trade operation has been executed, overwise false. Note It checks conditions to reverse short position (by calling CheckReverseShort method of Expert Signal object) and perform reverse operation of the current short position (by calling ReverseShort method) if necessary.
Implementation
//+------------------------------------------------------------------+ //| Check for short position reverse //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckReverseShort() { double price,sl,tp; datetime expiration=TimeCurrent(); //--- check signal for short reverse operations if(m_signal.CheckReverseShort(price,sl,tp,expiration)) return(ReverseShort(price,sl,tp)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2324
Standard Library
ReverseLong
Perform reverse operation of long position.
virtual bool ReverseLong( double price, double sl, double tp ) // Price // Stop Loss // Take Profit
Parameters price [in] Price of long position reverse. sl [in] Stop Loss price. tp [in] Take Profit price. Returned value true if trade operation has been executed, overwise false. Note It gets position reverse volume (by calling LotReverse method) and perform trade operation of long position reverse (by calling Sell method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+ //| Long position reverse //| INPUT: //| //| price - price, sl tp - stop loss, - take profit. | | | | | |
//| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::ReverseLong(double price,double sl,double tp) { //--- get lot for reverse double lot=LotReverse(sl); //--- check lot if(lot==0.0) return(false); //--return(m_trade.Sell(lot,price,sl,tp)); }
//+------------------------------------------------------------------+
2325
Standard Library
ReverseShort
Perform reverse operation of short position.
virtual bool ReverseShort( double price, double sl, double tp ) // Price // Stop Loss // Take Profit
Parameters price [in] Price of short position reverse. sl [in] Stop Loss price. tp [in] Take Profit price. Returned value true if trade operation has been executed, overwise false. Note It gets position reverse volume (by calling LotReverse method) and perform trade operation of short position reverse (by calling Buy method of Trade object) if trading volume is not equal to 0.
Implementation
//+------------------------------------------------------------------+ //| Short position reverse //| INPUT: //| //| price - price, sl tp - stop loss, - take profit. | | | | | |
//| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::ReverseShort(double price,double sl,double tp) { //--- get lot for reverse double lot=LotReverse(sl); //--- check lot if(lot==0.0) return(false); //--return(m_trade.Buy(lot,price,sl,tp)); }
//+------------------------------------------------------------------+
2326
Standard Library
CheckTrailingStop
It checks Trailing Stop conditions of the opened position.
virtual bool CheckTrailingStop()
Returned value true if trade operation has been executed, overwise false. Note It checks Trailing Stop conditions of the opened position (by calling CheckTrailingStopLong or CheckTrailingStopShort for long and short positions).
Implementation
//+------------------------------------------------------------------+ //| Check for trailing stop/profit position //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckTrailingStop() { //--- position must be selected before call if(m_position.Type()==POSITION_TYPE_BUY) { //--- check the possibility of modifying the long position if(CheckTrailingStopLong()) return(true); } else { //--- check the possibility of modifying the short position if(CheckTrailingStopShort()) return(true); } //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2327
Standard Library
CheckTrailingStopLong
It checks Trailing Stop conditions of the opened long position.
virtual bool CheckTrailingStopLong()
Returned value true if trade operation has been executed, overwise false. Note It checks Trailing Stop conditions of the opened long position (by calling CheckTrailingStopLong method of Expert Trailing object). If conditions are satisfied, it modifies the position parameters (by calling TrailingStopLong method).
Implementation
//+------------------------------------------------------------------+ //| Check for trailing stop/profit long position //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckTrailingStopLong() { double sl=EMPTY_VALUE; double tp=EMPTY_VALUE; //--- check for long trailing stop operations if(m_trailing.CheckTrailingStopLong(GetPointer(m_position),sl,tp)) { if(sl==EMPTY_VALUE) sl=m_position.StopLoss(); if(tp==EMPTY_VALUE) tp=m_position.TakeProfit(); //--- long trailing stop operations return(TrailingStopLong(sl,tp)); } //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2328
Standard Library
CheckTrailingStopShort
It checks Trailing Stop conditions of the opened short position.
virtual bool CheckTrailingStopShort()
Returned value true if trade operation has been executed, overwise false. Note It checks Trailing Stop conditions of the opened short position (by calling CheckTrailingStopShort method of Expert Trailing object). If conditions are satisfied, it modifies the position parameters (by calling TrailingStopShort method).
Implementation
//+------------------------------------------------------------------+ //| Check for trailing stop/profit short position //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckTrailingStopShort() { double sl=EMPTY_VALUE; double tp=EMPTY_VALUE; //--- check for short trailing stop operations if(m_trailing.CheckTrailingStopShort(GetPointer(m_position),sl,tp)) { if(sl==EMPTY_VALUE) sl=m_position.StopLoss(); if(tp==EMPTY_VALUE) tp=m_position.TakeProfit(); //--- short trailing stop operations return(TrailingStopShort(sl,tp)); } //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2329
Standard Library
TrailingStopLong
The function modifies parameters of the opened long position.
virtual bool TrailingStopLong( double sl, double tp ) // Stop Loss price // Take Profit price
Parameters sl [in] New Stop Loss price. tp [in] New Take Profit price. Returned value true if trade operation has been executed, overwise false. Note The function modifies parameters of the opened long position (by calling PositionModify method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Trailing stop/profit long position //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::TrailingStopLong(double sl,double tp) { return(m_trade.PositionModify(m_symbol.Name(),sl,tp)); } | | | |
//+------------------------------------------------------------------+
2330
Standard Library
TrailingStopShort
The function modifies parameters of the opened short position.
virtual bool TrailingStopShort( double sl, double tp ) // Stop Loss price // Take Profit price
Parameters sl [in] New Stop Loss price. tp [in] New Take Profit price. Returned value true if trade operation has been executed, overwise false. Note The function modifies parameters of the opened short position (by calling PositionModify method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Trailing stop/profit short position //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::TrailingStopShort(double sl,double tp) { return(m_trade.PositionModify(m_symbol.Name(),sl,tp)); } | | | |
//+------------------------------------------------------------------+
2331
Standard Library
CheckTrailingOrderLong
It checks Trailing Stop conditions of buy limit/stop pending order.
virtual bool CheckTrailingOrderLong()
Returned value true if trade operation has been executed, overwise false. Note It checks Trailing Stop conditions for buy limit/stop pending order (by calling CheckTrailingOrderLong method of Trade Signals object) and modifies the order parameters if necessary (by calling TrailingOrderLong method).
Implementation
//+------------------------------------------------------------------+ //| Check for trailing long limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckTrailingOrderLong() { double price; //--- check the possibility of modifying the long order if(m_signal.CheckTrailingOrderLong(GetPointer(m_order),price)) return(TrailingOrderLong(price)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2332
Standard Library
CheckTrailingOrderShort
It checks Trailing Stop conditions of sell limit/stop pending order.
virtual bool CheckTrailingOrderShort()
Returned value true if trade operation has been executed, overwise false. Note It checks Trailing Stop conditions for sell limit/stop pending order (by calling CheckTrailingOrderShort method of Trade Signals object) and modifies the order parameters if necessary (by calling TrailingOrderShort method).
Implementation
//+------------------------------------------------------------------+ //| Check for trailing short limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckTrailingOrderShort() { double price; //--- check the possibility of modifying the short order if(m_signal.CheckTrailingOrderShort(GetPointer(m_order),price)) return(TrailingOrderShort(price)); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2333
Standard Library
TrailingOrderLong
The function modifies parameters of buy limit/stop pending order.
virtual bool TrailingOrderLong( double delta ) // delta
Parameters delta [in] Price delta. Returned value true if trade operation has been executed, overwise false. Note It modifies parameters of buy limit/stop order (by calling OrderModify method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Trailing long limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::TrailingOrderLong(double delta) { ulong ticket=m_order.Ticket(); =m_order.StopLoss()-delta; =m_order.TakeProfit()-delta; double price =m_order.PriceOpen()-delta; double sl double tp | | | |
//+------------------------------------------------------------------+
2334
Standard Library
TrailingOrderShort
The function modifies parameters of sell limit/stop pending order.
virtual bool TrailingOrderShort( double delta ) // delta
Parameters delta [in] Price delta. Returned value true if trade operation has been executed, overwise false. Note It modifies parameters of sell limit/stop order (by calling OrderModify method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Trailing short limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::TrailingOrderShort(double delta) { ulong ticket=m_order.Ticket(); =m_order.StopLoss()-delta; =m_order.TakeProfit()-delta; double price =m_order.PriceOpen()-delta; double sl double tp | | | |
//+------------------------------------------------------------------+
2335
Standard Library
CheckDeleteOrderLong
It checks conditions to delete the buy limit/stop pending order.
virtual bool CheckDeleteOrderLong()
Returned value true if trade operation has been executed, overwise false. Note The steps are: Step 1. It checks the order expiration time. Step 2. It checks conditions to delete the buy limit/stop pending order (by calling CheckCloseLong method of Expert Signal class object) and deletes the order if condition is satisfied (by calling DeleteOrderLong method).
Implementation
//+------------------------------------------------------------------+ //| Check for delete long limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckDeleteOrderLong() { double price; //--- check the possibility of deleting the long order if(m_expiration!=0 && TimeCurrent()>m_expiration) { m_expiration=0; return(DeleteOrderLong()); } if(m_signal.CheckCloseLong(price)) return(DeleteOrderLong()); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2336
Standard Library
CheckDeleteOrderShort
It checks conditions to delete the sell limit/stop pending order.
virtual bool CheckDeleteOrderShort()
Returned value true if trade operation has been executed, overwise false. Note The steps are: Step 1. It checks the order expiration time. Step 2. It checks conditions to delete the sell limit/stop pending order (by calling CheckCloseShort method of Expert Signal class object) and deletes the order if condition is satisfied (by calling DeleteOrderShort method).
Implementation
//+------------------------------------------------------------------+ //| Check for delete short limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation processed, false otherwise. //| REMARK: no. bool CExpert::CheckDeleteOrderShort() { double price; //--- check the possibility of deleting the short order if(m_expiration!=0 && TimeCurrent()>m_expiration) { m_expiration=0; return(DeleteOrderShort()); } if(m_signal.CheckCloseShort(price)) return(DeleteOrderShort()); //--- return without operations return(false); } | | | |
//+------------------------------------------------------------------+
2337
Standard Library
DeleteOrders
Deletes all orders.
virtual bool DeleteOrders()
Returned value true if trade operation has been executed, overwise false. Note It deletes all orders (by calling DeleteOrder method in the loop).
Implementation
//+------------------------------------------------------------------+ //| Delete all limit/stop orders //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::DeleteOrders() { bool result=false; int //--for(int i=total-1;i>=0;i--) { if(m_order.Select(OrderGetTicket(i))) { if(m_order.Symbol()!=m_symbol.Name()) continue; result|=DeleteOrder(); } } //--return(result); } total=OrdersTotal(); | | | |
//+------------------------------------------------------------------+
2338
Standard Library
DeleteOrder
Deletes the limit/stop pending order.
virtual bool DeleteOrder()
Returned value true if trade operation has been executed, overwise false. Note It deletes the limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Delete limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::DeleteOrder() { return(m_trade.OrderDelete(m_order.Ticket())); } | | | |
//+------------------------------------------------------------------+
2339
Standard Library
DeleteOrderLong
Deletes the buy limit/stop pending order.
virtual bool DeleteOrderLong()
Returned value true if trade operation has been executed, overwise false. Note It deletes the buy limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Delete long limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::DeleteOrderLong() { return(m_trade.OrderDelete(m_order.Ticket())); } | | | |
//+------------------------------------------------------------------+
2340
Standard Library
DeleteOrderShort
Deletes the sell limit/stop pending order.
virtual bool DeleteOrderShort()
Returned value true if trade operation has been executed, overwise false. Note It deletes the sell limit/stop pending order (by calling OrderDelete method of CTrade class object).
Implementation
//+------------------------------------------------------------------+ //| Delete short limit/stop order //| INPUT: no. //| OUTPUT: true-if trade operation successful, false otherwise. //| REMARK: no. bool CExpert::DeleteOrderShort() { return(m_trade.OrderDelete(m_order.Ticket())); } | | | |
//+------------------------------------------------------------------+
2341
Standard Library
LotOpenLong
Gets trade volume for buy operation.
double LotOpenLong( double price, // Price double sl ) // Stop Loss
Parameters sl [in] Stop Loss price. tp [in] Take Profit price. Returned value Trade volume (in lots) for buy operation. Note It gets trade volume for buy operation (by calling CheckOpenLong method of money management object).
Implementation
//+------------------------------------------------------------------+ //| Method of getting the lot for open long position. //| INPUT: no. //| OUTPUT: lot for open. //| REMARK: no. double CExpert::LotOpenLong(double price,double sl) { double lot=m_money.CheckOpenLong(price,sl); //--return(lot); } | | | |
//+------------------------------------------------------------------+
2342
Standard Library
LotOpenShort
Gets trade volume for sell operation.
double LotOpenShort( double price, // Price double sl ) // Stop Loss
Parameters sl [in] Stop Loss price. tp [in] Take Profit price. Returned value Trade volume (in lots) for sell operation. Note It gets trade volume for sell operation (by calling CheckOpenLong method of money management object).
Implementation
//+------------------------------------------------------------------+ //| Method of getting the lot for open short position. //| INPUT: no. //| OUTPUT: lot for open. //| REMARK: no. double CExpert::LotOpenShort(double price,double sl) { double lot=m_money.CheckOpenShort(price,sl); //--return(lot); } | | | |
//+------------------------------------------------------------------+
2343
Standard Library
LotReverse
Gets trade volume for position reverse.
double LotReverse( double sl ) // Stop Loss
Parameters sl [in] Stop Loss price. Returned value Trade volume (in lots) for position reverse operation. Note It gets trade volume for position reverse operation (by calling CheckReverse method of money management object).
Implementation
//+------------------------------------------------------------------+ //| Method of getting the lot for reverse position. //| INPUT: sl - stop loss. //| OUTPUT: lot for open. //| REMARK: no. double CExpert::LotReverse(double sl) { return(m_money.CheckReverse(GetPointer(m_position),sl)); } | | | |
//+------------------------------------------------------------------+
2344
Standard Library
PrepareHistoryDate
Sets starting date for the trade history.
void PrepareHistoryDate()
Note The trade history tracking period is set from the beginning of the month (but not less than one day).
2345
Standard Library
HistoryPoint
Creates checkpoint of trade history (saves number of positions, orders, deals and historical orders).
void HistoryPoint( bool from_check_trade==false ) // flag
Parameters from_check_trade==false [in] flag to avoid the recursion. Note It saves the number of positions, orders, deals and historical orders.
2346
Standard Library
CheckTradeState
Compares the current state with the saved one and calls the corresponding event handler.
bool CheckTradeState()
Returned value true if event has been handled, overwise - false. Note It checks the number of positions, orders, deals and historical orders by comparing with the values, saved by HistoryPoint method. If trade history has changed, it calls the corresponding virtual event handler.
2347
Standard Library
WaitEvent
Sets event waiting flag.
void WaitEvent( ENUM_TRADE_EVENTS event ) // Flag
2348
Standard Library
NoWaitEvent
Resets event waiting flag.
void NoWaitEvent( ENUM_TRADE_EVENTS event ) // Flag
2349
Standard Library
IsWaitingPositionOpened
Returns true if Expert Advisor should handle the "Position Opened" event, overwise false.
bool IsWaitingPositionOpened() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventPositionOpened() method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2350
Standard Library
IsWaitingPositionVolumeChanged
Returns true if Expert Advisor should handle the "Position volume changed" event, overwise false.
bool IsWaitingPositionVolumeChanged() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventPositionVolumeChanged method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2351
Standard Library
IsWaitingPositionModified
Returns true if Expert Advisor should handle the "Position modified" event, overwise false.
bool IsWaitingPositionModified() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventPositionModified method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2352
Standard Library
IsWaitingPositionClosed
Returns true if Expert Advisor should handle the "Position closed" event, overwise false.
bool IsWaitingPositionClosed() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventPositionClosed method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2353
Standard Library
IsWaitingPositionStopTake
Returns true if Expert Advisor should handle the "Position Stop Loss/Take Profit triggered" event, overwise false.
bool IsWaitingPositionStopTake() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventPositionStopTake method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2354
Standard Library
IsWaitingOrderPlaced
Returns true if Expert Advisor should handle the "Pending order placed" event, overwise false.
bool IsWaitingOrderPlaced() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventOrderPlaced method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2355
Standard Library
IsWaitingOrderModified
Returns true if Expert Advisor should handle the "Pending order modified" event, overwise false.
bool IsWaitingOrderModified() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventOrderModified method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2356
Standard Library
TradeEventOrderDeleted
Returns true if Expert Advisor should handle the "Pending order deleted" event, overwise false.
bool IsWaitingOrderDeleted() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventOrderDeleted method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2357
Standard Library
IsWaitingOrderTriggered
Returns true if Expert Advisor should handle the "Pending order triggered" event, overwise false.
bool IsWaitingOrderTriggered() const
Returned value true if corresponding flag is set and event should handled, overwise false. The event is processed by TradeEventOrderTriggered method. Note The event tracking flag can be set/reset using WaitEvent() and NoWaitEvent() methods.
2358
Standard Library
TradeEventPositionStopTake
"Position Stop Loss/Take Profit triggered" event handler.
virtual bool TradeEventPositionStopTake()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2359
Standard Library
TradeEventOrderTriggered
"Pending order triggered" event handler.
virtual bool TradeEventOrderTriggered()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2360
Standard Library
TradeEventPositionOpened
"Position opened" event handler.
virtual bool TradeEventPositionOpened()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2361
Standard Library
TradeEventPositionVolumeChanged
"Position volume changed" event handler.
virtual bool TradeEventPositionVolumeChanged()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2362
Standard Library
TradeEventPositionModified
"Position modified" event handler.
virtual bool TradeEventPositionModified()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2363
Standard Library
TradeEventPositionClosed
"Position closed" event handler.
virtual bool TradeEventPositionClosed()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2364
Standard Library
TradeEventOrderPlaced
"Pending order placed" event handler.
virtual bool TradeEventOrderPlaced()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2365
Standard Library
TradeEventOrderModified
"Pending order modified" event handler.
virtual bool TradeEventOrderModified()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2366
Standard Library
TradeEventOrderDeleted
"Pending order deleted" event handler.
virtual bool TradeEventOrderDeleted()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2367
Standard Library
TradeEventNotIdentified
Event handler of the non-identified event.
virtual bool TradeEventNotIdentified()
Returned value true if event has been processed, overwise false. Note The virtual method of CExpert class does nothing and always returns true.
2368
Standard Library
TimeframeAdd
Add a timeframe for tracking.
void TimeframeAdd( ENUM_TIMEFRAMES period ) // Timeframe
2369
Standard Library
TimeframesFlags
The function returns the flag indicating the timeframes with a new bar.
int TimeframesFlags( MqlDateTime& time ) // Variable for time
Parameters time [in] Variable of MqlDateTime type for new time, passed by reference. Returned value It returns the flag, that indicates timeframes with a new bar.
2370
Standard Library
CExpertSignal
CExpertSignal is a base class for trading signals, it does nothing (except CheckReverseLong and CheckReverseShort methods) but provides the interfaces. How to use it: 1. Prepare an algorithm for trading signals; 2. Create your own trading signal class, inherited from CExpertSignal class; 3. Override the virtual methods in your class with your own algorithms. You can find an examples of trading signal classes in the Expert\Signal\ folder.
Description
CExpertSignal is a base class for implementation of trading signal algorithms.
Declaration
class CExpertSignal : public CObject
Title
#include <Expert\ExpertSignal.mqh>
Class Methods
Initialization virtual Init virtual InitIndicators virtual ValidationSettings Check Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort virtual CheckReverseLong virtual CheckReverseShort Check Trailing Stop Conditions virtual CheckTrailingOrderLong virtual CheckTrailingOrderShort Checks conditions to modify buy pending order Checks conditions to modify sell pending order Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Checks conditions of long position reversal Checks conditions of short position reversal Initializes class members Initializes indicators and time series Checks the settings
2371
Standard Library
Init
Initializes class members.
virtual bool Init( CSymbolInfo* symbol, // CSymbolInfo object pointer // Timeframe // Point size ENUM_TIMEFRAMES period, double ) adjusted_point
Parameters symbol [in] Pointer to CSymbolInfo object (CExpert class member). period [in] Timeframe (ENUM_TIMEFRAMES enumeration). adjusted_point [in] Point size. Returned value true if successful, overwise false.
2372
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false. Note The InitIndicators() method of the base class always returns true.
2373
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The ValidationSettings() method of the base class always returns true.
2374
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckOpenLong() method of the base class always returns false.
2375
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckCloseLong() method of the base class always returns false.
2376
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for opening price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "ake Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckOpenShort() method of the base class always returns false.
2377
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Closing price
Parameters price [in][out] Variable for position closing price, passed by reference. Returned value true if condition is satisfied, overwise false. Note The CheckCloseShort() method of the base class always returns false.
2378
Standard Library
CheckReverseLong
Checks conditions of long position reversal.
virtual bool CheckReverseLong( double& double& double& price, sl, tp, // Reversal price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for reversal price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "ake Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckReverseLong() method of the base class returns true if both CheckCloseLong and CheckOpenShort conditions are satisfied and closing and opening prices are equal.
2379
Standard Library
CheckReverseShort
Checks conditions of short position reversal.
virtual bool CheckReverseShort( double& double& double& price, sl, tp, // Reversal price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for reversal price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "ake Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckReverseShort() method of the base class returns true if both CheckCloseShort and CheckOpenLong conditions are satisfied and closing and opening prices are equal.
2380
Standard Library
CheckTrailingOrderLong
Checks conditions to modify buy pending order.
virtual bool CheckTrailingOrderLong( COrderInfo* order, double& ) price // COrderInfo object pointer // New order price
Parameters order [in] Pointer to COrderInfo object. price [in][out] Variable for new order price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckTrailingOrderLong() method of the base class always returns false.
2381
Standard Library
CheckTrailingOrderShort
Checks conditions to modify sell pending order.
virtual bool CheckTrailingOrderShort( COrderInfo* order, double& ) price // COrderInfo object pointer // New order price
Parameters order [in] Pointer to COrderInfo object. price [in][out] Variable for new order price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckTrailingOrderShort() method of the base class always returns false.
2382
Standard Library
CExpertTrailing
CExpertTrailing is a base class for trailing algorithms, it does nothing but provides the interfaces. How to use it: 1. Prepare an algorithm for trailing; 2. Create your own trailing class, inherited from CExpertTrailing class; 3. Override the virtual methods in your class with your own algorithms. You can find an examples of trailing classes in the Expert\Trailing\ folder.
Description
CExpertTrailing is a base class for implementation of trailing algoritms.
Declaration
class CExpertTrailing : public CObject
Title
#include <Expert\ExpertTrailing.mqh>
Class Methods
Initialization virtual Init virtual InitIndicators virtual ValidationSettings Checking Trailing Stop virtual CheckTrailingStopLong virtual CheckTrailingStopShort Checks conditions to modify long position Checks conditions to modify short position Initializes class members Initializes indicators and time series Checks the settings
2383
Standard Library
Init
Initializes class members.
virtual bool Init( CSymbolInfo* symbol, // CSymbolInfo object pointer // Timeframe // Point size ENUM_TIMEFRAMES period, double ) adjusted_point
Parameters symbol [in] Pointer to CSymbolInfo object (CExpert class member). period [in] Timeframe. adjusted_point [in] Point size. Returned value true if successful, overwise false.
2384
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] A pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false. Note The InitIndicators() method of the base class always returns true.
2385
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The ValidationSettings() method of the base class always returns true.
2386
Standard Library
CheckTrailingStopLong
Checks conditions to modify long position.
virtual bool CheckTrailingStopLong( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price, passed by reference. tp [in][out] Variable for Take Profit price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckTrailingStopLong() method of the base class always returns false.
2387
Standard Library
CheckTrailingStopShort
Checks conditions to modify short position.
virtual bool CheckTrailingStopShort( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price, passed by reference. tp [in][out] Variable for Take Profit price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The CheckTrailingStopShort() method of the base class always returns false.
2388
Standard Library
CExpertMoney
CExpertMoney is a base class for money and risk management algorithms.
Description
CExpertMoney is a base class for implementation of money and risk management classes.
Declaration
class CExpertMoney : public CObject
Title
#include <Expert\ExpertMoney.mqh>
Class Methods
Access to Protected Data Percent Initialization virtual Init virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckOpenShort virtual CheckReverse virtual CheckClose Gets the volume for long position Gets the volume for short position Gets the volume for reverse of the position Checks conditions to close opened position Initializes class members Initializes indicators and time series Checks the settings Sets the value of "Risk percent" parameter
2389
Standard Library
Percent
Sets the value of "Risk percent" parameter.
void Percent( double perent ) // Risk percent
2390
Standard Library
Init
Initializes class members.
virtual bool Init( CSymbolInfo* symbol, // CSymbolInfo object pointer // Timeframe // Point size ENUM_TIMEFRAMES period, double ) adjusted_point
Parameters symbol [in] Pointer to CSymbolInfo object (CExpert class member). period [in] Timeframe (ENUM_TIMEFRAMES enumeration). adjusted_point [in] Point size. Returned value true if successful, overwise false.
2391
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false. Note The InitIndicators() method of the base class always returns true.
2392
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The ValidationSettings() method of the base class always returns true.
2393
Standard Library
CheckOpenLong
Gets the volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Opening price of long position. sl [in] Stop Loss price of long position. Returned value Trade volume for long position.
2394
Standard Library
CheckOpenShort
Gets the volume for short position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Opening price of short position. sl [in] Stop Loss price of short position. Returned value Trade volume for short position.
2395
Standard Library
CheckReverse
Gets the volume for reverse of the position.
virtual double CheckReverse( CPositionInfo* position, double ) sl // CPositionInfo object pointer // Stop Loss price
Parameters position [in] Pointer to CPositionInfo object. sl [in] Stop Loss price. Returned value Volume for reverse of the position.
2396
Standard Library
CheckClose
Checks conditions to close position.
virtual double CheckClose()
2397
Standard Library
CSignalADX_MA
CSignalAlligator
CSignalCandles
CSignalCandlesRSI
CSignalCandlesStoch
CSignalCrossEMA
CSignalCrossMA
CSignalMA
CSignalMACD
CSignalMovingAverage
CSignalITF
CSignal2EMA_ITF
2398
Standard Library
2399
Standard Library
CSignal3EMA
CSignal3EMA is a class with implementation of trading strategy, based on three exponentially smoothed moving averages.
Description
CSignal3EMA class implements trading signals based on the strategy that uses three exponentially smoothed moving averages.
Declaration
class CSignal3EMA : public CExpertSignal
Title
#include <Expert\Signal\Signal3EMA.mqh>
Class Methods
Initialization FastPeriod MediumPeriod SlowPeriod StopLoss TakeProfit virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of fast EMA Sets period of medium EMA Sets period of slow EMA Sets the value of Stop Loss level Sets the value of Take Profit level Initializes indicators and time series Checks the settings
2400
Standard Library
FastPeriod
Sets smoothing period of fast EMA.
void FastPeriod( int period ) // Smoothing period
2401
Standard Library
MediumPeriod
Sets smoothing period of medium EMA.
void MediumPeriod( int period ) // Smoothing period
2402
Standard Library
SlowPeriod
Sets smoothing period of slow EMA.
void SlowPeriod( int period ) // Smoothing period
2403
Standard Library
StopLoss
Sets Stop Loss level (in points).
void StopLoss( int stop_loss ) // Stop Loss level
Parameters stop_loss [in] New value of Stop Loss level (in conventional 2/4-digit points).
2404
Standard Library
TakeProfit
Sets the value of Take Profit level (in points).
void TakeProfit( int take_profit ) // Take Profit level
Parameters take_profit [in] New value of Take Profit level (in conventional 2/4-digit points).
2405
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2406
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note It returns false if period of fast EMA lower then period of medium EMA or period of medium EMA is lower than period of slow EMA. In all other cases it returns true.
2407
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied for the previous bar: Fast EMA > Middle EMA, Slow EMA < Middle EMA. The output variables are set to: price = 0.0; sl = Current Price-Stop Loss level; tp = Current Price+Take Profit level. In other words, if Fast EMA>Middle EMA>Slow EMA at the previous bar, it suggests to open long position on the current price with calculated values of sl and tp.
2408
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied for the previous bar: Fast EMA < Middle EMA, Slow EMA > Middle EMA. The price variable is set to 0.0. In other words, if Fast EMA<Middle EMA<Slow EMA at the previous bar, it suggests to close long position on the current price.
2409
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied for the previous bar: Fast EMA < Middle EMA, Slow EMA > Middle EMA. The output variables are set to: price = 0.0; sl = Current Price+Stop Loss level; tp = Current Price-Take Profit level. In other words, if Fast EMA<Middle EMA<Slow EMA at the previous bar, it suggests to open short position on the current price with calculated values of sl and tp.
2410
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied for the previous bar: Fast EMA > Middle EMA, Slow EMA < Middle EMA. The price variable is set to 0.0. In other words, if Fast EMA>Middle EMA>Slow EMA at the previous bar, it suggests to close short position on the current price.
2411
Standard Library
CSignalADX_MA
CSignalADX_MA is a class with implementation of trading strategy, based on price crossover with exponentially smoothed moving average, confirmed by ADX indicator.
Description
This class implements trading signals, based on price crossover with exponentially smoothed moving average, confirmed by ADX indicator.
Declaration
class CSignalADX_MA : public CExpertSignal
Title
#include <Expert\Signal\SignalADX-MA.mqh>
Class Methods
Initialization PeriodADX MinimumADX PeriodMA StopLoss Sets period of ADX indicator Sets the minimal value of ADX for the analysis Sets period of EMA indicator Sets the value of Stop Loss level (in points) from the opening price Sets the value of Take Profit level (in points) from the opening price Initializes indicators and time series
TakeProfit
virtual InitIndicators Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort
Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position
2412
Standard Library
PeriodADX
Sets period of ADX indicator.
void PeriodADX( int period ) // Period
2413
Standard Library
MinimumADX
Sets the minimal value of ADX for the analysis.
void MinimumADX( double minimum ) // Mininal ADX value
2414
Standard Library
PeriodMA
Sets period of EMA indicator.
void PeriodMA( int period ) // Period
2415
Standard Library
TakeProfit
Sets the value of Take Profit level (in points).
void TakeProfit( int take_profit ) // Take Profit level
Parameters take_profit [in] New value of Take Profit level (in conventional 2/4-digit points).
2416
Standard Library
StopLoss
Sets the value of Stop Loss level (in points).
void StopLoss( int stop_loss ) // Stop Loss level
Parameters stop_loss [in] New value of Stop Loss level (in conventional 2/4-digit points).
2417
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2418
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. EMA rises at least two previous bars (its values increase). 2. Closing price of the previous bar is greater than EMA. 3. Base line of ADX indicator is greater than MinimumADX (minimal value for the analysis). 4. The value of "+ADX" line is greater than value of "-ADX" line. If all conditions are satisfied at the previous bar, it suggests to open long position on the current price with calculated values of sl and tp. The output variables are set to: price = 0.0; sl = Current Price-Stop Loss level; tp = Current Price+Take Profit level.
2419
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. EMA falls at least two previous bars (its values decrease). 2. Closing price of the previous bar is lower than EMA. 3. Base line of ADX indicator is greater than MinimumADX (minimal value for the analysis). 4. The value of "+ADX" line is lower than value of "-ADX" line. If all conditions are satisfied at the previous bar, it suggests to close long position on the current price. The price variable is set to 0.0.
2420
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. EMA falls at least two previous bars (its values decrease). 2. Closing price of the previous bar is lower than EMA. 3. Base line of ADX indicator is greater than MinimumADX (minimal value for the analysis). 3. The value of "+ADX" line is lower than value of "-ADX" line. If all conditions are satisfied at the previous bar, it suggests to open short position on the current price. The output variables are set to: price = 0.0; sl = Current Price+Stop Loss level; tp = Current Price-Take Profit level.
2421
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. EMA rises at least two previous bars (its values increase). 2. Closing price of the previous bar is greater than EMA. 3. Base line of ADX indicator is greater than MinimumADX (minimal value for the analysis). 4. The value of "+ADX" line is greater than value of "-ADX" line. If all conditions are satisfied at the previous bar, it suggests to close short position on the current price. The price variable is set to 0.0.
2422
Standard Library
CSignalAlligator
CAlligator is a class for implementation of trading strategy, based on crossover of the Alligator indicator lines.
Description
This class implements trading signals based on the crossover of the Alligator indicator lines.
Declaration
class CSignalAlligator : public CExpertSignal
Title
#include <Expert\Signal\SignalAlligator.mqh>
Class Methods
Initialization JawPeriod JawShift TeethPeriod TeethShift LipsPeriod LipsShift MaMethod Applied CrossMeasure virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of of Jaw line Sets shift of Jaw line Sets period of Teeth line Sets shift of Teeth line Sets period of Lips line Sets shift of Lips line Sets smoothing method Sets applied price Sets the value of lines crossover threshold Initializes indicators and time series Checks the settings
2423
Standard Library
JawPeriod
Sets period of Jaw line.
void JawPeriod( int period ) // Period
2424
Standard Library
JawShift
Sets shift parameter of Jaw line.
void JawShift( int shift ) // Shift
2425
Standard Library
TeethPeriod
Sets period of Teeth line.
void TeethPeriod( int period ) // Period
2426
Standard Library
TeethShift
Sets shift of Teeth line.
void TeethShift( int shift ) // Shift
2427
Standard Library
LipsPeriod
Sets period of Lips line.
void LipsPeriod( int period ) // Period
2428
Standard Library
LipsShift
Sets shift of Lips line.
void LipsShift( int shift ) // Shift
2429
Standard Library
MaMethod
Sets smoothing method.
void MaMethod( ENUM_MA_METHOD method ) // Smoothing method
2430
Standard Library
Applied
Sets applied price.
void Applied( ENUM_APPLIED_PRICE applied ) // Applied price
2431
Standard Library
CrossMeasure
Sets the value of lines crossover threshold.
void CrossMeasure( int measure ) // Threshold
Parameters measure [in] Threshold for measure of lines crossover of Alligator indicator.
2432
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2433
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the value of JawPeriod is lower or equal to TeethPeriod, or TeethPeriod is lower or equal to LipsPeriod parameter. In other cases it returns true.
2434
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note If the price has crossed upward (on the previous bar) all three lines of the Alligator indicator, it suggests to open long position on the current price without setting of Stop Loss and Take Profit. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2435
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the Jaw line has crossed downward (on the previous bar) the Teeth line, it suggests to close long position on the current price.
2436
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note If the price has crossed downward (on the previous bar) all three lines of the Alligator indicator, it suggests to open short position on the current price without setting of Stop Loss and Take Profit. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2437
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the Jaw line has crossed upward (on the previous bar) the Teeth line, it suggests to close short position on the current price.
2438
Standard Library
CSignalCandles
CSignalCandles is a class for implementation of trading strategy, based on reversal candlestick patterns.
Description
This class implements trading signals based on reversal candlestick pattern, it has a simplified algorithm of recognition of "reversal" candlestick patterns. 1. The maximal number of bars in the composite candle is defined by Range method. 2. The minimal size of the composite candle is specified in points. The composite candle is formed when its size is equal of greater than value, defined by Minimum method. 3. The "reversal" candlestick parameters is defined by ShadowBig and ShadowSmall methods (in units of the composite candle size, i.e. size of the composite candle = 1.0). 4. The Limit, TakeProfit and StopLoss levels are specified in composite candle units, relative to open price of the composite candle. 5. The Expiration method is used to specify order expiration time (in bars) if the trade must be opened at price, different from the market price(Limit!=0.0)) The composite candle (O, H, L, C) parameters are calculated as follows: 1. The initial values are: O = Open[1], H = High[1], L = Low[1], C = Close[1]. 2. Calculate O, H and L of the composite candle in a loop (i=2; i<Range) (H-L<Minimum) by formulae: O = Open[i]; H = Max(H, High[i]); L = Min(L, Low[i]); The reversal candlestick patterns are determined as follows. It calculates the composite candle parameters starting from the recent completed bar (with index 1) to the number of bars, defined by Range method. If the composite candle size is greater than value, specified by Minimum method, it checks the reversal conditions of the composite candle by analysis of its shadows. The bears power is characterized by size of the upper shadow of the composite candle, the bulls power is characterized by size of the lower shadow. To confirm the reversal of the bearish trend (and start of the bullish) it is needed the following: the size of the lower shadow (bulls power) must be greater than value, defined by ShadowBig method. The size of the upper shadow (bears power) must be less than value, defined by ShadowSmall method. To confirm the reversal of the bullish trend (and start of the bearish) it is needed the following: the size of the upper shadow (bears power) must be greater than value, defined by ShadowBig method. The size of the lower shadow (bulls power) must be less than value, defined by ShadowSmall method.
Declaration
class CSignalCandles : public CExpertSignal
Title
2439
Standard Library
#include <Expert\Signal\SignalCandles.mqh>
Class Methods
Initialization Range Sets maximal number of bars of the composite candle Sets minimal size (in points) of the composite candle Sets minimal size of big shadow (composite candle units) Sets maximal size of small shadow (composite candle units) Sets the limit price (composite candle units) Sets the value of Take Profit level (composite candle units) Sets the value of Stop Loss price (composite candle units) Sets order expiration period (in bars) Initializes indicators and time series Checks the settings
Minimum
ShadowBig
ShadowSmall
Limit TakeProfit
StopLoss
Expiration virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Candle
Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Checks the type of the resulting candlestick pattern
2440
Standard Library
Range
Sets the range (maximal number of bars) of the composite candle.
void Range( int range ) // Maximal allowed number of bars in the candle
Parameters range [in] The maximal number of bars of the composite candle.
2441
Standard Library
Minimum
Sets the minimal size (in points) of the composite candle.
void Minimum( int minimum ) // Minimal size of the resulted candle
Parameters minimum [in] The minimal size of the composite candle (in conventional 2/4-digit points).
2442
Standard Library
ShadowBig
Sets size of "big shadow".
void ShadowBig( double shadow_big ) // Big shadow size
Parameters shadow_big [in] New value of big shadow (in units of the composite candle size, i.e. composite candle size= 1.0).
2443
Standard Library
ShadowSmall
Sets the size of small shadow.
void ShadowSmall( double shadow_small ) // Small shadow size
Parameters shadow_small [in] New value of small shadow (in units of the composite candle size, i.e. composite candle size= 1.0).
2444
Standard Library
Limit
Sets the limit price.
void Limit( double limit ) // Limit price level
Parameters limit [in] New value of limit price (in units of the composite candle size, i.e. composite candle size= 1.0).
2445
Standard Library
TakeProfit
Sets the value of Take Profit level.
void TakeProfit( double take_profit ) // Take Profit
Parameters take_profit [in] New value of Take Profit level (in units of the composite candle size, i.e. composite candle size = 1.0).
2446
Standard Library
StopLoss
Sets the value of Stop Loss level.
void StopLoss( double stop_loss ) // Stop Loss
Parameters stop_loss [in] New value of Stop Loss level (in units of the composite candle size, i.e. composite candle size = 1.0).
2447
Standard Library
Expiration
Sets the order expiration period.
void Expiration( int expiration ) // Number of bars
2448
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2449
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the range (maximum number of bars in the resulting candle) is less or equal to zero. For all other cases it returns true.
2450
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note It returns true if the bullish reversal pattern has formed on the previous (completed) bar. The output variables are set to: price = Current Price-Limit; sl = Current Price-StopLoss; tp = Current Price+TakeProfit. In other words, if the bullish reversal pattern has formed, It suggests to open long position on the calculated price with setting Stop Loss and Take Profit levels according to the calculated values of sl and tp.
2451
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note It returns true if the bearish reversal pattern has formed on the previous (completed) bar. The price variable is set to 0.0. In other words, if the bearish reversal pattern has formed, it suggests to close long position on the current price.
2452
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note It returns true if the bearish reversal pattern has formed on the previous (completed) bar. The output variables are set to: price = Current Price+Limit; sl = Current Price+StopLoss; tp = Current Price-TakeProfit. In other words, if the bearish reversal pattern has formed, It suggests to open short position on the calculated price with setting Stop Loss and Take Profit levels according to the calculated values of sl and tp.
2453
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note It returns true if the bullish reversal pattern has formed on the previous (completed) bar. The price variable is set to 0.0. In other words, if the bullish reversal pattern has formed, it suggests to close short position on the current price.
2454
Standard Library
Candle
Checks the type of the resulting candlestick pattern (if the bullish or bearish reversal pattern has formed).
int Candle( int ind ) // index of the first candle
Parameters ind [in] Index of the first candle. Returned value The returned value is positive for bullish candle and negative for bearish, the absolute value is equal to the number of candles, formed the resulting candlestick pattern.
2455
Standard Library
CSignalCandlesRSI
CSignalCandlesRSI is a class with implementation of trading strategy based on reversal candlestick pattern, confirmed by RSI indicator.
Description
CSignalCandlesRSI class implements trading signals based on reversal candlestick pattern, confirmed by RSI indicator.
Declaration
class CSignalCandlesRSI : public CSignalCandles
Title
#include <Expert\Signal\SignalCandlesRSI.mqh>
Class Methods
Initialization PeriodRSI AppliedRSI ExtrMapp Sets period of RSI indicator Sets applied price of RSI indicator Sets the "extremum bit map" for advanced analysis of RSI indicator Initializes indicators and time series Checks the settings
virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort
Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position
2456
Standard Library
PeriodRSI
Sets period of RSI indicator.
void PeriodRSI( int period ) // Period
2457
Standard Library
AppliedRSI
Sets applied price of RSI indicator.
void AppliedRSI( ENUM_APPLIED_PRICE applied ) // Price
2458
Standard Library
ExtrMap
Sets "extremum bit map" for advanced analysis of RSI indicator.
void ExtrMap( int map ) // Bit map
2459
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2460
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the candle parameters are invalid or the value or Period parameter of RSI indicator is lower of equal to zero. In all other cases it returns true.
2461
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckOpenLong() method of parent class returned true and this signal has been confirmed by upward reversal of RSI indicator. The values of the price, sl and tp variables are set by CSignalCandles::CheckOpenLong() method. In other words, if the bullish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by upward reversal of RSI indicator, it suggests to open long position on the calculated price with setting of Stop Loss and Take Profit levels.
2462
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckCloseLong() method of parent class returned true and this signal has been confirmed by downward reversal of RSI indicator. The value of price variable is set to 0.0 by CSignalCandles::CheckCloseLong() method. In other words, if the bearish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by downward reversal of RSI indicator, it suggests to close long position on the current price.
2463
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckOpenShort() method of parent class returned true and this signal has been confirmed by downward reversal of RSI indicator. The values of the price, sl and tp variables are set by CSignalCandles::CheckOpenShort() method. In other words, if the bearish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by downward reversal of RSI indicator, it suggests to open short position on the calculated price with setting of Stop Loss and Take Profit levels.
2464
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckCloseShort() method of parent class returned true and this signal has been confirmed by upward reversal of RSI indicator. The value of price variable is set to 0.0 by CSignalCandles::CheckCloseShort() method. In other words, if the bullish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by upward reversal of RSI indicator, it suggests to close short position on the current price.
2465
Standard Library
CSignalCandlesStoch
CSignalCandlesStoch is a class with implementation of trading strategy based on reversal candlestick patterns, confirmed by Stochastic indicator.
Description
CSignalCandlesStoch class implements trading signals based on reversal candlestick patterns, confirmed by Stochastic indicator.
Declaration
class CSignalCandlesStoch : public CSignalCandles
Title
#include <Expert\Signal\SignalCandlesStoch.mqh>
Class Methods
Initialization PeriodK PeriodD PeriodSlow Applied ExtrMapp Sets period %K of Stochastic indicator Sets period %D of Stochastic indicator Sets period of slow line of Stochastic indicator Sets applied price of Stochastic indicator Sets the "extremum bit map" for advanced analysis of Stochastic indicator Initializes indicators and time series Checks the settings
virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort
Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position
2466
Standard Library
PeriodK
Sets period of %K line of Stochastic indicator.
void PeriodK( int period ) // %K line period
2467
Standard Library
PeriodD
Sets period of %D line of Stochastic indicator.
void PeriodD( int period ) // %D line period
2468
Standard Library
PeriodSlow
Sets period of slow line of Stochastic indicator.
void PeriodSlow( int period ) // Period of slow line
2469
Standard Library
Applied
Sets applied price of Stochastic indicator.
void Applied( ENUM_STO_PRICE applied ) // Price
2470
Standard Library
ExtrMap
Sets "extremum bit map" for advanced analysis of Stochastic indicator.
void ExtrMap( int map ) // Bit map
2471
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2472
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if parameters of the composite candle is invalid or period%K or period%D of Stochastic indicator is negative. For all other cases it returns true.
2473
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckOpenLong() method of parent class returned true and this signal has been confirmed by upward reversal of Stochastic indicator. The values of the price, sl and tp variables are set by CSignalCandles::CheckOpenLong() method. In other words, if the bullish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by upward reversal of Stochastic indicator, it suggests to open long position on the calculated price with setting of Stop Loss and Take Profit levels.
2474
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckCloseLong() method of parent class returned true and this signal has been confirmed by downward reversal of Stochastic indicator. The value of price variable is set to 0.0 by CSignalCandles::CheckCloseLong() method. In other words, if the bearish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by downward reversal of Stochastic indicator, it suggests to close long position on the current price.
2475
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckOpenShort() method of parent class returned true and this signal has been confirmed by downward reversal of Stochastic indicator. The values of the price, sl and tp variables are set by CSignalCandles::CheckOpenShort() method. In other words, if the bearish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by downward reversal of Stochastic indicator, it suggests to open short position on the calculated price with setting of Stop Loss and Take Profit levels.
2476
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the CSignalCandles::CheckCloseShort() method of parent class returned true and this signal has been confirmed by upward reversal of Stochastic indicator. The value of price variable is set to 0.0 by CSignalCandles::CheckCloseShort() method. In other words, if the bullish reversal candlestick pattern has formed on the previous (completed) bar and it has been confirmed by upward reversal of Stochastic indicator, it suggests to close short position on the current price.
2477
Standard Library
CSignalCrossEMA
CSignalCrossEMA is a class with implementation of trading strategy, based on crossover of two exponentially smoothed moving averages.
Description
CSignalCrossEMA class implements trading signals, based on crossover of two exponentially smoothed moving averages.
Declaration
class CSignalCrossEMA : public CExpertSignal
Title
#include <Expert\Signal\SignalCrossEMA.mqh>
Class Methods
Initialization FastPeriod SlowPeriod virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of fast smoothed moving average Sets period of slow smoothed moving average Initializes indicators and time series Checks the settings
2478
Standard Library
FastPeriod
Sets period of fast exponentially smoothed moving average.
void FastPeriod( int period ) // Period
2479
Standard Library
SlowPeriod
Sets period of slow exponentially smoothed moving average.
void SlowPeriod( int period ) // Period
2480
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2481
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The functions returns false if the period of fast EMA is lower than period of slow EMA. In all other cases it returns true.
2482
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast EMA has crossed upward (on the previous bar) the slow EMA. The output variables are set to: price = 0.0; sl = 0.0, tp = 0.0. If the fast EMA has crossed upward the slow EMA on the previous (completed bar), it suggests to open long position on the current price without setting Stop Loss and Take Profit orders.
2483
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast EMA has crossed downward (on the previous bar) the slow EMA. The price variable is set to 0.0. If the fast EMA has crossed downward the slow EMA on the previous (completed bar), it suggests to close long position on the current price.
2484
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast EMA has crossed downward (on the previous bar) the slow EMA. The output variables are set to: price = 0.0; sl = 0.0, tp = 0.0. If the fast EMA has crossed downward the slow EMA on the previous (completed bar), it suggests to open short position on the current price without setting Stop Loss and Take Profit orders.
2485
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast EMA has crossed upward (on the previous bar) the slow EMA. The price variable is set to 0.0. If the fast EMA has crossed upward the slow EMA on the previous (completed bar), it suggests to close short position on the current price.
2486
Standard Library
CSignalCrossMA
CSignalCrossMA is a class with implementation of trading strategy based on crossover of two moving averages.
Description
CSignalCrossMA class implements trading signals based on crossover of two moving averages
Declaration
class CSignalCrossMA : public CExpertSignal
Title
#include <Expert\Signal\SignalCrossMA.mqh>
Class Methods
Initialization FastPeriod FastShift FastMethod FastApplied SlowPeriod SlowShift SlowMethod SlowApplied StopLoss TakeProfit virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of fast moving average Sets shift of fast moving average Sets smoothing method of fast moving average Sets applied price of fast moving average Sets period of slow moving average Sets shift of slow moving average Sets smoothing method of slow moving average Sets applied price of slow moving average Sets the value of Stop Loss level Sets the value of Take Profit level Initializes indicators and time series Checks the settings
2487
Standard Library
FastPeriod
Sets period of fast moving average.
void FastPeriod( int period ) // Period
2488
Standard Library
FastShift
Sets shift of fast moving average.
void FastShift( int shift ) // Shift
2489
Standard Library
FastMethod
Sets smoothing method of fast moving average.
void FastMethod( ENUM_MA_METHOD method ) // Smoothing method
2490
Standard Library
FastApplied
Sets applied price of fast moving average.
void FastApplied( ENUM_APPLIED_PRICE applied ) // Applied price
2491
Standard Library
SlowPeriod
Sets period of slow moving average.
void SlowPeriod( int period ) // Period
2492
Standard Library
SlowShift
Sets shift of slow moving average.
void SlowShift( int shift ) // Shift
2493
Standard Library
SlowMethod
Sets smoothing method of slow moving average.
void SlowMethod( ENUM_MA_METHOD method ) // Smoothing method
2494
Standard Library
SlowApplied
Sets applied price of slow moving average.
void SlowApplied( ENUM_APPLIED_PRICE applied ) // Applied price
2495
Standard Library
StopLoss
Sets the value of Stop Loss level (in points).
void StopLoss( int stop_loss ) // Stop Loss level
Parameters stop_loss [in] New value of Stop Loss level (in conventional 2/4-digit points).
2496
Standard Library
TakeProfit
Sets the value of Take Profit level (in points).
void TakeProfit( int take_profit ) // Take Profit level
Parameters take_profit [in] New value of Take Profit level (in conventional 2/4-digit points).
2497
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2498
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if period of fast moving average lower than period of slow moving average. For other cases it returns true.
2499
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast moving average has crossed upward (on the previous bar) the slow moving average. The output variables are set to: price = 0.0; sl = Current Price-Stop Loss level; tp = Current Price+Take Profit level. If the fast moving average has crossed upward the slow moving average on the previous (completed bar), it suggests to open long position on the current price with the calculated values of Stop Loss and Take Profit levels.
2500
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast moving average has crossed downward (on the previous bar) the slow moving average. The price variable is set to 0.0. If the fast moving average has crossed downward the slow moving average on the previous (completed bar), it suggests to close long position on the current price.
2501
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast moving average has crossed downward (on the previous bar) the slow moving average. The output variables are set to: price = 0.0; sl = Current Price+Stop Loss level; tp = Current PriceTake Profit level. If the fast moving average has crossed downward the slow moving average on the previous (completed bar), it suggests to open short position on the current price with the calculated values of Stop Loss and Take Profit levels.
2502
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the fast moving average has crossed upward (on the previous bar) the slow moving average. The price variable is set to 0.0. If the fast moving average has crossed upward the slow moving average on the previous (completed bar), it suggests to close short position on the current price.
2503
Standard Library
CSignalMA
CSignalMA is a class with implementation of trading strategy, based on price crossover with moving average.
Description
CSignalMA class implements trading signals, based on price crossover with moving average.
Declaration
class CSignalMA : public CExpertSignal
Title
#include <Expert\Signal\SignalMA.mqh>
Class Methods
Initialization Period Shift Method Applied virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of moving average Sets shift of moving average Set smoothing method of moving average Sets applied price of moving average Initializes indicators and time series Checks the settings
2504
Standard Library
Period
Sets period of moving average.
void Period( int period ) // Period
2505
Standard Library
Shift
Sets shift of moving average.
void Shift( int shift ) // Shift
2506
Standard Library
Method
Sets smoothing method.
void Method( ENUM_MA_METHOD method ) // Smoothing method
2507
Standard Library
Applied
Sets applied price.
void Applied( ENUM_APPLIED_PRICE applied ) // Applied price
2508
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2509
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the period of moving average is less or equal to 0. For all other cases it returns true.
2510
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is lower than moving average. 2. Bar close price is higher than moving average. 3. The slope of the moving average is positive (its values increases). If all conditions are satisfied at the previous bar, it suggests to open long position on the current price without setting of Stop Loss and Take Profit orders. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2511
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is higher than moving average. 2. Bar close price is lower than moving average. 3. The slope of the moving average is negative (its values decreases). If all conditions are satisfied at the previous bar, it suggests to close long position on the current price. The price variable is set to 0.0.
2512
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is higher than moving average. 2. Bar close price is lower than moving average. 3. The slope of the moving average is negative (its values decreases). If all conditions are satisfied at the previous bar, it suggests to open short position on the current price without setting of predefined Stop Loss and Take Profit orders. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2513
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is lower than moving average. 2. Bar close price is higher than moving average. 3. The slope of the moving average is positive (its values increases). If all conditions are satisfied at the previous bar, it suggests to close short position on the current price. The price variable is set to 0.0.
2514
Standard Library
CSignalMACD
CSignalMACD is a class with implementation of trading strategy based on crossover of main and signal lines of MACD indicator.
Description
CSignalMACD class implements trading signals based on crossover of main and signal lines of MACD indicator.
Declaration
class CSignalMACD : public CExpertSignal
Title
#include <Expert\Signal\SignalMACD.mqh>
Class Methods
Initialization PeriodFast PeriodSlow PeriodSignal TakeProfit StopLoss virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of fast moving average Sets period of slow moving average Sets period of the signal line Sets the value of Stop Loss Sets the value of Take Profit Initializes indicators and time series Checks the settings
2515
Standard Library
PeriodFast
Sets period of fast exponentially smoothed moving average.
void PeriodFast( int period ) // Period
Parameters period [in] Period of fast exponentially smoothed moving average of MACD indicator.
2516
Standard Library
PeriodSlow
Sets period of slow exponentially smoothed moving average.
void PeriodSlow( int period ) // Period
Parameters period [in] Period of slow exponentially smoothed moving average of MACD indicator.
2517
Standard Library
PeriodSignal
Sets period of the signal line.
void PeriodSignal( int period ) // Period
2518
Standard Library
TakeProfit
Sets the value of Take Profit level (in points).
void TakeProfit( int take_profit ) // Take Profit level
Parameters take_profit [in] New value of Take Profit level (in conventional 2/4-digit points).
2519
Standard Library
StopLoss
Sets the value of Stop Loss level (in points).
void StopLoss( int stop_loss ) // Stop Loss level
Parameters stop_loss [in] New value of Stop Loss level (in conventional 2/4-digit points).
2520
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] A pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2521
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if period of fast EMA is less than period of slow EMA. For all other cases it returns true.
2522
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the signal MACD line has crossed upward (on the previous bar) the main MACD line. The output variables are set to: price = 0.0; sl = Current Price-Stop Loss level; Price+Take Profit level. tp = Current
If the signal MACD line has crossed upward the main MACD line on the previous (completed bar), it suggests to open long position on the current price with setting of the corresponding Stop Loss and Take Profit orders.
2523
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the signal MACD line has crossed downward (on the previous bar) the main MACD line. The price variable is set to 0.0. If the signal MACD line has crossed downward the main MACD line on the previous (completed bar), it suggests to close long position on the current price.
2524
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the signal MACD line has crossed downward (on the previous bar) the main MACD line. The output variables are set to: price = 0.0; sl = Current Price+Stop Loss level; tp = Current PriceTake Profit level. If the signal MACD line has crossed downward the main MACD line on the previous (completed bar), it suggests to open short position on the current price with setting of the corresponding Stop Loss and Take Profit orders.
2525
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the signal MACD line has crossed upward (on the previous bar) the main MACD line. The price variable is set to 0.0. If the signal MACD line has crossed upward the main MACD line on the previous (completed bar), it suggests to close short position on the current price.
2526
Standard Library
CSignalMovingAverage
CSignalMovingAverage is a class with implementation of trading strategy based on price crossover with simple moving average.
Description
CSignalMovingAverage class implements trading signals, based on price crossover with simple moving average.
Declaration
class CSignalMovingAverage : public CExpertSignal
Title
#include <Expert\Signal\SignalMovingAverage.mqh>
Class Methods
Initialization Period Shift virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort virtual CheckCloseShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Checks conditions to close short position Sets period of simple moving average Sets shift of simple moving average Initializes indicators and time series Checks the settings
2527
Standard Library
Period
Sets period of simple moving average.
void Period( int period ) // Period
2528
Standard Library
Shift
Sets shift of simple moving average.
void Shift( int shift ) // Shift
2529
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2530
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the value of period of simple moving average is less or equal to zero. For all other cases it returns true.
2531
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is lower than moving average. 2. Bar close price is higher than moving average. 3. The slope of the moving average is positive (its values increases). If all conditions are satisfied at the previous bar, it suggests to open long position on the current price without setting of Stop Loss and Take Profit orders. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2532
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is higher than moving average. 2. Bar close price is lower than moving average. 3. The slope of the moving average is negative (its values decreases). If all conditions are satisfied at the previous bar, it suggests to close long position on the current price. The price variable is set to 0.0.
2533
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is higher than moving average. 2. Bar close price is lower than moving average. 3. The slope of the moving average is negative (its values decreases). If all conditions are satisfied at the previous bar, it suggests to open short position on the current price without setting of predefined Stop Loss and Take Profit orders. The output variables are set to: price = 0.0; sl = 0.0; tp = 0.0.
2534
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the following conditions are satisfied on the previous (completed) bar: 1. Bar open price is lower than moving average. 2. Bar close price is higher than moving average. 3. The slope of the moving average is positive (its values increases). If all conditions are satisfied at the previous bar, it suggests to close short position on the current price. The price variable is set to 0.0.
2535
Standard Library
CSignalITF
CSignalITF is a class with implementation of signal filtration algorithm, based on specified time periods.
Description
CSignalITF class implements filtration of trade signals, based on specified time periods.
Declaration
class CSignalITF : public CExpertSignal
Title
#include <Expert\Signal\SignalITF.mqh>
Class Methods
Initialization GoodMinuteOfHour BadMinutesOfHour GoodHourOfDay BadHoursOfDay GoodDayOfWeek BadDaysOfWeek Checking Trading Conditions virtual CheckOpenLong virtual CheckOpenShort Checks filter conditions the open long position Checks filter conditions the open short position Sets "good minute" within the hour Sets bit map of "bad minutes" within the hour Sets "good hour" within the day Sets bit map of "bad hours" within the day Sets "good day" within the week Sets bit map of "bad days" within the week
2536
Standard Library
GoodMinuteOfHour
Sets "good minute" within the hour.
void GoodMinuteOfHour( int good_minute_of_hour ) // good minute
Parameters good_minute_of_hour [in] Index of "good minute" within the hour. Note The correct values are: any value from 0 to 59 (index of the "good minute" within the hour) and -1 (all minutes within the hour are "good").
2537
Standard Library
BadMinutesOfHour
Sets bit map of "bad minutes" within the hour.
void BadMinutesOfHour( long bad_minutes_of_hour ) // "bad minutes" bit map
Parameters bad_minutes_of_hour [in] Bit map of "bad minutes" within the hour. Note The correct value of bit map is any value from 0 to 1152921504606846975 (111111111111111111111111111111111111111111111111111111111111b). An each individual bit of the number marks the minute of the hour as a "bad minute".
2538
Standard Library
GoodHourOfDay
Sets "good hour" within the day.
void GoodHourOfDay( int good_hour_of_day ) // good hour
Parameters good_hour_of_day [in] Index of "good hour" within the day. Note The correct values are: any value from 0 to 23 (index of the "good hour" within the hour) and -1 (all hours within the day are "good").
2539
Standard Library
BadHoursOfDay
Sets bit map of "bad hours" within the day.
void BadHoursOfDay( int bad_hours_of_day ) // "bad hours" bit map
Parameters bad_hours_of_day [in] Bit map of "bad hours" within the day. Note The correct value of bit map is any value from 0 to 16777215 (111111111111111111111111b). An each individual bit of the number marks the hour of the day as a "bad hour".
2540
Standard Library
GoodDayOfWeek
Sets "good day" within the week.
void GoodDayOfWeek( int good_day_of_week ) // good day
Parameters good_day_of_week [in] Index of "good day" within the week. Note The correct values are: any value from 0 (Sunday) to 6 (index of the "good day" within the week) and -1 (all days within the week are "good").
2541
Standard Library
BadDaysOfWeek
Sets bit map of "bad days" within the week.
void BadDaysOfWeek( int bad_days_of_week ) // "bad days" bit map
Parameters bad_days_of_week [in] Bit map of "bad days" within the week. Note The correct value of bit map is any value from 0 to 127 (1111111b). An each individual bit of the number marks the day of the week as a "bad day".
2542
Standard Library
CheckOpenLong
Checks filter conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if the filtration isn't needed, overwise false. Note The function returns true if the date, specified by expiration parameter is "good". The date is good, if the following three conditions are satisfied: 1. The week day isn't marked as "bad day" (in "bad days" bit map) and there isn't any "good day" specified. 2. The hour isn't marked as "bad hour" (in "bad hours" bit map) and there isn't any "good hour" specified. 3. The minute isn't marked as "bad minute" (in "bad minute" bit map) and there isn't any "good minute" specified. The variables price, sl and tp aren't used, they added for compatibility with parent class interface.
2543
Standard Library
CheckOpenShort
Checks filter conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if the filtration isn't needed, overwise false. Note The function returns true if the date, specified by expiration parameter is "good". The date is good, if the following three conditions are satisfied: 1. The week day isn't marked as "bad day" (in "bad days" bit map) and there isn't any "good day" specified. 2. The hour isn't marked as "bad hour" (in "bad hours" bit map) and there isn't any "good hour" specified. 3. The minute isn't marked as "bad minute" (in "bad minute" bit map) and there isn't any "good minute" specified. The variables price, sl and tp aren't used, they added for compatibility with parent class interface.
2544
Standard Library
CSignal2EMA_ITF
CSignal2EMA_ITF is a class with implementation of trading signal algorithm, based on crossover of two exponentially smoothed moving averages with signal filtration, based on specified time periods.
Description
CSignal2EMA_ITF class implements trading signal algorithm, based on crossover of two exponentially smoothed moving averages with signal filtration, based on specified time periods.
Declaration
class CSignal2EMA_ITF : public CExpertSignal
Title
#include <Expert\Signal\Signal2EMA-ITF.mqh>
Class Methods
Initialization PeriodFastEMA PeriodSlowEMA PeriodATR Limit StopLoss TakeProfit Expiration GoodMinuteOfHour BadMinutesOfHour GoodHourOfDay BadHoursOfDay GoodDayOfWeek BadDaysOfWeek virtual InitIndicators virtual ValidationSettings Checking Trading Conditions virtual CheckOpenLong virtual CheckCloseLong virtual CheckOpenShort Checks conditions to open long position Checks conditions to close long position Checks conditions to open short position Sets period of fast EMA Sets period of slow EMA Sets period of ATR indicator Sets Limit level Sets Stop Loss level Sets Take Profit level Sets order expiration time Sets "good minute" within the hour Sets bit map of "bad minutes" within the hour Sets "good hour" within the day Sets bit map of "bad hours" within the day Sets "good day" within the week Sets bit map of "bad days" within the week Initializes indicators and time series Checks the settings
2545
Standard Library
Checks conditions to close short position Checks Trailing Stop conditions of pending buy order Checks Trailing Stop conditions of pending sell order
virtual CheckTrailingOrderShort
2546
Standard Library
PeriodFastEMA
Sets period of fast EMA.
void PeriodFastEMA( int period ) // Period
2547
Standard Library
PeriodSlowEMA
Sets period of slow EMA.
void PeriodSlowEMA( int period ) // Period
2548
Standard Library
PeriodATR
Sets period of ATR indicator.
void PeriodATR( int period ) // Period
Parameters period [in] Period of ATR indicator. Note The ATR indicator measures the market volatility. Its values will be used (instead of points) as units for Limit, Stop Loss and Take Profit prices.
2549
Standard Library
Limit
Sets the value of Limit level (in units of ATR indicator values).
void StopLoss( double limit ) // Limit level
Parameters limit [in] New value of Limit level (in units of ATR indicator values).
2550
Standard Library
StopLoss
Sets the value of Stop Loss level (in units of ATR indicator values).
void StopLoss( int stop_loss ) // Stop Loss level
Parameters stop_loss [in] New value of Stop Loss level (in units of ATR indicator values).
2551
Standard Library
TakeProfit
Sets the value of Take Profit level (in units of ATR indicator values).
void TakeProfit( int take_profit ) // Take Profit level
Parameters take_profit [in] New value of Take Profit level (in units of ATR indicator values).
2552
Standard Library
Expiration
Sets order expiration period.
void Expiration( int expiration ) // Number of bars
2553
Standard Library
GoodMinuteOfHour
Sets "good minute" within the hour.
void GoodMinuteOfHour( int good_minute_of_hour ) // good minute
Parameters good_minute_of_hour [in] Index of "good minute" within the hour. Note The correct values are: any value from 0 to 59 (index of the "good minute" within the hour) and -1 (all minutes within the hour are "good").
2554
Standard Library
BadMinutesOfHour
Sets bit map of "bad minutes" within the hour.
void BadMinutesOfHour( long bad_minutes_of_hour ) // "bad minutes" bit map
Parameters bad_minutes_of_hour [in] Bit map of "bad minutes" within the hour. Note The correct value of bit map is any value from 0 to 1152921504606846975 (111111111111111111111111111111111111111111111111111111111111b). An each individual bit of the number marks the minute of the hour as a "bad minute".
2555
Standard Library
GoodHourOfDay
Sets "good hour" within the day.
void GoodHourOfDay( int good_hour_of_day ) // good hour
Parameters good_hour_of_day [in] Index of "good hour" within the day. Note The correct values are: any value from 0 to 23 (index of the "good hour" within the hour) and -1 (all hours within the day are "good").
2556
Standard Library
BadHoursOfDay
Sets bit map of "bad hours" within the day.
void BadHoursOfDay( int bad_hours_of_day ) // "bad hours" bit map
Parameters bad_hours_of_day [in] Bit map of "bad hours" within the day. Note The correct value of bit map is any value from 0 to 16777215 (111111111111111111111111b). An each individual bit of the number marks the hour of the day as a "bad hour".
2557
Standard Library
GoodDayOfWeek
Sets "good day" within the week.
void GoodDayOfWeek( int good_day_of_week ) // good day
Parameters good_day_of_week [in] Index of "good day" within the week. Note The correct values are: any value from 0 (Sunday) to 6 (index of the "good day" within the week) and -1 (all days within the week are "good").
2558
Standard Library
BadDaysOfWeek
Sets bit map of "bad days" within the week.
void BadDaysOfWeek( int bad_days_of_week ) // "bad days" bit map
Parameters bad_days_of_week [in] Bit map of "bad days" within the week. Note The correct value of bit map is any value from 0 to 127 (1111111b). An each individual bit of the number marks the day of the week as a "bad day".
2559
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2560
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function returns false if the period of fast moving average is greater or equal to period of slow moving average. For all other cases it returns true.
2561
Standard Library
CheckOpenLong
Checks conditions to open long position.
virtual bool CheckOpenLong( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the value of fast EMA is higher than slow EMA and time filtration isn't used. The value of slow EMA at the previous (completed) bar is assumed as a base price. The value of the price variable is dependent on sign of the Limit level. The values of sl and tp variables is set calculated using the base price and Stop Loss and Take Profit levels. It suggests to open long position at the calculated price (base price) with setting of Stop Loss and Take Profit, specified in sl and tp parameters.
2562
Standard Library
CheckCloseLong
Checks conditions to close long position.
virtual bool CheckCloseLong( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function always returns false, there isn't any conditions to close long position.
2563
Standard Library
CheckOpenShort
Checks conditions to open short position.
virtual bool CheckOpenShort( double& double& double& price, sl, tp, // Price // Stop Loss price // Take Profit price // Order expiration time
datetime& expiration )
Parameters price [in][out] Variable for price, passed by reference. sl [in][out] Variable for "Stop Loss" price, passed by reference. tp [in][out] Variable for "Take Profit" price, passed by reference. expiration [in][out] Variable for order expiration time (if necessary), passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function returns true if the value of fast EMA is lower than slow EMA and time filtration isn't used. The value of slow EMA at the previous (completed) bar is assumed as a base price. The value of the price variable is dependent on sign of the Limit level. The values of sl and tp variables is set calculated using the base price and Stop Loss and Take Profit levels. It suggests to open long position at the calculated price (base price) with setting of Stop Loss and Take Profit, specified in sl and tp parameters.
2564
Standard Library
CheckCloseShort
Checks conditions to close short position.
virtual bool CheckCloseShort( double& price ) // Price
Parameters price [in][out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The function always returns false, there isn't any conditions to close short position.
2565
Standard Library
CheckTrailingOrderLong
Checks Trailing Stop conditions of pending buy order.
virtual bool CheckTrailingOrderLong( COrderInfo* order, double& ) price // COrderInfo object pointer // Price
Parameters order [in][out] Pointer to COrderInfo object. price [out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The value of slow EMA at the previous (completed) bar is assumed as a base price. The value of the price variable is dependent on sign of the Limit level. The Level is positive for pending orders of Buy limit type and negative for pending orders of Buy Stop type. It suggests to trail pending orders along the values of slow EMA.
2566
Standard Library
CheckTrailingOrderShort
Checks Trailing Stop conditions of pending sell order.
virtual bool CheckTrailingOrderShort( COrderInfo* order, double& ) price // COrderInfo object pointer // Price
Parameters order [in][out] Pointer to COrderInfo object. price [out] Variable for price, passed by reference. Returned value true if conditions are satisfied, overwise false. Note The value of slow EMA at the previous (completed) bar is assumed as a base price. The value of the price variable is dependent on sign of the Limit level. The Level is positive for pending orders of Sell limit type and negative for pending orders of Sell Stop type. It suggests to trail pending orders along the values of slow EMA.
2567
Standard Library
CTrailingMA
CTrailingNone
CTrailingPSAR
2568
Standard Library
CTrailingFixedPips
CTrailingFixedPips is a class with implementation of Trailing Stop algorithm, based on fixed points trailing. If position has Stop Loss price, it checks the minimal allowed Stop Loss distance to the current price. If its value is lower, that Stop Loss level, it suggests to set new Stop Loss price. For this case if position has Take Profit price, it suggests to set new Take Profit price. If Expert Advisor has been initialized with the flag every_tick=false, it will perform all operations (trading, trailing, etc) only at the new bar. For this case Take profit level can be used. It will allow you to close opened position at Take Profit price before the new bar will be completed.
Description
CTrailingFixedPips implements the Trailing Stop algorithm, based on positions trailing with the fixed points.
Declaration
class CTrailingFixedPips: public CExpertTrailing
Title
#include <Expert\Trailing\CTrailingFixedPips.mqh>
Class Methods
Initialization StopLevel ProfitLevel virtual ValidationSettings Check Trailing Methods virtual CheckTrailingStopLong virtual CheckTrailingStopShort Check Trailing Stop conditions of long position Check Trailing Stop conditions of short position Sets the value of Stop Loss level Sets the value of Take Profit level Checks the settings
2569
Standard Library
StopLevel
Sets the value Stop Loss level (in points).
void StopLevel( int stop_level ) // Stop Loss level
Parameters stop_loss [in] The value of Stop Loss level (in conventional 2/4-digit points). Note If Stop Loss level is equal to 0, the Trailing Stop is not used.
2570
Standard Library
ProfitLevel
Sets the value of Take Profit level (in points).
void ProfitLevel( int profit_level ) // Take profit level
Parameters profit_level [in] The value of Take Profit level (in conventional 2/4-digit points). Note If profit level is equal to 0, the Trailing Stop is not used.
2571
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function checks Take Profit and Stop Loss levels. The correct values are 0 and values, greater than minimal stop for stop orders for the symbol.
2572
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note If Stop Loss level is equal to 0, the Trailing Stop is not used. If position already has Stop Loss price, its value is assumed as a base price, overwise the position open price is assumed as a base price. If the current Bid price is higher than base price+stop loss level, it suggests to set new Stop Loss price. In this case, If position already has Take Profit price, it suggests to set new Take Profit price equal to Bid price+take proft level.
2573
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note If Stop Loss level is equal to 0, the Trailing Stop is not used. If position already has Stop Loss price, its value is assumed as a base price, overwise the position open price is assumed as a base price. If the current Ask price is lower than base price-stop loss level, it suggests to set new Stop Loss price. In this case, If position already has Take Profit price, it suggests to set new Take Profit price equal to Ask price-take proft level.
2574
Standard Library
CTrailingMA
CTrailingMA is a class with implementation of Trailing Stop algorithm, based on the values of moving average indicator.
Description
CTrailingMA class implements Trailing Stop algorithm, based on the values of moving average indicator of the previous (completed) bar.
Declaration
class CTrailingMA: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingMA.mqh>
Class Methods
Initialization Period Shift Method Applied virtual InitIndicators virtual ValidationSettings Check Trailing Methods virtual CheckTrailingStopLong virtual CheckTrailingStopShort Check Trailing Stop conditions of long position Check Trailing Stop conditions of short position Sets period of moving average Sets shift of moving average Sets smoothing method of moving average Sets applied price of moving average Initializes indicators and time series Checks the settings
2575
Standard Library
Period
Sets period of moving average.
void Period( int period ) // Smoothing period
2576
Standard Library
Shift
Sets shift of moving average.
void Shift( int shift ) // Shift
2577
Standard Library
Method
Sets smoothing method of moving average.
void Method( ENUM_MA_METHOD method ) // Smoothing method
2578
Standard Library
Applied
Sets applied price of moving average.
void Applied( ENUM_APPLIED_PRICE applied ) // Applied price
2579
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2580
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function checks the period of moving average, the correct values are positive.
2581
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The first it calculates the maximal allowed Stop Loss price, closest to the current price and calculates Stop Loss price using the values of moving average indicator of the previous (completed) bar. If position already has Stop Loss price, its value is assumed as a base price, overwise the base price is the open price of the position. If the calculated Stop Loss price is higher than base price and lower than maximal allowed Stop Loss price, it suggests to set new Stop Loss price.
2582
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The first it calculates the minimal allowed Stop Loss price, closest to the current price and calculates Stop Loss price using the values of moving average indicator of the previous (completed) bar. If position already has Stop Loss price, its value is assumed as a base price, overwise the base price is the open price of the position. If the calculated Stop Loss price is higher than base price and lower than minimal allowed Stop Loss price, it suggests to set new Stop Loss price.
2583
Standard Library
CTrailingNone
CTrailingNone is a gag class. This class should be used at initialization of Trailng object if your strategy doesn't use Trailing Stop.
Description
CTrailingNone class doesn't implement any Trailing Stop algorithms. The methods of checking Trailing Stop conditions always return false.
Declaration
class CTrailingNone: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingNone.mqh>
Class Methods
Check Trailing Methods virtual CheckTrailingStopLong A gag method for check Trailing Stop conditions of long position A gag method for check Trailing Stop conditions of short position
virtual CheckTrailingStopShort
2584
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The function always returns false.
2585
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort( CPositionInfo* position, double& double& ) sl, tp // CPositionInfo object pointer // Stop Loss price // Take Profit price
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The function always returns false.
2586
Standard Library
CTrailingPSAR
CTrailingPSAR is a class with implementation of Trailing Stop algorithm, based on the values of of Parabolic SAR indicator.
Description
CTrailingPSAR class implements the Trailing Stop algorithm, based on the values of Parabolic SAR indicator of the previous (completed) bar.
Declaration
class CTrailingPSAR: public CExpertTrailing
Title
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
Class Methods
Initialization Step Sets the value of step of Parabolic SAR indicator Sets the value of maximum of Parabolic SAR indicator Initializes indicators and time series
Maximum
Check conditions of trailing stop of long position Check conditions of trailing stop of short position
virtual CheckTrailingStopShort
2587
Standard Library
Step
Sets the value of step of Parabolic SAR indicator.
void Step( double step ) // Step
2588
Standard Library
Maximum
Sets the value of maximum of Parabolic SAR indicator.
void Maximum( double maximum ) // Maximum
2589
Standard Library
InitIndicators
Initializes indicators and time series.
virtual bool InitIndicators( CIndicators* indicators ) // CIndicators collection pointer
Parameters indicators [in] Pointer to indicators and time series collection (CExpert class member). Returned value true if successful, overwise false.
2590
Standard Library
CheckTrailingStopLong
Checks Trailing Stop conditions of long position.
virtual bool CheckTrailingStopLong( CPositionInfo* position, double& double& ) sl, tp // // //
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The first it calculates the maximal allowed Stop Loss price, closest to the current price and calculates Stop Loss price using the values of Parabolic SAR indicator of the previous (completed) bar. If position already has Stop Loss price, its value is assumed as a base price, overwise the position open price is assumed as a base price. If the calculated Stop Loss price is higher than base price and lower than maximal allowed Stop Loss price, it suggests to set new Stop Loss price.
2591
Standard Library
CheckTrailingStopShort
Checks Trailing Stop conditions of short position.
virtual bool CheckTrailingStopShort( CPositionInfo* position, double& double& ) sl, tp // // //
Parameters position [in] Pointer to CPositionInfo object. sl [in][out] Variable for Stop Loss price. tp [in][out] Variable for Take Profit price. Returned value true if conditions are satisfied, overwise false. Note The first it calculates the minimal allowed Stop Loss price, closest to the current price and calculates Stop Loss price using the values of Parabolic SAR indicator of the previous (completed) bar. If position already has Stop Loss price, its value is assumed as a base price, overwise the position open price is assumed as a base price. If the calculated Stop Loss price is higher than base price and lower than minimal allowed Stop Loss price, it suggests to set new Stop Loss price.
2592
Standard Library
CMoneyFixedMargin
CMoneyFixedRisk
CMoneyNone
CMoneySizeOptimized
2593
Standard Library
CMoneyFixedLot
CMoneyFixedLot is the class money management algorithm, based on trading with predefined fixed lot size.
Description
CMoneyFixedLot implements money management algorithm, based on trading with predefined fixed lot size.
Declaration
class CMoneyFixedLot: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedLot.mqh>
Class Methods
Initialization Lots virtual ValidationSettings Money and Risk Management Methods virtual CheckOpenLong virtual CheckOpenShort Gets trade volume for long position Gets trade volume for short position Sets trading volume Checks the settings
2594
Standard Library
Lots
Sets trading volume (in lots).
void Lots( double lots ) // Lots
2595
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note Checks the specified trading volume for correctness.
2596
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function always returns the fixed trade volume, defined by Lots method.
2597
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for short position. Note The function always returns the fixed trade volume, defined by Lots method.
2598
Standard Library
CMoneyFixedMargin
CMoneyFixedMargin is the class money management algorithm, based on trading with predefined fixed margin.
Description
CMoneyFixedMargin implements money management algorithm, based on trading with predefined fixed margin.
Declaration
class CMoneyFixedMargin: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedMargin.mqh>
Class Methods
Money and Risk Management Methods virtual CheckOpenLong virtual CheckOpenShort Gets trade volume for long position Gets trade volume for short position
2599
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function returns trade volume for long position, it uses the fixed margin. The margin is defined by Percent parameter of CExpertMoney base class.
2600
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for short position. Note The function returns trade volume for short position, it uses the fixed margin. The margin is defined by Percent parameter of CExpertMoney base class.
2601
Standard Library
CMoneyFixedRisk
CMoneyFixedRisk is a class with implementation of money management algorithm with fixed predefined risk.
Description
CMoneyFixedRisk class implements the money management algorithm with fixed predefined risk.
Declaration
class CMoneyFixedRisk: public CExpertMoney
Title
#include <Expert\Money\MoneyFixedRisk.mqh>
Class Methods
Money and Risk Management Methods virtual CheckOpenLong virtual CheckOpenShort Gets trade volume for long position Gets trade volume for short position
2602
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function returns trade volume for long position, it uses the fixed risk. The risk is defined by Percent parameter of CExpertMoney base class.
2603
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for short position. Note The function returns trade volume for short position, it uses the fixed risk. The risk is defined by Percent parameter of CExpertMoney base class.
2604
Standard Library
CMoneyNone
CMoneyNone is a class with implementation of trading algorithm with minimal allowed lot.
Description
CMoneyNone class implements trading with minimal allowed lot.
Declaration
class CMoneyNone: public CExpertMoney
Title
#include <Expert\Money\MoneyNone.mqh>
Class Methods
Initialization virtual ValidationSettings Money and Risk Management Methods virtual CheckOpenLong virtual CheckOpenShort Gets trade volume for long position Gets trade volume for short position Checks the settings
2605
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note The function always returns true.
2606
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function always returns the minimal lot size.
2607
Standard Library
CheckOpenShort
Gets trade volume for long position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for short position. Note The function always returns the minimal lot size.
2608
Standard Library
CMoneySizeOptimized
CMoneySizeOptimized is a class with implementation of money management algorithm, based on trading with variable lot size, depending on results of the previous deals.
Description
CMoneySizeOptimized implements money management algorithm, based on trading with variable lot size, depending on results of the previous deals.
Declaration
class CMoneySizeOptimized: public CExpertMoney
Title
#include <Expert\Money\MoneySizeOptimized.mqh>
Class Methods
Initialization DecreaseFactor virtual ValidationSettings Money and Risk Management Methods virtual CheckOpenLong virtual CheckOpenShort Gets trade volume for long position Gets trade volume for short position Sets the value of decrease factor Checks the settings
2609
Standard Library
DecreaseFactor
Sets the value of decrease factor.
void DecreaseFactor( double decrease_factor ) // Decrease factor
Parameters decrease_factor [in] Decrease factor. Note The DecreaseFactor defines the volume decreasing coefficient (compared with the volume of previous position) for the case of consecutive loss trades.
2610
Standard Library
ValidationSettings
Checks the settings.
virtual bool ValidationSettings()
Returned value true if successful, overwise false. Note If the value of decrease factor is negative, it returns false, overwise it returns true.
2611
Standard Library
CheckOpenLong
Gets trade volume for long position.
virtual double CheckOpenLong( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function returns trade volume for long position, the volume dependent on results of the previous deals.
2612
Standard Library
CheckOpenShort
Gets trade volume for short position.
virtual double CheckOpenShort( double price, double sl ) // Price // Stop Loss price
Parameters price [in] Price. sl [in] Stop Loss price. Returned value Trade volume for long position. Note The function returns trade volume for short position, the volume dependent on results of the previous deals.
2613
Functions OnInit and OnDeinit perform the same role as init and deinit in MQL4 - they are designed to locate the code, which must be performed during initialization and deinitialization of mql5 programs. You can either just rename these functions accordingly, or leave them as they are, but add calls of these functions in corresponding places. Example:
void OnInit() { //--- Functions is called to initialize init(); }
2614
The start function is replaced by OnStart only in scripts. In Expert Advisors and indicators it should be renamed to OnTick and OnCalculate, respectively. The code that is to be executed during a mql5 program operation should be located in these three functions: mql5-program script indicator Expert Advisor main function OnStart OnCalculate OnTick
If the indicator or script code does not contain the main function, or the function name differs from the required one, the call of this function is not performed. It means, if the source code of a script doesn't contain OnStart, such a code will be compiled as an Expert Advisor. If an indicator code doesn't contain the OnCalculate function, the compilation of such an indicator is impossible.
Predefined Variables
In MQL5 there are no such predefined variables as Ask, Bid, Bars. Variables Point and Digits have a slightly different spelling: MQL4 Digits Point MQL5 _Digits _Point _LastError _Period _Symbol _StopFlag _UninitReason
Access to Timeseries
In MQL5 there are no such predefined timeseries as Open [], High [], Low [], Close [], Volume [] and Time []. The necessary depth of a timeseries can now be set using corresponding functions to access timeseries.
2615
Expert Advisors
Expert Advisors in MQL5 do not require the obligatory presence of the function for handling the events of a new tick receipt - OnTick, as it was in MQL4 (the start function in MQL4 is executed when you receive a new tick), because in MQL5 Expert Advisors can contain pre-defined handler functions are several types of events: OnTick receipt of a new tick; OnTimer timer event; OnTrade - trade event; OnChartEvent events of input from the keyboard and mouse, events of a graphic object moving, event of a text editing completion in the entry field of the LabelEdit object; OnBookEvent event of Depth of Market status change.
Custom Indicators
In MQL4, the number of indicator buffers is limited and can't exceed 8. In MQL5 there are no such limitations, but it should be remembered that each indicator buffer requires allocation of a certain part of memory for its location in the terminal, so the new possibility should not be abused. MQL4 offered only 6 types of custom indicator plotting; while MQL5 now offers 18 drawing styles. The names of drawing types haven't changed, but the ideology of the graphical representation of indicators has changed significantly. The direction of indexing in indicator buffers also differs. By default, in MQL5 all the indicator buffers have the behavior of common arrays, i.e. 0 indexed element is the oldest one in the history, and as the index increases, we move from the oldest data to the most recent ones. The only function for working with custom indicators that was preserved from MQL4 is SetIndexBuffer. But its call has changed; now you should specify type of data to be stored in an array, linked to the indicator buffer. Properties of custom indicators also have changed and expanded. New functions for accessing timeseries have been added, so the total calculation algorithm must be reconsidered.
Graphical Objects
The number of graphical objects in has increased significantly MQL5. Besides, graphical objects can now be positioned in time with the accuracy of a second in a chart of any timeframe - now object anchor points are not rounded off to the bar opening time in the current price chart. For objects Arrow, Text and Label now way of binding can be indicated, and for Label, Button, Chart, Bitmap Label and Edit chart corner, to which the object is anchored, can be set.