bool CalendarCountryById( const long country_id, // country ID MqlCalendarCountry& country // country description );CalendarEventById — gets event description by identifier.
bool CalendarEventById( const long event_id, // event ID MqlCalendarEvent& event // event description );CalendarValueById — gets event value description by identifier.
bool CalendarValueById( const long value_id, // value ID MqlCalendarValue& value // value description );CalendarEventByCountry — gets the array of available events for the country.
bool CalendarEventByCountry( string country_code, // country code MqlCalendarEvent& events[] // array of events );CalendarEventByCurrency — gets the array of available events for the affected currency.
bool CalendarEventByCurrency( string currency, // currency MqlCalendarEvent& events[] // array of events );CalendarValueHistoryByEvent — gets the array of values for the specified time period, by event identifier.
bool CalendarValueHistoryByEvent( ulong event_id, // event ID MqlCalendarValue& values[], // array of values datetime datetime_from, // period beginning date datetime datetime_to=0 // period end date );CalendarValueHistory — gets the array of values for the specified time period for all events, filtered by country and/or currency.
bool CalendarValueHistory( MqlCalendarValue& values[], // array of values datetime datetime_from, // beginning of period datetime datetime_to=0, // end of period string country_code=NULL, // country code string currency=NULL // currency );CalendarValueLastByEvent — gets an array of last event values by identifier. This function enables the request of the values which have appeared since the previous request. The in/out parameter "change_id" is additionally used for this operation.
bool CalendarValueHistory( ulong event_id, // event ID ulong& change_id, // last calendar change ID MqlCalendarValue& values[] // array of values );CalendarValueLast — gets the array of last values for all events, filtered by country and/or currency. This function enables the request of the values which have appeared since the previous request. Similarly to CalendarValueLastByEvent, the "change_id" property is used for the request.
bool CalendarValueHistory( ulong event_id, // event ID ulong& change_id, // last calendar change ID MqlCalendarValue& values[], // array of values string country_code=NULL, // country code string currency=NULL // currency );
struct MqlCalendarCountry { ulong id; // country ID in ISO 3166-1 string name; // text name of the country string code; // code name of the country in ISO 3166-1 alpha-2 string currency; // country currency code string currency_symbol; // country currency symbol/sign string url_name; // country name used in URL on mql5.com };MqlCalendarEvent — event description.
struct MqlCalendarEvent { ulong id; // event ID ENUM_CALENDAR_EVENT_TYPE type; // event type ENUM_CALENDAR_EVENT_SECTOR sector; // sector to which the event belongs ENUM_CALENDAR_EVENT_FREQUENCY frequency; // event release frequency ENUM_CALENDAR_EVENT_TIMEMODE time_mode; // event release time mode ulong country_id; // country ID ENUM_CALENDAR_EVENT_UNIT unit; // unit for the event values ENUM_CALENDAR_EVENT_IMPORTANCE importance; // event importance ENUM_CALENDAR_EVENT_MULTIPLIER multiplier; // event importance multiplier uint digits; // number of decimal places in the event value string source_url; // source URL string event_code; // event code string name; // text name of the event in the terminal language };MqlCalendarValue — event value description.
struct MqlCalendarValue { ulong id; // value ID ulong event_id; // event ID datetime time; // event date and time datetime period; // period, for which the event is published int revision; // published indicator revision in relation to the reported period long actual_value; // current event value long prev_value; // previous event value long revised_prev_value; // revised previous event value long forecast_value; // forecast event value ENUM_CALENDAR_EVENT_IMPACRT impact_type; // potential impact on the currency rate };
enum ENUM_CALENDAR_EVENT_FREQUENCY { CALENDAR_FREQUENCY_NONE =0, // not used CALENDAR_FREQUENCY_WEEK =1, // weekly CALENDAR_FREQUENCY_MONTH =2, // monthly CALENDAR_FREQUENCY_QUARTER =3, // quarterly CALENDAR_FREQUENCY_YEAR =4, // yearly CALENDAR_FREQUENCY_DAY =5, // daily }; enum ENUM_CALENDAR_EVENT_TYPE { CALENDAR_TYPE_EVENT =0, // event (meeting, speech, etc.) CALENDAR_TYPE_INDICATOR =1, // indicator CALENDAR_TYPE_HOLIDAY =2, // holiday }; enum ENUM_CALENDAR_EVENT_SECTOR { CALENDAR_SECTOR_NONE =0, // no CALENDAR_SECTOR_MARKET =1, // market CALENDAR_SECTOR_GDP =2, // GDP CALENDAR_SECTOR_JOBS =3, // jobs CALENDAR_SECTOR_PRICES =4, // prices CALENDAR_SECTOR_MONEY =5, // money CALENDAR_SECTOR_TRADE =6, // trade CALENDAR_SECTOR_GOVERNMENT =7, // government CALENDAR_SECTOR_BUSINESS =8, // business CALENDAR_SECTOR_CONSUMER =9, // consumer CALENDAR_SECTOR_HOUSING =10, // housing CALENDAR_SECTOR_TAXES =11, // taxes CALENDAR_SECTOR_HOLIDAYS =12, // holidays }; enum ENUM_CALENDAR_EVENT_IMPORTANCE { CALENDAR_IMPORTANCE_NONE =0, // no CALENDAR_IMPORTANCE_LOW =1, // low CALENDAR_IMPORTANCE_MODERATE =2, // moderate CALENDAR_IMPORTANCE_HIGH =3, // high }; enum ENUM_CALENDAR_EVENT_UNIT { CALENDAR_UNIT_NONE =0, // no CALENDAR_UNIT_PERCENT =1, // percent CALENDAR_UNIT_CURRENCY =2, // national currency CALENDAR_UNIT_HOUR =3, // number of hours CALENDAR_UNIT_JOB =4, // number of jobs CALENDAR_UNIT_RIG =5, // number of rigs CALENDAR_UNIT_USD =6, // US dollar CALENDAR_UNIT_PEOPLE =7, // number of people CALENDAR_UNIT_MORTGAGE =8, // number of mortgages CALENDAR_UNIT_VOTE =9, // number of votes CALENDAR_UNIT_BARREL =10, // number of barrels CALENDAR_UNIT_CUBICFEET =11, // volume in cubic feet CALENDAR_UNIT_POSITION =12, // number of job positions CALENDAR_UNIT_BUILDING =13 // number of buildings }; enum ENUM_CALENDAR_EVENT_MULTIPLIER { CALENDAR_MULTIPLIER_NONE =0, // no CALENDAR_MULTIPLIER_THOUSANDS =1, // thousands CALENDAR_MULTIPLIER_MILLIONS =2, // millions CALENDAR_MULTIPLIER_BILLIONS =3, // billions CALENDAR_MULTIPLIER_TRILLIONS =4, // trillions }; enum ENUM_CALENDAR_EVENT_IMPACRT { CALENDAR_IMPACT_NA =0, // not available CALENDAR_IMPACT_POSITIVE =1, // positive CALENDAR_IMPACT_NEGATIVE =2, // negative }; enum ENUM_CALENDAR_EVENT_TIMEMODE { CALENDAR_TIMEMODE_DATETIME =0, // the source publishes the exact time CALENDAR_TIMEMODE_DATE =1, // the event takes the whole day CALENDAR_TIMEMODE_NOTIME =2, // the source does not publish the event time CALENDAR_TIMEMODE_TENTATIVE =3, // the source provides only date, but does not publish the exact time in advance, exact time is added when event occurs };
ERR_CALENDAR_MORE_DATA =5400, // the array is too small for the whole result (values which fit in the array were passed) ERR_CALENDAR_TIMEOUT =5401, // timed out waiting for a response to the calendar data request ERR_CALENDAR_NO_DATA =5402, // data not found
bool CharArrayToStruct( void& struct_object, // structure const uchar& char_array[], // array uint start_pos=0 // starting position in the array );StructToCharArray copies a POD structure to a uchar array.
bool StructToCharArray( const void& struct_object, // structure uchar& char_array[], // array uint start_pos=0 // starting position in the array );
ushort MathSwap(ushort value); uint MathSwap(uint value); ulong MathSwap(ulong value);
bool StringReserve( string& string_var, // string uint new_capacity // buffer size for the string );StringSetLength sets the specified string length in characters.
bool StringSetLength( string& string_var, // string uint new_length // new string length );
bool ArrayRemove( void& array[], // array of any type uint start, // the index to start removal uint count=WHOLE_ARRAY // number of elements );ArrayInsert inserts to a receiver array the specified number of elements from the source array, starting with the specified index.
bool ArrayInsert( void& dst_array[], // receiver array const void& src_array[], // source array uint dst_start, // index in the receiver array where to insert uint src_start=0, // index in the source array to start copying uint count=WHOLE_ARRAY // number of inserted elements );ArrayReverse reverses in an array the specified number of elements starting with the specified index.
bool ArrayReverse( void& array[], // array of any type uint start=0, // index to start reversing uint count=WHOLE_ARRAY // number of elements );
int CustomBookAdd( const string symbol, // symbol name const MqlBookInfo& books[] // an array with the DOM elements descriptions uint count=WHOLE_ARRAY // number of elements to be used );
bool CustomSymbolCreate( const string symbol_name, // custom symbol name const string symbol_path="", // name of the group in which the symbol will be created const string symbol_origin=NULL // name of the symbol based on which the custom symbol will be created );The name of the symbol, from which the properties of for the custom symbol should be copied, is specified in the "symbol_origin" parameter.
Added user interface translation into Croatian.
Documentation has been updated.
#import "TestLib.dll" //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { int x=41; TestClass::Inc(x); Print(x); }The C# code of the Inc function of the TestClass looks as follows:
public class TestClass { public static void Inc(ref int x) { x++; } }As a result of execution, the script returns the value of 42.
struct MqlTick
{
datetime time; // Last price update time
double bid; // Current Bid price
double ask; // Current Ask price
double last; // Current price of the Last trade
ulong volume; // Volume for the current Last price
long time_msc; // Last price update time in milliseconds
uint flags; // Tick flags
double volume_real; // Volume for the current Last price with greater accuracy
};
struct MqlBookInfo { ENUM_BOOK_TYPE type; // order type from the ENUM_BOOK_TYPE enumeration double price; // price long volume; // volume double volume_real; // volume with greater accuracy };
//+------------------------------------------------------------------+ //| Default packing | //+------------------------------------------------------------------+ struct A { char a; int b; }; //+------------------------------------------------------------------+ //| Specified packing | //+------------------------------------------------------------------+ struct B pack(4) { char a; int b; }; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { Print("sizeof(A)=",sizeof(A)); Print("sizeof(B)=",sizeof(B)); } //+------------------------------------------------------------------+Conclusion:
sizeof(A)=5 sizeof(B)=8Find more information about alignment within structures in MSDN.
enum Main { PRICE_CLOSE_, PRICE_OPEN_ }; input Main Inp=PRICE_CLOSE; //+------------------------------------------------------------------+ //| Start function | //+------------------------------------------------------------------+ void OnStart() { }The compiler displays the warning:
class X { }; void f(int) { } template<typename T> void a(T*) { new T(2); } // previously, the compiler generated the error here template<typename T> void a() { f(0); } void OnInit() { a<X>(); }
Updated documentation.
Documentation has been updated.
Documentation has been updated.
datetime iTime( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
double iOpen( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
double iHigh( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
double iLow( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
double iClose( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
long iVolume( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
int iBars( string symbol, // Symbol ENUM_TIMEFRAMES timeframe // Period );
int iBarShift( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period datetime time, // Time bool exact=false // Mode );
int iLowest( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int type, // Timeseries identifier int count, // Number of elements int start // Index );
int iHighest( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int type, // Timeseries identifier int count, // Number of elements int start // Index );
long iRealVolume( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
long iTickVolume( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
long iSpread( string symbol, // Symbol ENUM_TIMEFRAMES timeframe, // Period int shift // Shift );
void TesterHideIndicators( bool hide // Flag );
Documentation has been updated.
Fixed errors reported in crash logs.
MetaTrader 5 build 1745 will be the last platform version supporting Microsoft Windows XP/2003/Vista.
A few months ago, we announced end of support for older versions of operating systems.
Windows 2003, Windows Vista and especially Microsoft Windows XP are
outdated operating systems. Microsoft ended support for Windows XP three
years ago, because potential hardware capabilities could no longer be
realized on this system due to technical limitations.
MetaTrader 5 build 1745 and older versions will continue to work on the above
operating systems, but will no longer receive updates. Platform
installers will not run on these operating systems.
The minimum
required operating system version for running MetaTrader 5 is Windows 7.
However, we strongly recommend using the 64-bit version of Windows 10.
Support for older versions of desktop and mobile terminals will end upon the release of the new platform version:
Unsupported terminal builds will not be able to connect to new server
versions. We strongly recommend that you update your terminals in
advance.
To support new shared projects, we have updated the protocol of operation with the MQL5 Storage. Therefore, you will need to perform a checkout of all data from the storage after the platform update. Data stored at the MQL5 Storage will not be lost or affected during the update.
Before updating the platform to the new version, we recommend that you perform the Commit operation to send all local changes to the MQL5 Storage.
Now, the trading platform allows creating synthetic financial instruments, i.e. symbols based on one or more existing instruments. The user should set the formula for calculating quotes, after which the platform will generate ticks of the synthetic instrument in real time, and also will create its minute history.
How It Works
For example, you can create an instrument showing the dollar index (USDX). It uses the below formula:
50.14348112 * pow(ask(EURUSD),-0.576) * pow(USDJPY,0.136) * pow(ask(GBPUSD),-0.119) * pow(USDCAD,0.091) * pow(USDSEK,0.042) * pow(USDCHF,0.036)
Note: the USDEUR and USDGBP pairs are used in the source dollar index formula. Since only reverse pairs are available in the platform, a negative power and Ask instead of Bid are used in the synthetic symbol
formula.
The platform will calculate in real time the price of the new instrument based on the quotes of the other six symbols provided by your broker. The price changes will be visualized in the Market
Watch window and on the chart:
Create a new custom symbol, open its specification and enter the formula:
For convenience, the formula editor shows a list of possible options as you type the names of symbols and functions.
Calculation of ticks and one-minute bars of a synthetic instrument starts when this instrument is added to the Market Watch. Also, all symbols required for the synthetic price calculation are automatically added to the Market Watch. An entry about the calculation start will be added to the platform journal: Synthetic Symbol USDX: processing started.
Real-Time Calculation of Quotes
Every 100 ms (i.e. ten times per second) the prices of symbols used in calculation are checked. If at least one of them has changed, the price of the synthetic symbol is calculated and a new tick is generated. Calculation is performed in parallel in three threads for Bid, Ask and Last prices. For example, if the calculation formula is EURUSD*GBPUSD, the price of the synthetic symbol will be calculated as follows:
The availability of changes is checked separately for each price. For example, if only the Bid price of a source instrument has changed, only the appropriate price of a synthetic instrument will be calculated.
Creating a History of Minute Bars
In addition to collecting ticks in real time, the platform creates a minute history of the synthetic instrument. It enables traders to view synthetic symbol charts similar to normal ones, as well as to conduct technical analysis using objects and indicators.
When a trader adds a synthetic instrument to the Market Watch, the platform checks whether its calculated minute history exists. If it does not exist, the history for the last 60 days will be created, which includes about 50,000 bars. If a lower value is specified in the 'Max. bars in chart' parameter in platform settings, the appropriate restriction will apply.
If some of bars within this period have already been create, the platform will additionally generate new bars. A deeper history is created if the user tries to view an older time period on the chart (by scrolling it back or accessing it from an MQL5 program).
The history of one-minute bars of a synthetic instrument is calculated based one one-minute bars (not ticks) of instruments used in its formula. For example, to calculate the Open price of a 1-minute bar of a synthetic symbol, the platform uses the Open prices of symbols used in its formula. High, Low and Close prices are calculated in a similar way.
If the required bar is not available for any of the instruments, the platform will use the Close price of the previous bar. For example, three instruments are used: EURUSD, USDJPY and GBPUSD. If in the calculation of a bar corresponding to 12:00 the required bar of USDJPY is not available, the following prices will be used for calculation:
If the minute bar is not available for all of the instruments used in the formula, the appropriate minute bar of the synthetic instrument will not be calculated.
Drawing New Minute Bars
All new bars (current and subsequent ones) of the synthetic instrument are created based on generated ticks. The price used for building the bars depends on the value of the Chart Mode parameter in the specification:
What Operations Can Be Used in the Symbol Formula
Price data and some properties of existing symbols provided by the broker can be used for calculating synthetic prices. Specify the following:
The following arithmetic operations can be used in the formula: addition (+), subtraction (-), multiplication (*), devision (/) and remainder of division (%). For example, EURUSD+GBPUSD means that the price is calculated as the sum of EURUSD and GBPUSD prices. Also you can use the unary minus to change the sign, for example: -10*EURUSD.
Mind the calculation priority of arithmetic operations:
You can also use in the formula all mathematical functions supported in MQL5, except for MathSrand, MathRand and MathIsValidNumber: Only short names are used for all functions, such as fabs(), acos(), asin() etc.
int CustomTicksAdd( const string symbol, // Symbol name const MqlTick& ticks[] // The array with tick data that should be applied to the custom symbol );
The CustomTicksAdd function allows feeding quotes as if these quotes were received from a broker's server. Data is sent to the Market Watch window instead of being directly written to the tick database. Then, the terminal saves ticks from the Market Watch to the database. If a large volume of data is passed in one call, the function behavior changes, in order to save resources. If more than 256 ticks are transmitted, data is divided into two parts. A larger part is recorded directly to the tick database (similar to CustomTicksReplace). The second part consisting of the last 128 ticks is sent to the Market Watch, from where the terminal saves the ticks to a database.
If a symbol chart is constructed using Bid prices (as per specification settings), Bid High and Bid Low prices are shown for this symbol. If a symbol chart is constructed using Last prices, Last High and Last Low prices are shown for this symbol.
If Market Watch contains at least one symbol whose chart is drawn based on Last prices, the Last column is automatically enabled in addition to High/Low.
Full-featured projects are now available in MetaEditor. The program development process has become more convenient.
Now the main MQ5 program file does not appear as the project. The project is a separate "MQPROJ" file, which stores program settings, compilation parameters and information about all used files. Main project settings can be accessed from a separate dialog box, so there is no need to specify them in the source code via #property now.
A separate tab in the Navigator is provided for work convenience within the project. All files, such as include, resource, header and other files are arranged into categories on this tab. All files are automatically added to the project navigator. For example, if you include a new MQH file, it will automatically appear in the "Dependencies" section of the navigator.
Support for new projects has also been implemented in the updated MQL5 Storage online repository. Now, it has become much more convenient to develop large projects through collaboration with other members of the MQL5.community.
New Shared Projects section is provided for group projects. A project created in this section is immediately sent to the storage: you can grant permissions to other users and start collaboration right away.
When you compile a project in Shared Projects, an executable EX5 file is automatically copied to the local Experts, Indicators or Scripts directory depending on the program type. You can easily launch the program on a chart without having to copy files manually.
What's New in the MQL5 Storage Operation
To implement support for new shared projects, we have modified the protocol of operation with the MQL5 Storage. Therefore, you will need to perform a checkout of all data from the storage after the platform update. Data stored at the MQL5 storage will not be lost or affected during the update.
The 'Checkout from Storage' command is unavailable now. Instead, the 'Activate MQL5 Storage' and 'Update from Storage' commands are used to receive data:
New Projects: Examples of Creation and Operation Details
A new project entity has been added in MetaEditor. A project is an mqproj file that stores common program properties and information about all used files. Now, program properties can be conveniently managed from a separate MetaEditor dialog instead of manual modification of properties in the source code (using #property directives).
If you have available code, you can easily test new projects by using the 'New Project from Source' command.
In the directory where the selected file is located, a new project file with the same name and the mqproj extension will be created. The main program properties specified in the source code via #property will be automatically added to the project, including the name, copyright, version, link to the developer's site and program description.
Two new options for compiling MQL5 programs have been added to project properties:
To work with projects, use a separate Project tab in the Navigator window. All files used in a project are displayed on this tab in a convenient form. When a project is generated from a source file, all used include files (specified using the #include directory in the main MQ5 file and in its include files) are automatically added to the Dependencies section.
When a new include file is added to the source code, it also appears in the project Navigator. Used header files are added to the Headers section; images, sounds and other MQL5 programs used in the project as resource are added to the Resources section. MQ5 files with the source code are displayed in the Sources section. In the 'Settings and files' section, you can add other files, such as set files for testing and chart templates.
Use context menu commands to add existing files to a project or to delete files from it. Be careful when deleting files, since you can remove a file from the project (remove the binding) or completely delete it from the hard disk:
Creation of a new project is as easy as the creation of a normal MQL5 program. Click 'New Project', select the type of new program and specify properties (such as name, event handlers, etc) in the MQL5 Wizard.
To obtain an executable EX5 file, you can open the project and press F7 (the compilation command) or open the main MQ5 file of the program and compile it.
Shared Projects in MQL5 Storage: Operation Details
Shared projects are managed from a separate Shared Projects section. If you have not connected the storage yet, execute the 'Activate MQL5 Storage' command from the context menu of the desired folder. MetaEditor will check if your storage contains any saved data and if there are any share projects available to you. All available data will be retrieved from the storage and uploaded to your computer (the checkout operation). Available group projects appear in the Shared Projects section. To retrieve the projects, execute "Checkout from Storage" in the context menu.
To create a new group project, select the Shared Projects folder and click "New Project":
Then complete standard MQL5 steps: set the type, name and properties of the desired program. For group projects, you should use clear and understandable names, so that other participants could easily find them. Only Latin letters and numbers without spaces can be used in project names.
A created object is immediately added to the MQL5 Storage. Standard Library files used in the project are not added to the storage, and you can add them manually.
To allow other participants to work with the project, open its properties. From here you can grant permissions to selected users by specifying their MQL5.community login, as well as set common parameters for the group work:
When you compile a group project, the executable EX5 file is automatically copied to the local Experts, Indicators or Scripts directory depending on the program type. It allows you to instantly run
the program in the terminal without having to copy it manually to the proper directory.
Public Projects in MQL5 Storage: Participation in Development
As mentioned above, each group project in MQL5 Storage has publicity settings: the project can be private or open to other users. Now, all projects you can freely join are displayed in the separate "Public Projects" tab.
Everyone can find an exciting project and take part in its development. Simply click Join and receive the project from the storage.
Each joined user gets read-only rights. Contact the project author to be able to submit your changes. To know his or her login, open the project properties via the context menu.
Added the ability to easily insert properties and resources to program code. For example, you can quickly add an included file to code. Use command "Insert—MQH as #incude", and select the desired include file. The #include directive with the proper path to the selected file will be inserted to program code.
The same menu allows adding to program code files in the form of a binary or text array. Among others, you can transfer chart templates with Expert Advisors or indicators: insert your template in the program code as an array, and save it to disk then using the FileSave function. After that the template can be applied on the desired chart right from an Expert Advisor using the ChartApplyTemplate function.
//+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- Template file as a binary array unsigned char my_template[]= { 0xFF,0xFE,0x3C, ... ,0x00 // The data array in this example is shortened }; //--- Saving and applying the template if(FileSave("my_template.tpl",my_template)) { Print("Custom template saved in \\MQL5\\Files"); if(ChartApplyTemplate(0,"\\Files\\my_template.tpl")) Print("Custom template applied to the current chart"); else Print("Failed to apply custom template"); } else Print("Failed to save custom template"); }
Function | Action |
---|---|
CustomSymbolCreate | Create a custom symbol with the specified name in the specified group |
CustomSymbolDelete | Delete a custom symbol with the specified name |
CustomSymbolSetInteger | Set the integer type property value for a custom symbol |
CustomSymbolSetDouble | Set the real type property value for a custom symbol |
CustomSymbolSetString | Set the string type property value for a custom symbol |
CustomSymbolSetMarginRate | Set the margin rates depending on the order type and direction for a custom symbol |
CustomSymbolSetSessionQuote | Set the start and end time of the specified quotation session for the specified symbol and week day |
CustomSymbolSetSessionTrade | Set the start and end time of the specified trading session for the specified symbol and week day |
CustomRatesDelete | Delete all bars from the price history of the custom symbol in the specified time interval |
CustomRatesReplace | Fully replace the price history of the custom symbol within the specified time interval with the data from the MqlRates type array |
CustomRatesUpdate | Add missing bars to the custom symbol history and replace existing data with the ones from the MqlRates type array |
CustomTicksAdd | Adds data from an array of the MqlTick type to the price history of a custom symbol. The custom symbol must be selected in the Market Watch window. |
CustomTicksDelete | Delete all ticks from the price history of the custom symbol in the specified time interval |
CustomTicksReplace | Fully replace the price history of the custom symbol within the specified time interval with the data from the MqlTick type array |
Added Generic Data Collections to the Standard Library. They contain classes and interfaces for defining collections based on templates. The new strongly typed collections provide a greater application development convenience and high data handling performance.
The library is placed to the Include\Generic folder of the terminal's working directory.
bool ArraySwap( void& array1[], // The first array void& array2[] // The second array );The function accepts dynamic arrays of the same type and the same dimensions. For multidimensional arrays, the number of elements in all dimensions except the first one should match.
union LongDouble { long long_value; double double_value; };Unlike the structure, various union members belong to the same memory area. In this example, the union of LongDouble is declared with long and double type values sharing the same memory area. Please note that it is impossible to make the union store a long integer value and a double real value simultaneously (unlike a structure), since long_value and double_value variables overlap (in memory). On the other hand, an MQL5 program is able to process data containing in the union as an integer (long) or real (double) value at any time. Therefore, the union allows receiving two (or more) options for representing the same data sequence.
union LongDouble { long long_value; double double_value; }; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- LongDouble lb; //--- get and display the invalid -nan(ind) number lb.double_value=MathArcsin(2.0); printf("1. double=%f integer=%I64X",lb.double_value,lb.long_value); //--- largest normalized value (DBL_MAX) lb.long_value=0x7FEFFFFFFFFFFFFF; printf("2. double=%.16e integer=%I64X",lb.double_value,lb.long_value); //--- smallest positive normalized (DBL_MIN) lb.long_value=0x0010000000000000; printf("3. double=%.16e integer=%.16I64X",lb.double_value,lb.long_value); } /* Execution result 1. double=-nan(ind) integer=FFF8000000000000 2. double=1.7976931348623157e+308 integer=7FEFFFFFFFFFFFFF 3. double=2.2250738585072014e-308 integer=0010000000000000 */
class Foo { int value; public: string Description(void){return IntegerToString(value);}; //--- default constructor Foo(void){value=-1;}; //--- parameterized constructor Foo(int v){value=v;}; }; //+------------------------------------------------------------------+ //| structure containing Foo type objects | //+------------------------------------------------------------------+ struct MyStruct { string s; Foo foo; }; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- MyStruct a,b; Foo an_foo(5); a.s="test"; a.foo=an_foo; Print("a.s=",a.s," a.foo.Description()=",a.foo.Description()); Print("b.s=",b.s," b.foo.Description()=",b.foo.Description()); //--- Print("b=a"); b=a; //--- Print("a.s=",a.s," a.foo.Description()=",a.foo.Description()); Print("b.s=",b.s," b.foo.Description()=",b.foo.Description()); /* Execution result; a.s=test a.foo.Description()=5 b.s= b.foo.Description()=-1 b=a a.s=test a.foo.Description()=5 b.s=test b.foo.Description()=5 */ }Memberwise copying of objects is performed in the implicit operator.
ENUM_POSITION_REASON | ENUM_DEAL_REASON | ENUM_ORDER_REASON | Reason description |
---|---|---|---|
POSITION_REASON_CLIENT | DEAL_REASON_CLIENT | ORDER_REASON_CLIENT | The operation was executed as a result of activation of an order placed from a desktop terminal |
POSITION_REASON_MOBILE | DEAL_REASON_MOBILE | ORDER_REASON_MOBILE | The operation was executed as a result of activation of an order placed from a mobile application |
POSITION_REASON_WEB | DEAL_REASON_WEB | ORDER_REASON_WEB | The operation was executed as a result of activation of an order placed from the web platform |
POSITION_REASON_EXPERT | DEAL_REASON_EXPERT | ORDER_REASON_EXPERT | The operation was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script |
- | DEAL_REASON_SL | ORDER_REASON_SL | The operation was executed as a result of Stop Loss activation |
- | DEAL_REASON_TP | ORDER_REASON_TP | The operation was executed as a result of Take Profit activation |
- | DEAL_REASON_SO | ORDER_REASON_SO | The operation was executed as a result of the Stop Out event |
- | DEAL_REASON_ROLLOVER | - | The deal was executed due to a rollover |
- | DEAL_REASON_VMARGIN | - | The deal was executed after charging the variation margin |
- | DEAL_REASON_SPLIT | - | The deal was executed after the split (price reduction) of a stock or another asset, which had an open position during split announcement |
Updated documentation.
//+------------------------------------------------------------------+ //| Template function | //+------------------------------------------------------------------+ template<typename T1,typename T2> string Assign(T1 &var1,T2 var2) { var1=(T1)var2; return(__FUNCSIG__); } //+------------------------------------------------------------------+ //| Special overload for bool+string | //+------------------------------------------------------------------+ string Assign(bool &var1,string var2) { var1=(StringCompare(var2,"true",false) || StringToInteger(var2)!=0); return(__FUNCSIG__); } //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { int i; bool b; Print(Assign(i,"test")); Print(Assign(b,"test")); }As a result of the code execution, we can see that the Assign() template function has been used for the int+string pair, while the overloaded version has already been used for the bool+string pair during the second call.
string Assign<int,string>(int&,string) string Assign(bool&,string)
template<typename T> T Func() { return (T)0; } void OnInit() { Func<double>(); // explicit template function specialization }Thus, typification is performed by explicit specification of types rather than via the call parameters.
Updated documentation.
Updated documentation.
#resource path_to_resource_file as type_of_resource_variable name_of_resource_variable
#resource "data.bin" as int ExtData[] // declaring the numeric array containing data from the data.bin file #resource "data.bin" as MqlRates ExtData[] // declaring the simple structures array containing data from the data.bin file #resource "data.txt" as string ExtCode // declaring the string containing the data.txt file data #resource "data.txt" as string ExtCode[] // declaring the string array containing the data.txt file data #resource "image.bmp" as bitmap ExtBitmap[] // declaring the one-dimensional array containing a bitmap from the BMP file, array size = width * height #resource "image.bmp" as bitmap ExtBitmap2[][] // declaring the two-dimensional array containing a bitmap from the BMP file, array size [hight][width]
Updated documentation.
string str; ... if(str) // will result in "Cannot convert type 'string' to 'bool'" compilation error (no error would appear in the previous versions) Print("str is true");One should use an explicit condition:
string str; ... //--- check if the string is initialized if(str!=NULL) Print("str is true"); or //--- check if the string value is "true" if(StringCompare(str,"true",false)) Print("str is true"); or //--- check if the string is integer and is not equal to zero if((int)str!=0) Print("str is true");
Fixed errors reported in crash logs.
void ArrayPrint( const void& array[], // Printed array uint digits=_Digits, // The number of decimal places const string separator=NULL, // A separator between the values of the structure fields ulong start=0, // The index of the first displayed element ulong count=WHOLE_ARRAY, // The number of displayed elements ulong flags=ARRAYPRINT_HEADER|ARRAYPRINT_INDEX|ARRAYPRINT_LIMIT|ARRAYPRINT_ALIGN );ArrayPrint does not print all fields of a structure array to logs – array fields and pointer fields of objects are skipped. If you want to print all fields of a structure, you should use a custom function for the mass printing with a desired formatting.
//--- Prints the values of the last 10 bars MqlRates rates[]; if(CopyRates(_Symbol,_Period,1,10,rates)) { ArrayPrint(rates); Print("Проверка\n[time]\t[open]\t[high]\t[low]\t[close]\t[tick_volume]\t[spread]\t[real_volume]"); for(int i=0;i<10;i++) { PrintFormat("[%d]\t%s\t%G\t%G\t%G\t%G\t%G\t%G\t%I64d\t",i, TimeToString(rates[i].time,TIME_DATE|TIME_MINUTES|TIME_SECONDS), rates[i].open,rates[i].high,rates[i].low,rates[i].close, rates[i].tick_volume,rates[i].spread,rates[i].real_volume); } } else PrintFormat("CopyRates failed, error code=%d",GetLastError()); //--- A log example /* [time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume] [0] 2016.11.09 04:00:00 1.11242 1.12314 1.11187 1.12295 18110 10 17300175000 [1] 2016.11.09 05:00:00 1.12296 1.12825 1.11930 1.12747 17829 9 15632176000 [2] 2016.11.09 06:00:00 1.12747 1.12991 1.12586 1.12744 13458 10 9593492000 [3] 2016.11.09 07:00:00 1.12743 1.12763 1.11988 1.12194 15362 9 12352245000 [4] 2016.11.09 08:00:00 1.12194 1.12262 1.11058 1.11172 16833 9 12961333000 [5] 2016.11.09 09:00:00 1.11173 1.11348 1.10803 1.11052 15933 8 10720384000 [6] 2016.11.09 10:00:00 1.11052 1.11065 1.10289 1.10528 11888 9 8084811000 [7] 2016.11.09 11:00:00 1.10512 1.11041 1.10472 1.10915 7284 10 5087113000 [8] 2016.11.09 12:00:00 1.10915 1.11079 1.10892 1.10904 8710 9 6769629000 [9] 2016.11.09 13:00:00 1.10904 1.10913 1.10223 1.10263 8956 7 7192138000 Check [time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume] [0] 2016.11.09 04:00:00 1.11242 1.12314 1.11187 1.12295 18110 10 17300175000 [1] 2016.11.09 05:00:00 1.12296 1.12825 1.1193 1.12747 17829 9 15632176000 [2] 2016.11.09 06:00:00 1.12747 1.12991 1.12586 1.12744 13458 10 9593492000 [3] 2016.11.09 07:00:00 1.12743 1.12763 1.11988 1.12194 15362 9 12352245000 [4] 2016.11.09 08:00:00 1.12194 1.12262 1.11058 1.11172 16833 9 12961333000 [5] 2016.11.09 09:00:00 1.11173 1.11348 1.10803 1.11052 15933 8 10720384000 [6] 2016.11.09 10:00:00 1.11052 1.11065 1.10289 1.10528 11888 9 8084811000 [7] 2016.11.09 11:00:00 1.10512 1.11041 1.10472 1.10915 7284 10 5087113000 [8] 2016.11.09 12:00:00 1.10915 1.11079 1.10892 1.10904 8710 9 6769629000 [9] 2016.11.09 13:00:00 1.10904 1.10913 1.10223 1.10263 8956 7 7192138000 */
void OnStart() { int arr[]; //--- Amount of memory initially used Print("Array size:",ArraySize(arr)," Memory used:",MQLInfoInteger(MQL_MEMORY_USED)," MB"); //--- Amount of memory used for the array of size 1, with a reserve ArrayResize(arr,1,1024*1024); Print("Array size:",ArraySize(arr)," Memory used:",MQLInfoInteger(MQL_MEMORY_USED)," MB"); //--- After the increase of the array, the amount of memory used will not change due to the reserve ArrayResize(arr,1024*512,1024*1024); Print("Array size:",ArraySize(arr)," Memory used:",MQLInfoInteger(MQL_MEMORY_USED)," MB"); //--- After reducing the array, the memory size will not change either ArrayResize(arr,1); Print("Array size:",ArraySize(arr)," Memory used:",MQLInfoInteger(MQL_MEMORY_USED)," MB"); //--- Unused memory will be released after the removal of the reserve ArrayResize(arr,1,-1); Print("Array size:",ArraySize(arr)," Memory used:",MQLInfoInteger(MQL_MEMORY_USED)," MB"); }
#include <Graphics/Graphic.mqh> double Func1(double x) { return MathPow(x,2); } double Func2(double x) { return MathPow(x,3); } double Func3(double x) { return MathPow(x,4); } void OnStart() { GraphPlot(Func1,Func2,Func3,-2,2,0.05,CURVE_LINES); }The result:
#include <Math/Stat/Binomial.mqh> #include <Graphics/Graphic.mqh> void OnStart(void) { double vars[101]; double results[101]; const int N=2000; //--- MathSequence(0,N,20,vars); MathProbabilityDensityBinomial(vars,N,M_PI/10,true,results); ArrayPrint(results,4); GraphPlot(results); //--- }The result:
Updated documentation.
Added tooltips for the Buy, Sell and Close buttons in trade dialogs. The tooltips contain information about the security to be bought or sold during the operation, to help beginners understand the trading process.
An MQL5 version of the ALGLIB numerical analysis library has been included into the Standard Library.
Library Features
How to Use
ALGLIB files are located in \MQL5\Include\Math\Alglib. To use the functions, add the main library file into your program:
Mathematical statistics functions have been included into the Standard Library. MQL5 now provides the functionality of the R language, which is one of the best tools for statistical data processing and analysis.
Library Features
The statistical library contains functions for calculating the statistical characteristics of data, as well as functions for operations with statistical distributions:
How to Use
The statistical library files are located in \MQL5\Include\Math\Stat. To use the library, add the file with required functions into your program, for example:
#include <Math\Stat\Binomal.mqh> #include <Math\Stat\Cauchy.mqh>
The detailed description of the library functions is available in the article Statistical Distributions in MQL5 - Taking the Best of R.
The MQL5 version of the Fuzzy library has been included into the Standard Library. The Fuzzy library implements Mamdani and Sugeno fuzzy inference systems.
Library Features
How to Use
Fuzzy Library files are located in \MQL5\Include\Math\Fuzzy. To use the library, add the file with required functions into your program, for example:
#include <Math\Fuzzy\mamdanifuzzysystem.mqh> #include <Math\Fuzzy\sugenofuzzysystem.mqh>
A detailed description of the library is available in the Code Base: Fuzzy - library for developing fuzzy models
long FileLoad( const string filename, // [in] File name void &buffer[], // [out] An array to which the file is read uint common_flag=0 // [in] 0 - search for the file in the Files folder of the terminal, FILE_COMMON - search in the common directory of terminals ); bool FileSave( const string filename, // [in] File name const void &buffer[], // [in] An array to which the file is saved uint common_flag=0 // [in] 0 - create a file in the Files folder of the terminal, FILE_COMMON - create in the common directory of terminals );An example of how to write ticks to a file and then read them:
//--- input parameters input int ticks_to_save=1000; // Number of ticks //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { string filename=_Symbol+"_ticks.bin"; MqlTick ticks[]; //--- int copied=CopyTicks(_Symbol,ticks,COPY_TICKS_ALL,0,ticks_to_save); if(copied!=-1) { PrintFormat(" CopyTicks(%s) copied %d ticks",_Symbol,copied); //--- If the tick history is synchronized, the error code is equal to zero if(!GetLastError()==0) PrintFormat("%s: Ticks are not synchronized. Error=",_Symbol,copied,_LastError); //--- Writing ticks to a file if(!FileSave(filename,ticks,FILE_COMMON)) PrintFormat("FileSave() failed, error=%d",GetLastError()); } else PrintFormat("Failed CopyTicks(%s), Error=",_Symbol,GetLastError()); //--- Now reading the ticks back to the file ArrayFree(ticks); long count=FileLoad(filename,ticks,FILE_COMMON); if(count!=-1) { Print("Time\tBid\tAsk\tLast\tVolume\tms\tflags"); for(int i=0;i<count;i++) { PrintFormat("%s.%03I64u:\t%G\t%G\t%G\t%I64u\t0x%04x", TimeToString(ticks[i].time,TIME_DATE|TIME_SECONDS),ticks[i].time_msc%1000, ticks[i].bid,ticks[i].ask,ticks[i].last,ticks[i].volume,ticks[i].flags); } } }
//--- Candlesticks painted in the same color #property indicator_label1 "One color candles" #property indicator_type1 DRAW_CANDLES //--- Only one color is specified, so all candlesticks are the same color #property indicator_color1 clrGreenIf two colors are specified, one color is used for candlestick edges, the other one is used for the body.
//--- The color of the candlesticks differs from the color of shadows #property indicator_label1 "Two color candles" #property indicator_type1 DRAW_CANDLES //--- Candlestick edges and shadows are green, body is white #property indicator_color1 clrGreen,clrWhiteIf three colors are specified, one color is used for candlestick edges, two other colors are used for the bodies of bullish and bearish candlesticks.
//--- The color of the candlesticks differs from the color of shadows #property indicator_label1 "One color candles" #property indicator_type1 DRAW_CANDLES //--- Candlestick edges and shadows are green, the body of a bullish candle is white, the body of a bearish candle is red #property indicator_color1 clrGreen,clrWhite,clrRedThe DRAW_CANDLES style allows setting custom colors of candlesticks. All colors can also be changed dynamically while the indicator is running, using the function PlotIndexSetInteger(drawing_index_DRAW_CANDLES, PLOT_LINE_COLOR, modifier_number, color) where modifier_number can have the following values:
//--- Setting the color of edges and shadows PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrBlue); //--- Setting the color of the bullish candlestick body PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrGreen); //--- Setting the color of the bearish candlestick body PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrRed);
Updated documentation.
class CFoo final { //--- class body }; class CBar : public CFoo { //--- class body };When attempting to inherit from a class with the 'final' modifier as shown above, the compiler displays an error:
class CFoo { void virtual func(int x) const { } };The method is overridden in the inherited class:
class CBar : public CFoo { void func(short x) { } };But the argument type is mistakenly changed from 'int' to 'short'. In fact, the method overload instead of overriding is performed in that case. While acting according to the overloaded function definition algorithm, the compiler may in some cases select a method defined in the base class instead of an overridden one.
class CBar : public CFoo { void func(short x) override { } };If the method signature is changed during the overriding process, the compiler cannot find the method with the same signature in the parent class issuing the compilation error:
class CFoo { void virtual func(int x) final { } }; class CBar : public CFoo { void func(int) { } };When attempting to override a method with the 'final' modifier as shown above, the compiler displays an error:
Updated documentation.
class CFoo { }; class CBar { }; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { void *vptr[2]; vptr[0]=new CFoo(); vptr[1]=new CBar(); //--- for(int i=0;i<ArraySize(vptr);i++) { if(dynamic_cast<CFoo *>(vptr[i])!=NULL) Print("CFoo * object at index ",i); if(dynamic_cast<CBar *>(vptr[i])!=NULL) Print("CBar * object at index ",i); } CFoo *fptr=vptr[1]; // Will return an error while casting pointers, vptr[1] is not an object of CFoo } //+------------------------------------------------------------------+
string text="Hello"; ushort symb=text[0]; // Will return the code of symbol 'H'
Updated documentation.