Showing posts with label mql4. Show all posts
Showing posts with label mql4. Show all posts

Example programming: mql4 vs mql5

MQL5 is the development of its predecessor - the MQL4 language, in which numerous indicators, scripts, and Expert Advisors were written. Despite the fact that the new programming language is maximally compatible with the previous-generation language, there are still some differences between these languages. And when transferring programs these differences should be noted.
This section contains information intended to facilitate the adaptation of codes to the new MQL5 language for programmers who know MQL4.
First it should be noted:
  • The new language does not contain functions start(), init() and deinit();
  • The number of indicator buffers is not limited;
  • dll is downloaded immediately after downloading an Expert Advisor (or any other mql5 program);
  • Check of logical conditions is shortened;
  • When limits of an array are exceeded, the current performance is terminated (critically - with the output of an errors);
  • Precedence of operators like in C + +;
  • The language offers the implicit type cast (even from string to a number);
  • Local variables are not initialized automatically (except for strings);
  • Common local arrays are automatically deleted.

Special Functions init, start and deinit

The MQL4 language contained only three predefined functions that could be used in the indicator, script or Expert Advisor (not taking into account the include files *.mqh and library files). In MQL5 there are no such functions, but there are their analogues. The table shows the approximate correspondence of functions.
MQL4
MQL5
init
OnInit
start
OnStart
deinit
OnDeinit
Functions OnInit and OnDeinit perform the same role as init and deinit in MQL4 - they are designed to locate the code, which must be performed during initialization and deinitialization of mql5 programs. You can either just rename these functions accordingly, or leave them as they are, but add calls of these functions in corresponding places.
Example:
void OnInit()
  {
//--- Functions is called to initialize
   init();
  }
void OnDeinit(const int reason)
  {
//--- Call the function with deinitialization
   deinit();
//---
  }
The start function is replaced by OnStart only in scripts. In Expert Advisors and indicators it should be renamed to OnTick and OnCalculate, respectively. The code that is to be executed during a mql5 program operation should be located in these three functions:
mql5-program
main function
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
MQL5
Digits
_Digits
Point
_Point

_LastError

_Period

_Symbol

_StopFlag

_UninitReason

Access to Timeseries

In MQL5 there are no such predefined timeseries as Open [], High [], Low [], Close [], Volume [] and Time []. The necessary depth of a timeseries can now be set using corresponding functions to access timeseries.

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:
  • 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.

Programming of mql4 vs mql5

The MetaQuotes folks brang a lot of improvements to the new language MQL5 vs the old MQL4.

Data types
They added the enum data type to the base data types and also made a more precise definition of the integer types. In this way, they added:
char , short , long , uchar , ushort , uint , ulong
This time the structures appear too:
struct, class

Operators
The introduction of the operators new si delete which are used for the creation and destruction of objects. These two operators apply to object-oriented programming.

Events
These are functions that execute when an event happens:
OnStart(), OnInit(), OnDeinit(), OnTick(), OnTimer(), OnTrade(), OnBookEvent(), OnChartEvent().
We can mention new event types:
- OnTimer() : The function is called when a timer event is triggered, which is set up by EventSetTimer();
- OnTrade() : The function is called whenever the list of orders or position changes ; that means it is called whenever an order is posted or gets executed;
- OnBookEvent() : Function is called whenever the price change for any symbol registered by MarketBookAdd() si-a schimbat pretul. In a way it is a generalized form of OnTick().
- OnChartEvent() : Function is called whenever the chart receives an event, be it given by the keyboard, mouse, or moving a graphics object by mouse.

Notes:
OnInit() basically takes over from MQL4’s init();
OnStart() reduces from the role that start() had in MQL4, remaining as main block for scripts;
OnTick() takes over the role as incoming tick event, from the start() function from MQL4;
OnDeinit() takes over old MQL4’s deinit();


Object Oriented Programming
One of the novelties of MQL5 is the Object Oriented Programming, which makes code to be easier to write, read and use. The basic OOP features are : encapsulation, inheritance, polymorphism, function overload and virtual functions.

New graphics objects
MetaQuotes comes with new graphics elements .Below is the list with the new graphics objects featured by MQL5:
OBJ_ELLIOTWAVE5 , OBJ_ELLIOTWAVE3 , OBJ_ARROW_THUMB_UP , OBJ_ARROW_THUMB_DOWN,
OBJ_ARROW_UP , OBJ_ARROW_DOWN , OBJ_ARROW_STOP , OBJ_ARROW_CHECK ,OBJ_ARROW_LEFT_PRICE,
OBJ_ARROW_RIGHT_PRICE ,OBJ_BUTTON , OBJ_CHART , OBJ_BITMAP , OBJ_BITMAP_LABEL , OBJ_EDIT.
Our opinion would be that OBJ_EDIT,OBJ_BUTTON si OBJ_CHART are the most important graphics objects. Once with OBJ_CHART comes the possibility to have chart in chart feature (to see inside a chart a different other charts). These objects are fully packed with properties, which leads to a better graphics object management.

Special variables for debugging
To simplify debugging four variables have been introduced : __LINE__ , __FILE__ ,__FUNCTION__ , __MQL5BUILD__  , which can be used to log info about current line, file , function or the MQL5 build ; these come handy in debugging as there were no such infos in MQL4 and possible errors that were generated by functions were traceable with extra logging and considerable programming effort.

The position based system that replaces the order based system
This is an MT5 feature rather than a MQL5 feature. However, since it changes the trading activity, it leaves marks over MQL5. The order selection mechanism is modified, and also a new position selection mechanism has been added

Symbol enumeration
With functions SymbolSelect() and SymbolTotal() can be made easily the list of all symbols offered by broker. Even more, with SymbolInfoInteger() a lot of symbol information can be retrieved, including the profit calculus and the margin calculus mode that tells about the symbol nature.
This existed also in MQL4’s MarketInfo(), however the symbol list was not retrievable. The symbol nature information, combined with the list, is a powerful tool in knowing which symbols are forex, which are futures, stocks or stock exchange indexes. This will have implications later in retrieving option chains by knowing the underlying.

A new way of reading/writing properties
The functions working with properties are now divided on data types, according to the data type they work with.
For instance MQL4’s MarketInfo() is now divided in SymbolInfoInteger(), SymbolInfoDouble(), SymbolInfoString() ; also SymbolInfoTick() for current prices;
The functions working with the account, which were one per solicited element in MQL4, are organized in a similar manner: AccountInfoInteger(), AccountInfoDouble(), AccountInfoString() (there were 16 account functions in MQL4, for comparison);
For the running program, MQL5InfoInteger(), MQL5InfoString() (similar functions were not existant in MQL4);
For data series : SeriesInfoInteger();
For charts : ChartGetDouble(), ChartGetInteger(),ChartGetString() , with their writing complements ChartSetDouble(), ChartSetString(), ChartSetSymbolPeriod() , near a series of functions inherited from MQL4’s window functions;
For indicators : IndicatorSetDouble(), IndicatorSetInteger(), IndicatorSetString();
To establish indicator plotting parameters: PlotIndexGetInteger(), PlotIndexSetDouble(), PlotIndexSetInteger(), PlotIndexSetString;
For graphics objects : ObjectGetDouble(), ObjectGetInteger(), ObjectGetString() , also the newer ObjectGetTimeByValue(), ObjectGetValueByTime ; also for writing : ObjectSetDouble(), ObjectSetInteger(), ObjectSetString().

A new way to address data series
Gone are functions like iHigh(), iHighest(), iLow(), iLowest(), iOpen(), iClose(), iBars(), iBarShift() from MQL4.
I said that appeared the function SeriesInfoInteger(). But this one returns only general properties.
To return data from data series now the function being used is CopyRates().

Un new way to construct and address indicators
This subject is too complicated for the present article. However, all indicators, including custom indicators, have the addressing manner changed. This time, functions don’t return values anymore, but handlers. It is recommendable that a new handler to be created for every indicator called with some parameters, one time. Then data can be extracted , datele pot fi extrase, pentru orice bara, cu ajutorul functiei CopyBuffer() , that can use same handler over and over again.
Sure we can’t cover in an article all the new relevant stuff brought by MQL5.
But these will appear in time, with the development of trading strategies written in MQL5.