Thursday, March 19, 2009

MQL 4: Library functions and their use in programs

After a public beta version of the premiere MetaTrader 4 has passed not so much time, but thanks to the active forum to discuss the company MetaQuotes Software advantages and disadvantages of the terminal, the developers, while listening to the opinion buduyuschih users have made some changes in the user interface programs, and software interface MQL-executable program environment. Thus, in one of the most recent builds of the program were abolished Synonyms arrays to Open, Low, High, Close, Time and Volume.



In this regard, please note that these six arrays are not synonyms, abbreviations are mentioned in the preceding article. Now the use of the array O is not equivalent to the use of Open, L - is not equivalent to Low, H - is not equivalent to High, C - is not equivalent to Close, T - is not equivalent to Time, and V - is not equivalent to Volume, respectively. Thus, programs written using such reductions would have to slightly correct. According to the developers that was done to avoid confusion. Trust intuition development, and go on. Another point I would like to make in connection with one inaccuracy, permitted the author in the article "Programming language MQL 4: Implementation of programs, types and structure, published in the 48 th issue of the journal Forex Magazine.



The article claimed that the program type advisor has exclusive opportunity - at that time to commit the transaction. Such a possibility is lacking in other types of custom programs. In fact, it is available even from one version of MQL-programs - from custom scripts.



Today, correcting inaccurate approved, we will create a script is a bargain. We believe that it is not necessary to explain the readers how the opening of market orders in MetaTrader. Those who have not yet had that experience, can train, because each of the terminal can be downloaded from the server to register for a demonstration account. Demo account is largely similar to the real and can help beginners to try their strength in the financial markets. Often, especially for novice traders, it can take quite a long time. Ability to quickly open the market order can be evaluated dostoinsivu those trades on the news, skalperami and other intradey traders. This article is an example of the script almost instantly displayed market order to buy. One of the benefits of opening market orders with the help of a script is that the computation of parameters of order-type "stop loss", "take profit" and the size of open positions can be assigned to MQL-program. Particularly useful such an opportunity may be in the fast movements of the market, where each second of delay may be very expensive in the literal sense of the word. However, the script now for us, both for students MQL 4, will be of interest so that his example would be to consider the creation and use of library functions.



Let's begin with a description of the algorithm of the script:

. determine the degree of risk, ie the percentage of free deposit, which we agree to donate in the event of an unsuccessful outcome for us of developments in the market;

. ascertain the level at which you need to put "stop loss" in this situation;

. determine the level of "take profit";

. calculate the value of the lot to meet the risk and size of "stop loss";

. try to perform the market order with previous parameters.



In order to calculate the value of the lot to open in order to use functions MMGetLotsCount. It's not the case would be if we built the implementation of this feature in the same file that contains the script code. But this could well be that the same function in the future will require us to write an expert. If you do not use any features, the expert uses the same algorithm for calculating the size of the lot would have to do the same again, inside the implementation of this function in the same file that contains a code expert. Imagine a situation where you have reviewed and at least partially modified method of calculating the amount of open positions. All MQL-programs that use the old method of calculation must be corrected and recompile. If the code of this function should be corrected in three or four places, it is not big problem, you can do it fast enough, but worse when it turns out that it was used in the twenty programs - the time spent on changing all the programs can be very palpable. But this is not the worst, it may happen that one or more programs, the code for any reason you do not accidentally be updated. Then the real nightmare begins for MQL-user of such programs, as well as some of them would be to calculate the size of the lot one way and the rest - quite differently.



To avoid these complications in MQL 4 programmers to create libraries of functions. In this article we will create a library of functions MMlib (Money Management Library), consisting only of a single function MMGetLotsCount. Later in MMlib can add other functions for the calculation of certain indicators of money management.



Library of functions is a compiled module consisting of functions written in MQL 4. Let us explain the sequence of steps that should be implemented to create a library MMlib:



. in the folder you want expertslibraries Create file mmlib.mq4, containing the title of the comments, what is any other MQL-program;

. followed by the title, add the feature module library:



# property library



MQL4 language compiler is smart enough and do not include in the compiled module functions that are not caused anywhere within the module. Properties module "library" guarantees that all unused, but sold in the source code of the function module will fall into the compiled module.



. put the implementation of functions that after its compilation in the library can be imported into its program.

. Create a folder expertsincludes file mmlib.mqh, containing the title of the comments, this is what any other MQL-program;

. followed by the title, add an instruction importing compiled library MMlib:

. continue to file mmlib.mqh added the definition of the function MMGetLotsCount, the same as it was in mmlib.mq4, but without the body functions.



At the establishment of a library containing a single function MMGetLotsCount completed. If this library would need to add more functions, their ads will need to write to a file MMlib.mqh, and implementation of these functions to write to MMlib.mq4. Now, recompile the module, we get MMlib.ex4 library containing the function MMGetLotsCount and just add a function.



Similarly, you can create your own library, containing your own functions. In addition, the use of libraries of functions helps to solve the problems described above, another of the advantages of creating libraries of functions is that they can be distributed in the form of compiled modules, accompanied. Mqh files. Thus, it is possible to observe intellectual property rights. Another of the advantages of creating libraries of functions is that if you do not change the settings for call functions, they can be modified irrespective of the use of their programs. For example, if you find that one of the library functions of a mistake, you can fix and recompile only the module containing the corrected function, using it to recompile the program is not required.



Use the library in your program, you can include in your code. Mqh-file, the appropriate library. Such files are commonly referred to as the header files, and. Mq4-file library name of the file implementation. With the implementation of files we deal only in the phase of the library, ie at the stage of creation. Ex4-file. Thus, the use of "hidden" in the library of the functions normally carried out with the help of including in its header file corresponding to the library, using the instruction # include. For explanation of the characteristics of these instructions advise you to refer to directory language MQL 4 from MeatQuotes Software. Here is a code for all three files, which illustrates the above. It should be remembered that the code is recommended to consider only as an example of the implementation of library functions and using his script and did not try to use it to get a real return on fininsovyh markets. Also, given the code, thanks to the abundance of comments, is easy to understand and can serve as the starting point for creating a version of the script with the desired functionality.



The contents of the file mmlib.mq4



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

/ / | Mmlib.mq4 |

/ / | Copyright c 2004, Alexander Ivanov. |

/ / | Alexander@indus.ru |

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

# property copyright "Copyright c 2004, Alexander Ivanov."

# property link "mailto: alexander@indus.ru"

# property library

double MMGetLotsCount (double dPrice, double dStopLoss, double dRisk, double dLeverage)

(

double dSpread = MarketInfo (Symbol (), MODE_SPREAD);

double dPoint = MarketInfo (Symbol (), MODE_POINT);

double dFreeMargin = AccountFreeMargin ();

double dMoneyRisk = dFreeMargin * dRisk/100;

double dPointsRisk = MathAbs (dPrice-dStopLoss) / dPoint;

double dPointCost = dMoneyRisk / dPointsRisk;

double dLots = dPointCost / dLeverage;

/ / Rounds dLots one decimal place, as MT has

/ / Can not deal with smaller lots

return (NormalizeDouble (dLots, 1));

////////////////////////////////////////////////// ////////////////

/ /

/ / ATTENTION!

/ /

/ / We should be careful in relation to the fact that the rounding

/ / Is happening to the nearest tenth of a, ie 0.06 becomes 0.1

/ /

/ / If the algorithm you are not satisfied, then

/ / Implement your way round, for example, rounding to the

/ / The nearest tenth of a

/ /

////////////////////////////////////////////////// ////////////////

)





The contents of the file mmlib.mqh



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

/ / | Mmlib.mqh |

/ / | Copyright c 2004, Alexander Ivanov. |

/ / | Alexander@indus.ru |

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

# import "mmlib.ex4"

double MMGetLotsCount (double dPrice, double dStopLoss, double dRisk, double dLeverage);



The contents of the file order_by.mq4



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

/ / | Order_buy.mq4 |

/ / | Copyright © 2004, Alexander Ivanov. |

/ / | Alexander@indus.ru |

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

# property copyright "Copyright © 2004, Alexander Ivanov."

# property link "mailto: alexander@indus.ru"

/ / Next, the constant DAYS_TO_CONSIDER will we replace the quantity

/ / Days on which we will seek at least to be placed Stop loss'a

# define DAYS_TO_CONSIDER 3

/ / Could add to the definitions in stdlib.mqh

/ / But let's hope that MetaQuotes Software do it yourself

/ / In the next version stdlib.mqh, as yet, for ease of reference,

/ / Define constants for error in this module. After adding them to the

/ / Stdlib.mqh, the following two lines need to be out

# define ERROR_NOT_ENOUGH_MONEY 134

# define ERROR_PRICE_CHANGED 135

////////////////////////////////////////////////// ////////////////

/ /

/ / ATTENTION!

/ /

/ / Allow the import functions of the compiled libraries

/ / You can check 'Allow import of external experts'

/ / On the 'advisers' window' Settings' caused SELECTING



/ / Menu Servis'-> 'Options'

/ /

/ / In our case it is necessary, because we are going to import

/ / Function ErrorDescription (...) from the library and stdlib

/ / Function MMGetLotsCount (...) from the library mmlib

/ /

////////////////////////////////////////////////// ////////////////

/ / Connects the library containing the implementation of

/ / This script functions

# include / / contains the desired function, we ErrorDescription (...)

# include / / contains the desired function, we MMGetLotsCount (...)

int start ()

(

/ / While (true) means that we are going to try to

/ / Set the order until it will not be accepted for execution

/ / Or receive so that we have to account zakochatsya free money

/ / ... or the user manually stops the script, for example,

/ / Selecting an item from the context menu of price schedule

while (true) (

double dMyRisk = 20 / / Assume that every time we accept the risk

/ / Twenty percent deposit free

double dMyLeverage = 100 / / Shoulder allowed us to broker

/ / DaysLowArray - is an array, which will be placed a minimum

/ / Day values for the last few days DAYS_TO_CONSIDER

double DaysLowArray [DAYS_TO_CONSIDER];

/ / Copy DAYS_TO_CONSIDER Day Low values in the array DaysLowArray

if (ArrayCopySeries (DaysLowArray, MODE_LOW, Symbol (), PERIOD_D1)


return (PrintErrorDescription ());

)

/ / As the value of Stop loss will use

/ / Minimum value of the current day and the previous two days

double dMyStopLoss =

DaysLowArray [ArrayMinimum (DaysLowArray, DAYS_TO_CONSIDER - 1,0)];

/ / Stores the current price in the event that during the computation

/ / Number of lots the price has changed.

double dMyPrice = Ask;

MQL 4: Library functions and their use in programs.

FOREX MAGAZINE © 2004-2005

January 2005 ? 52 / 3

59

/ / For simplicity, set Take profit at twice the Stop loss

double dMyTakeProfit = dMyPrice + 2 * (dMyPrice-dMyStopLoss);

double dMyLots =

MMGetLotsCount (dMyPrice, dMyStopLoss, dMyRisk, dMyLeverage);

Print ( "Price =", dMyPrice,

"Stop =", dMyStopLoss,

"Teika Profit =", dMyTakeProfit,

"Lots =", dMyLots);

if (OrderSend (Symbol () / / tradable instrument

, OP_BUY / / Type of operation

, dMyLots / / Number of lots

, dMyPrice / / warrant price

3 / / slippage

, dMyStopLoss / / Stop loss

, dMyTakeProfit / / Take profit

, "Ordered by" order_buy "script"

, 255 / / unique number

, 0 / / End time of the pending order

, HotPink / / color of labels on the graph

) <= 0) (

int error = PrintErrorDescription ();

/ / Process errors encountered during the placed orders

switch (error) (

case ERROR_NOT_ENOUGH_MONEY: (

/ / Lack of money to spend, will have to complete the sale :-(

return (error);

)

case ERROR_PRICE_CHANGED: (

/ / Price had changed, you need to update quotes

/ / And try again to put the warrant

RefreshRates ();

break;

)

default: (

/ / Forward 10 seconds

Sleep (10000);

)

)

) Else (



OrderPrint ();

break;

)

)

return (0);

)

/ / Executable code function PrintErrorDescription () is used

/ / Double inside the function start (), and therefore we found it necessary to make

/ / It in a separate function

int PrintErrorDescription ()

(

int error = GetLastError ();

Print ( "Error =", ErrorDescription (error));

return (error);

)









Alexander Ivanov

to Forex Magazine

fxtrade@tomsk.ru

No comments: