Showing posts with label MQL. Show all posts
Showing posts with label MQL. Show all posts

Friday, March 20, 2009

Programming language MQL 4: Interaction with the environment

In the previous article devoted to the study of MQL4 (Forex Magazine ? 48), we examined the environment of programs written in MQL4. In this article, try to understand the intricacies of communication between the MQL-media program and the client terminal, performing the program, but for one explain step by step, one of three possible types of user programs - Indicators.

But first a slight digression, which we hope will greatly facilitate the passage of one of the stages of MQL-creation program to combine creation wizard advisers:
Each time, beginning to write MQL-program with wizard creation advisors, we get the skeleton of the program with information about the developer, stating that the copyright belongs MetaQuotes Software. With that you can live on stage, but when you begin to write independently, and may distribute their own programs, naturally want to "cap" of the program contain your personal information. You can manually correct each time this version of the "cap" on its own or do it in one of the steps the wizard correcting field "Author" and "Link", but easier once done so, as suggested below.
Attention, described further method involves the precise understanding and consistent implementation of all these actions. If you are not confident that the deal with a task, it is better not berites for it at all!
Irregular steps with the register could lead to full or partial inoperable vehicles. Neither the author nor the Journal assumes no responsibility for the consequences of the process or other breaches of your system.

1. Run RegEdit

2. Select a tree in the left pane of the branch HKEY_CURRENT_USERSoftwareMetaQuotesSoftwareMetaEditor 4Experts

3. In the "File" menu, select "Export" and save in the selected line information. Reg file. Next to the certainty we assume that the selected registry branch was saved in the file "ME_ProgramHeader.reg"

4. Close the program RegEdit.

5. ME_ProgramHeader.reg open the file for editing. To do this in Windows Explorer, clicking on the file name, right-click from the context menu choose "Edit".

6. Change the field "Address" and "Author" to those that you want to see in the future in the "cap" program. Do not forget to double quotes, as in the names of the parameters and their values, as was the uncorrected file.

7. Now save the file under a different name, for example, "My_ProgramHeader_.reg" and close it.

8. Now you have two files: one - with the original data, which can at any time to restore the other - with your data that we have now added to the registry.

9. In Windows Explorer, double-click on the file name My_ProgramHeader_.reg, agree with the proposal to make the data file to the registry click "Yes" and then accepted congratulations on the successful introduction of data in the registry, again pressing "OK".

10. Established in MetaEditor'e with the wizard and a new program in the second stage, when prompted to enter the name of the program, we see that the "author" and "Reference" contains the necessary lines to us.

Now, each time the wizard will offer to create a MQL-program with the "correct" fields "Author" and "Reference". But if suddenly you want to return the value of the registry to its original state, it will be done very easily, you will need to restore the values from a file created on the 3 rd stage.

For this material will need to create a skeleton of an indicator. Causing the creation wizard advisers indicate that we want to create a custom indicator and proceed to the next screen, click "Next." The next stage is to determine, let's call our indicator Indicator1 and then click "Next." Adding an index and complete the wizard.

Our code, which has so far not doing anything useful, but it already contains all the formalities required in order to begin filling its functionality. Nachnem line parsing skeleton future indicator. Preview of five lines - this comment, which contains the name of the file pravaobladatel source code and a link on how to contact the author of the code. Comments from the viewpoint of MQL-program, there is something, which at the time of compiling the program does not need to pay attention, that is, they will never become the compiler of any executable command. Comments are written mainly for the fact that either do not forget the very many years, or that others read the source code to understand what it is.

The next section, which describes the properties (properties) buduyuschey program. Properties may include the following fields:

general information about the program:
copyright
link
Type of compiled module:
library
indicator_chart_window
indicator_separate_window
maximum and minimum indicator:
indicator_maximum
indicator_minimum
number of charts and color:
indicator_buffers
indicator_color1. indicator_color8

From general information about the program, we can specify two parameters. The effect of these parameters will be visible when we add an indicator on the graph. On the options panel display appears with the text, which we indicated in the "copyright". Clicking this inscription runs described in "link" refers to a web resource.

Then you can select the type of compiled module

If we write a program advisor, then none of these properties are not required. If we write the indicator, you can choose an indicator risuemy in the window with the price schedule, (chart window indicator) or indicator risuemy in a separate window (separate window indicator). The property of "library" refers to the fact that we do not want to write a program advisor or the type of indicator, and library functions. When we say that there are three types of programs, we purposely did not mention the library of functions - firstly, it is not a program, as well as can not be met, and secondly, until they turn comes when we are fully ovladeem skills MQL-creation programs.

The following properties of the program are responsible for the maximum (indicator maximum) and minimum (indicator minimum) value of the indicator. They are useful in the case when we write the indicator displayed in a separate window.

Let's look a little more detail the properties, indicating the number of schedules displayed indicator, and color. In previous versions of MetaTrader 3.x users from MQL-programs could draw only two curves. Often this is not enough, and had to resort to various tricks. It was common to use several programs for MQL-drawing of one indicator. This method does not satisfy many of the fact that he was not so time consuming, but not obvious and inconvenient. MetaQuotes Software Developers MetaTrader4 have taken into account when writing this weakness and the possibility of adding custom indicators to draw up to eight graphs. Now, in order to use a few graphs will need to specify the number of property
indicator "indicator_buffers". Well, to each of the scheduling indicator is displayed on the screen the desired color, you need to specify them in saoystvah indicator_color1, indicator_color2, indicator_color3 and so on until indicator_color8.

It is important to understand that it is not a direct indicator draws on the screen MetaTrader'a all that want, but merely asked to comply with this or that drawing, as already MetaTrader is free to decide how and what to do. Properties of the program during its run MetaTrader'om and deducted on the basis of their values MetaTrader Indicator draw on the screen, but these properties can be further modified from the terminal using the panel properties of the program.

Explain what properties can be used in MQL-programs, and how they operate in interaction with the indicator MetaTrder'om, you can go back for further review postrokovomu skeleton buduyuschey program.

For the section describing the properties, there is a section on global variables, recall that the "global", they are called from the fact that the area of visibility extends to all the features included in this file.
There is no global (we'll call them "local") who are declared within a function is not available for other functions.

The first and so far the only variable - it ExtMapBuffer1. This array, which must be filled with the values of our indicator. This is another fine place to back-terminal program, which is important to clearly represent yourself. ExtMapBuffer1 - this is the only one (in the case of a schedule) the opportunity to influence the way of rendering graphics. Then we will see how this variable relates to the schedule.

Look at the function init (). There are two callback functions of the software interface MetaTrader'a:
SetIndexStyle (0, DRAW_LINE);
SetIndexBuffer (0, ExtMapBuffer1);

One of them said that the schedule should be otrisovan as the solid line and the second connects the variable array ExtMapBuffer1 in our program with an array, which will be deducted MetaTrader data
otrisovyvaya schedule.

If you want to display multiple graphs on a screen, each of them will be proinitsializirovan this way. Number initsializiruemogo schedule is transmitted first parammetrom in both functions, this value is "0" as the indexing of arrays of graphs starting from scratch.
Further lines of you should already know. If not, then explaining to continue sending the reader to the previous issues of the journal Forex Magazine (? ? 20-28) and the site developers MetaTrader 4 - site of the company MetaQuotes Software



Alexander Ivanov
to Forex Magazine
fxtrade@tomsk.ru

MQL 4: Relation of user programs with internal arrays terminal

In a previous article we discussed the general interaction of the performing environment MetaTrader'a with a custom program. Today will be examined in detail the mechanisms linking the variables of user programs with a special area of memory - the internal representation of data in the memory of the terminal.
During the terminal is processing a large amount of data, which stores the entire history of a particular instrument at a given time interval. History is loaded into the terminal of the special files from the disk of your computer, and then in the process of on-line with MetaTrader'om load over the Internet from your broker. Historical data about each tool is stored in dynamic memory running MetaTrader'a in six volumes, each of which is available from MQL-user program. Not hard to guess that the six arrays are as follows: an array of Open, an array of Low, array High, an array of Close, the array and an array of Time Volume. User program elements for each of the above ranges are available under the name of the array and index. Index - the number of bars for which the requested data. For example, if you want to know the value of the price of opening a bar, formed by three periods ago, the program we will write Open [3].

It is often convenient to program, instead of full names of the arrays to use their abbreviated synonyms. For this example, you can record short: O [3]. The other five arrays, too, have their synonyms:

use of L is equivalent to Low,
H ~ High,
C ~ Close,
T ~ Time,
V ~ Volume.

In the above diagram clearly illustrates the fact that each bar corresponds to a set of six arrays of elements of historical data. The index of the cell array corresponds to the number bar. Number of elements in each of the data sets due to the number of historical data stored in the history of MetaTrader'a. The program can find it, referring to the built-in variable MQL "Bars". The figure also shows that the numbering of the bars is carried out from scratch. For readability, you can compare the number of bars with his age in the interim period of the current schedule. The older the age, the greater the number of bars, this bar is not yet formed and the number is zero, it can be considered as "babies." If we look at the yearly charts, you get a complete analogy with the age of bar numbers person.

Now pay attention to the fact that this method of treatment to the historical data provides information only about the instrument and the time interval scheduling, which is attached to the user program.

If you want to get data from the history of another time period or other tool, it should be used specifically for the intended function of the arsenal of MQL 4.

After consideration of the built-in MetaTrader arrays for storing and working with historical data, go to the question of user interaction with the environment MetaTrader'a, namely - to consider the array of indicators for the drawing.

In the last article, we will, considering the source code skeleton indicator, cooked with the wizard creating advisors, drew attention to the existence of a global array ExtMapBuffer1. Let's go back to a more detalnmu the topic.

By analogy with the above described arrays of historical data, the data for drawing the custom indicator is also stored in internal arrays allocated MetaTrader'om. As we already know from previous articles, such arrays may be allocated to eight. But pre-allocate memory in MetaTrader'e for these arrays, it would not be very economical, since not every indicator will draw all of the eight schedules. This means that when you start indicator, MetaTrader must be clearly informed of the number of arrays, it should provide data for the indicator and, last but not least, the number of arrays MetaTrader be taken into account, otrisovyvaya indicator on the graph.

The programmer can communicate this information through the feature indicator indicator_buffers. Furthermore, for illustration, we assume that we have set this property equal to three.

But by itself the number of available ad indicator arrays nothing will. Even the announcement of three variables, which must contain an indicator, does not help. Pledged arrays need to relate to the allocation of these memories in order to make them truly relevant in drawing the indicator executable environment MetaTradder'a.

Binding a custom program with these arrays occurs via the function call SetIndexBuffer. The first parameter is passed the number allocated to the array, the second - the name of the variable declared as an array without the elements.

The picture shows a situation that will happen only after a call of this function, as shown below:

SetIndexBuffer (0, ExtMapBuffer1);

In doing so, being the binding of the variable ExtMapBuffer1 with the first (with the number "0") array, a dedicated performing environment. Note that in accordance with the property indicator indicator_buffers equal to three, two allocated array remain unconnected.

If we try to refer to elements of arrays of variable ExtMapBuffer2 and ExtMapBuffer3, non-distributed MetatRader'om memory will not work. All our efforts will not be visible on the screen of the terminal. As you have probably guessed, these arrays also have to associate with a distributed memory MetaTrader'om using the following calls:

SetIndexBuffer (1, ExtMapBuffer2);
SetIndexBuffer (2, ExtMapBuffer3);

Now let's investigate how to fill the arrays, which are available to us through the associated
variables of the program. Let us turn to the skeleton of the indicator, which had been prepared for us to master the creation of advisors, and look more function start ().

int start ()
(
int counted_bars = IndicatorCounted ();
//---- TODO: add your code here
//----
return (0);
)

You can see that the artist has added a line, which is created and initialized integer variable counted_bars. After the function call IndicatorCounted (), the variable will contain a number of bars, which is already calculated the value created by the indicator.

One could do without it, but if we see that the artist so insistently invites us to enjoy this way of working with data, we can see so far is not much point to disregard the recommendations.
If we decide not to use IndicatorCounted () to find out what the bars have already calculated the indicator, then we would have to invent their own way of doing this, or could have been a time when the performing environment MetaTrader'a function called start (), recalculate the value of the indicator at all bars.

The latter method can be very computer load calculations, and when the price schedules attached to the large number of indicators, ignoring the call to the function IndicatorCounted (), we felt a certain discomfort because of the slow reaction of the terminal for our actions.
To avoid problems with the excessive computational load, it is suggested every time you call the performing environment to find out how many bars have already been taken into account when calculating the values of the indicator at the previous calls of the function start (). This is the first line of code our function start ().
After that, usually checked, there has not been there when you call MQL-function IndicatorCounted () of any errors. If counted_bars less than zero, the error occurred, and it makes no sense to continue this iteration of calculating the indicator.
In the case of an error we return from the function start () using the directive return. Pointing as a parameter in the directive, we return a negative value, thus, returns this number in the performing Wednesday terminal, allowing MetaTrader'u understand that computation is not performed or performed incorrectly due to an error. If the error does not happen, then we can continue to calculate and further algorithm works most of the indicators matches:

. if the number of recorded bars greater than zero, it takes away from the unit to ensure that this iteration in any case once again to calculate the value of the indicator, obtained in the previous call to start ();
. calculate the number of bars in which you want to calculate the indicator values (based on converted bar);
. in a cycle of performing computations on the values of the indicator bar and enters the required values in the arrays are allocated to the performing environment and associated with some variables of the program during its initialization.
All together, it looks something like this, as shown in the following example, provided detailed comments:

int start ()
(
int limit = 0;
/ / Get the number of recorded
/ / In previous iterations of the bars
int counted_bars = IndicatorCounted ();
/ / Check whether there was an error
if (counted_bars <0)> 0) counted_bars -;
/ / How many bars you need to calculate
/ / At this time?
limit = Bars-counted_bars;
/ / Execute the main loop
/ / Calculating the values of the indicator
for (int i = 0; i
Alexander Ivanov

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

Saturday, March 14, 2009

Implementation of programs, types and structure

Programming language MQL 4: Implementation of programs, types and structure

Writing programs in any programming language requires a complete understanding of how and in what environment it will rabotat, and what is its user audience. If the audience with programs written in MQL 4 is almost always clear, since the first issue is to deal with separately. A number of comparisons in the usual program, performed on our computer, and programs written in MQL 4. First of all, attention should be drawn on who performs the instructions of a program.

When the regular program runs on your computer, its instructions are executed directly to the processor and operating system. If such a program needs to read the file from the disk, it makes a request to the kernel operating system, and have the kernel code is responsible for reading the file. If such a program needs to calculate the sum of two numbers, then it turns to the processor with a request to put two numbers. Thus, the normal program is executed, appealing directly to the processor and operating system. That is, the operating system is the environment program, a processor - a means of execution of the program guidelines.

Now consider the case where a program is written in MQL 4. We can not simply run a program on our computer, if it is not installed MetaTrader 4. This means that this program really is not a full-fledged stand alone executable module. The lion's share of what the program wants to make, not the program is executed, and the interpreter MQL-program client terminal Metatrader 4.
When the MQL-program needs to read the file from the disk, ona do not ask for the opportunity to have an operating system, as it would make "full" program, and asked the interpreter to refer to the operating system and read the file. If the MQL-program needs to put two numbers, then it can not lay down the processor skomandovat two numbers, it may ask interpritator that he appealed to the processor and the processor has already resigned two numbers. MQL-starts, and running the interpreter, built into the client terminal. Is it good or bad? For programs orietntirovannyh to work only with the MetaTrader 4, this option is suitable, as no other. It is through such an arrangement the terminal with user applications can easily be made available to MQL-program all the services available to the user in MetaTrader 4. The interpreter intercepts all calls MetaTrader'a functions and performs them with the core client terminal. Agree to call the program interface terminal
set of features and functionality, offers MetaTrader'om MQL-program. And note that the study of programming language - this is basically the study of interfaces available for implementation of their plans.

In addition, with MQL-accessible program interface terminal, the new version of the language was added to the opportunity to perform functions that are compiled in the so-called dynamic library that allows you to perform the functions written in other programming languages. Thus, writing their own dynamic library allows you to create user interfaces, and thereby expand the functionality MetaTrader'a. But it will be discussed later, and only when fully mastered the basics of programming in MQL 4, now it is worth noting is that many of the functions of the operating system available for use in such a way. To see a list of such functions are advised to look to the file WinUser32.mqh, supplied together with MetaTrader 4.

Now it is time to discuss the types of programs that we can write in MQL 4, they are divided into three types:
. Counselor;
. Custom indicator
. Custom script.

It is these three types of programs we proposes the creation wizard programs MetaEditor'e called by pressing Ctrl + N).

Counselor - MQL-program, which is attached to a certain schedule and running at every prevention, ie, after each price change. Counselors are typically used for writing, mechanical trading systems. Indeed, the very title of "advisor", says that this program is to suggest something to do or not do you change the price. The program type advisor is exclusive opportunity - at that time to commit the transaction. Such a possibility is lacking in other types of custom programs. Moreover, an adviser may make the transaction as a real and virtual. In the latter case, he notes in the chart is the place where the transaction could be accomplished without performing
actual operation, he would advise her to make.

Custom Indicator - MQL-program, which allows us to write our own technical indicator. Often, traders want to have a large set of indicators than that provided them with the developers of the terminal. To save the situation called MQL-program type of "user LED". In these programs, we can draw their own graphs and display text and graphics on the label character quotations. Indicators, as well as advisers, to display attached to the schedule of a commercial instrument, and performed at every price changes. The difference is that the custom indicators can not carry out any transactions.
As already noted, advisors and indicators are performed at each change in price. This oznayaaet that when we are attached to a graphic indicator of or an advisor, metatrader puts him in a sort of internal queue and when there is a change in price, all trapped in this particular program are executed alternately.

Custom script - MQL-program that is written to perform any specific action and is done only once. To re-execution of the script, it will need to explicitly call again Taka as he will not be executed, as with advisors and indicators.

As we have seen, all three types of MQL-programming differ, as a way of fulfilling their interaction with environment (ie MetaTrader'om) and destination.

Now proceed to consider the structure of the program.
As a rule, to write the program you want to use the creation of advisors (called by pressing Ctrl + N). Depending on the type of program, after all the steps of the implementation of the master creation adviser, if the adviser had been selected or custom indicator, you'll see the text with three empty functions or one function of an empty, if the script has been selected.

First of all, it is worth noting that the program for the MQL 4 clearly structured, and their implementation is divided into several stages.

Counselors and Displays include in their programs of three phases of implementation, which are represented by the functions init (), start () and deinit (). Scripts are the interpretation of the function start (). Such a structure can talk about what steps the program takes place from its attachment to the schedule to the point where it will be removed from the schedule of the user.

The life cycle of all programs, with the exception of scripts includes: initsialzatsiyu, the main part of the program and deinitsializatsiyu. These stages as time and realized functions init (), start () and deinit ().
Not hard to guess that the main work is performed in the function start (), because it runs every time there is a change in schedule, which is attached programma.Krome these functions, the program contains a header. In this title, except for comments, explanations of the founders of the program and their rights to the program, shows the parameters for program execution, such as: whether the indicator is running in the same window as the schedule of prices, or whether it will draw in a separate window, and other parameters . All details will be considered by us in the following articles.

Today all. Readers are advised to carefully look at and compare the sources of indicators and advisers included with MetaTrader 4 as examples. Very useful to read how to use MetaEditor 4 and learn how to compile the program.



Alexander Ivanov
to Forex Magazine
fxtrade@tomsk.ru

Friday, March 13, 2009

Comparison with EasyLanguage and MQL II

Until recently, the undisputed leader in the trading systems for trading in financial markets remained firm TradeStation program of Omega Research. Programming language for writing indicators and trading systems for TradeStation is a convenient and easy to explore the EasyLanguage. Naturally, many enthusiasts and professionals has created a great number of indicators and trading systems to the system. The program, which includes trading terminal TradeStation, for too long becomes a model for software systems of its class, but the last time about the team of developers so the famous trading platforms do not hear anything, and probably unlikely to hope for its further development and support.



The natural desire to keep pace with time, forcing many, especially traders, is just beginning to work in the financial markets, to choose a modern trading platform, which will continue to develop and maintain. One of the candidates can be prepared for release in the near future trade-information complex MetaTrader 4.



As in the choice of platform traders intend to write your own indicators and trading systems should pay close attention to the programming language, then in order to help them to orientate themselves in this situation, we compare three programming language used in the modern trading platforms. The first two programming language - it is already mentioned EasyLanguage for TradeStation terminal and used in the present version of the trade terminal MetaTrader programming language MQL II. Third, in connection with the upcoming release of new versions of light commercial and informational complex MetaTrader 4, our review has got used to it a programming language MQL4.



Despite the fact that in today's review will involve only three languages, this story can serve as a starting point to determine the capabilities of any other programming language used in the modern trading systems.



So, to start it should be noted that the formal description of MQL II language states that it is syntactically highly similar to EasyLanguage, which means that a programmer familiar with the latter, could easily understand what is written in the program for the MQL II.



Apparently, when a group of designers the company MetaQuotes Software question for inclusion in the first version of the terminal MetaTrader convenient and easy to explore programming language, they felt that the right to make available to writers of the language programs are very similar to the familiar and well-established language EasyLanguage. That decision freed programmers from many of the difficulties associated with the transition to a new programming language, and has enabled a large audience of traders almost painless to take advantage of their ideas for the new TradeStation platform.



In support of the above, further contains syntactically correct expressions in the languages of EasyLanguage and MQL II:



Sample code in EasyLanguage



If Close [0]> Close [1] then begin

Condition1 = Low [0]
Condition2 = RSI (Close, 14) <30;

End;



Sample code to MQL II



If Close [0]> Close [1] then begin

Condition1 = Low [0]
Condition2 = iRSI (14,0) <30;

End;



You can see that the difference occurs only in the third line, when you want to get value indicator RSI, in the rest of the code is identical.



Over time, weaknesses have become clear MQL II, and by developing a new version MetaTrader'a in MetaQuotes Software decided to offer for programming a new programming language MQL 4, which seems to have managed to combine the best of his two predecessors. " In addition, it appeared very useful innovation, extending the capabilities of programmers.



Try to show some of the most important, in our opinion, differences MQL 4 of EasyLanguage and MQL II.



1. The structure of the program for the MQL 4 gained a clear division into blocks, each performed in due time. The program consists of certain functions init (), deinit () and statr (), that run at startup, respectively, and in the process of completing the program. Program for EasyLanguage and MQL II contained all the challenges and directions in a common block, and many, especially novice programmers, hampered write code block, which would be implemented only once, when you first start the program.



2. Indicator written in EasyLanguage, can contain a maximum of only four lines indicator. Indicator written in MQL II, may otrisovat even fewer lines of display - only two lines. Language MQL 4 is a function SetIndexValue, which as the first parameter takes the number of index data draw the line, and, judging by the fact that the index is type integer, then in theory, this function could specify the data for 32768 lines. In reality, this number is likely to be limited by a reasonable number to thirty.



3. Languages EasyLanguage and MQL II were able to work only with arrays of fixed length, the size of the array to be a programmer to guess at a stage of writing the program. This made certain restrictions on the algorithms. MQL 4 contains all you need to work with arrays, which can be changed dynamically programmer - in the work program.



4. Language MQL 4, due to the import function from any Shared Libraries (from the files with the extension. Dll) can now perform all kinds of system calls. This shortcoming can be eliminated almost all the missing features.



5. EasyLanguage Syntax when placed orders for the purchase, sale and closing of the warrants has a lot of nuances. MQL 4 language inherited from the MQL II comfortable, from the standpoint of the programmer, the method of insertion orders.



6. MQL II language is not permitted to work with multiple tools at once from one program that is not allowed to write the complex indicators, based on data from several time periods, and are not allowed to test the trading system at the portfolios of currencies. In MQL 4 the opportunity appeared.



7. Some changes to the syntax allowed to write readable programs. Denial of the use of MQL 4 operator brackets "Begin ... End", used both in MQL II, and in EasyLanguage, led to the source code of programs perceived significantly easier in such programs primarily visible essence. Despite the apparent triviality of this change, it could significantly ease the life of programmers, especially beginners.



8. In MQL 4 get rid of ambiguity operator "=", which in language MQL II and EasyLanguage, depending on the context of use, means two different steps: assigning a new value of the variable and comparison of two values. Now, in the case of the assignment to the "=", and to check on the equality of the two values is used "==".



For objectivity should be notice that there are trading systems that offer programming to use advanced programming languages such as VBScript and JavaScript. But these languages because of its universality, a few newcomers to explore the complex and, in particular, people far from the programming.







Alexander Ivanov

to Forex Magazine

fxtrade@tomsk.ru

Saturday, March 7, 2009

Programming in MQL 4: Trading System. Part 3.

In this article, we will continue the theme begun in the previous two issues of the journal Forex Magazine, and write the Adviser on the basis described in the previous section the general scheme of the advisers.



So, based on the MTS trading system to select the indicator RSI. Once a reservation, that this system is purely illustrative and are not scheduled for any of the financial markets. Moreover, the values of the parameters of the system are taken at random and have nothing to do with that really required in this situation.



Here to launch verbal description of the system:



One open position simultaneously.



Indicator RSI. Period indicator parameter is set adviser.



1. Rules of the opening lines: signal to open a short position will be the intersection of the curve RSI levels down 80% and 70% running. That is, if the intersection of the level 70% No 80% crossing level, the price of such behavior should not be taken into account, the signal for opening a long position will be the intersection of the curve RSI upward two levels of 20% and 30% running. That is, if the intersection of the level 30% No 20% of the level crossing, it does not take into account the price of such behavior.



2. Terms of closing the position: a signal to close long positions will be the intersection of the bottom-up level of 80%, a signal to close short positions will be the intersection of top-down level of 20%. In addition to these two signals at the closing position, the warrant will be closed by stop-loss'u, which will be calculated as a percentage of current price. The percentage will be raised as a parameter adviser.



3. The size of the position will be calculated as a percentage of the deposit. The percentage will be raised as a parameter adviser.



Then follow, in accordance with the scenario described in previous articles on trading systems.



With the help of advisers to the writing wizard, create a skeleton Adviser RSI-advisor. Do not forget the second stage of the master of writing advisers add parameters: nRsiPeriod type int, and the initial value of 8; fStopLoss type double and the initial value of 1.5 and fLots type double and the initial value of 0.10.



Upon receipt of frame indicator, start to fill his logic.



There are no special restrictions on the input parameters we have imposed, and therefore function Adviser init () will remain unchanged.



All the rules that we have indicated in the verbal description of the trading system will be checked and processed in the functions of adviser to start (). Here's the source code of the indicator, in which all the steps detailed comment.



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

/ / | RSI-advisor.mq4 |

/ / | Copyright © 2004, Horn |

/ / | Alexander@indus.ru |

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

# define copyright "Copyright © 2004, Horn"

# define link "alexander@indus.ru"

int g_nRsiPeriod;

double g_fStopLoss;

double g_fLots;

int init (int nRsiPeriod = 8, double fStopLoss = 0.5, double fLots =. 10)

(

g_nRsiPeriod = nRsiPeriod;

g_fStopLoss = fStopLoss;

g_fLots = fLots;

return (0);

)

int deinit ()

(

return (0);

)

int start ()

(

/ / If this function was called MetaTrader'om,

/ / Means a change in price or advisor

/ / Run the first time.

int nShift = 0;

int nOrders = 0;

double fCurrentRSI = 0;

double fPreviousRSI = 0;

double fShiftRSI = 0;

/ / Do not be 10-second limit?

if (CurTime () - LastAttemptTime () <10) return (0);

/ / Get values RSI indicator at the current and previous bar

fCurrentRSI = iRSI (g_nRsiPeriod, 0, PRICE_CLOSE, MODE_FIRST, 0);

fPreviousRSI = iRSI (g_nRsiPeriod, 0, PRICE_CLOSE, MODE_FIRST, 1);

/ / Do not exceed the number of open orders?

nOrders = OrderTotal ();

if ((nOrders <1)> = 1000 * g_fLots * 1.5)) (

/ / If no open positions, and the account is free

/ / Means that we check the values of indicators

/ / To check the signal for opening a new position.

/ / Check whether the fall in the current bar value of RSI

/ / In the corridor from 30% to 70%.

if ((fCurrentRSI) <70> 30) (

/ / Check whether the value of RSI in the previous bar more

/ / 70% line

if (fPreviousRSI> 70) (

/ / A chance to open a short position!

/ / Check remaining only after it matter

/ / RSI zone perekuplennosti 80% -100%

for (nShift = 2; nShift
fShiftRSI = iRSI (g_nRsiPeriod, 0, PRICE_CLOSE, MODE_FIRST, nShift);

if (fShiftRSI> = 80) (

/ / Open a short position and exit

OrderSet (OP_SELL, g_fLots, Bid, 3, Ask + (Ask * g_fStopLoss/100), 0, Blue);

return (0);

) else if (fShiftRSI <70) (

/ / Value RSI "was" not out of the perekuplennosti 80% -100%

/ / A, rising from the corridor 30% -70%, "chatter"

/ / In the corridor of 70% -80%. This intersection of RSI and

/ / Level 70%, we do not see how the signal and ends

/ / Handle the previous bars.

break;

)

)

) Else

/ / Check whether the value at the previous bar RSI is less than

/ / 30% line

if (fPreviousRSI <= 30) (

/ / A chance to open a long position!

/ / Left only to check whether the value rose

/ / RSI zone pereprodannosti 0% -20%

for (nShift = 2; nShift
fShiftRSI = iRSI (g_nRsiPeriod, 0, PRICE_CLOSE, MODE_FIRST, nShift);

if (fShiftRSI <= 20) (

/ / Open a long position and exit

OrderSet (OP_BUY, g_fLots, Ask, 3, Bid-(Bid * g_fStopLoss/100), 0, Red);

return (0);

) else if (fShiftRSI> 30) (

/ / Value RSI "was" not out of the pereprodannosti 0% -20%

/ / But, down the corridor from 30% -70%, "chatter"

/ / In the corridor of 20% -30%. This intersection of RSI and

/ / Level 30%, we do not see how the signal and ends

/ / Handle the previous bars.

break;

)

)

)

)

)

/ / If it is not possible to open a new position,

/ / You should check, is not it time to close the already open-minded.

for (nShift = 0; nShift
int nType = OrderGet (nShift, VAL_TYPE);

if (nType == OP_BUY) (

if (fCurrentRSI> = 80) (

/ / Your purchase, we are in zone perekuplennosti,

/ / Therefore, it is time to close

OrderClose (OrderGet (nShift, VAL_TICKET), OrderGet (nShift, VAL_LOTS),

Bid, 3, Violet);

return (0);

)

) Else if (nType == OP_SELL) (

if (fCurrentRSI <= 20) (

/ / Selling, we got into a zone pereprodannosti,

/ / Therefore, it is time to close

OrderClose (OrderGet (nShift, VAL_TICKET), OrderGet (nShift, VAL_LOTS),

Ask, 3, Magenta);

return (0);

)

)

)

return (0);

)



Just the simple terms of trade described MTS provides a small number of input parameters, which are always evaluated as one of the benefits of the trading system. When the opportunity to test the advisor, we will need to pick the optimal time indicator, depending on the time period under consideration, the amount of stop-loss'a, depending on the volatility of the currency and the size of the lot. The size of the lot should be selected by the rules applicable moneymanagement'a. In this case, one could write a function that, given these rules, are automatically calculated to the size of the next transaction. Proposed method used only for ease of implementation.



It should be noted that the final wording of the language MQL 4 will allow contact to the values of historical data and obtain the values of indicators of different time periods. In the current version of the language MQL 4 implements this feature through the two functions work with arrays. Options ArrayCopyRates () and ArrayCopySeries () are parameters symbol_name and period, through which you can specify the character and time period of historical data required for backup.











Alexander Ivanov

to Forex Magazine

fxtrade@tomsk.ru

Thursday, March 5, 2009

Programming in MQL 4: Camera Selection

Last week, the expectations of many of us have been partially met - Meta Quotes Software company posted on its website a beta version of the editor programs MetaEditor 4, is included in the new version of MetaTrader 4 trading system. Public presentation editor MetaEditor 4 can, as they say, "alive" to get acquainted with the programming language MQL 4. We now provide an opportunity to assess a set of functions available to the programmer to write their own indicators and advisers.

Let's hope that soon we will have an opportunity to experiment not only with the programming language, but also seen in the trading terminal MetaTrader 4 complex written program in place.

Now forget about this, of course, exciting news and will return to the study of MQL 4. Proceed to consider the operator of choice "switch".

In the last issue of the journal Forex Magazine reviewed conditionals "if". In the same place it was observed that the algorithms to build their programs so as to avoid the use of the second part of "else" operator "if". But in practice it is not always possible to achieve that, moreover, are often situations when the condition operator "if" it is not clear to the expression that gives one of two outcomes "true" or "false".

The simplest explanation is an example. Suppose we know that some of the variable takes a few well-defined values. We should check whether the variable is each of the predefined values, and, depending on the test results, perform different actions. You can see that the operator, which allows you to do one of two actions (depending on the conditions) are not entirely suitable. That is, when it comes to make multiple selections, classic version of the operator "if" - not the best solution. You can, of course, to use a series of nested operators "if", which would be as follows:

if (my_var == condition1) (
/ / If the following first
/ / Condition, then perform
/ / This block
) Else (
if (my_var == condition2) (
/ / If the following second
/ / Condition, then perform
/ / This block
) Else (
if (my_var == condition3) (
/ / If the third
/ / Condition, then perform
/ / This block
) Else (
/ / If not done
/ / None of the three
/ / Previous conditions,
/ / Execute this block
)
)
)

We see that when the variable my_var checked for a match with only three different values, use the operator "if" makes some clutter in the code of the program: first, it is very easy to get to comprehend the brackets, and secondly, the code has become unwieldy, difficult to understand, and, moreover, the search for errors in the code can be a lot of trouble. Imagine what will be happening in the case where the variable will be checked for a match with ten different values.

Fortunately, for those cases in MQL 4 operator added "switch". Applied to the situation described above, using the operator "switch" looks like this:

switch (my_var) (
case condition1: (
/ / If the following first
/ / Condition, then perform
/ / This block
) Break;
case condition2: (
/ / If the following second
/ / Condition, then perform
/ / This block
) Break;
case condition3: (
/ / If the third
/ / Condition, then perform
/ / This block
) Break;
default: (
/ / If not done
/ / None of the three
/ / Previous conditions,
/ / Execute this block
)
)

This code is easier to read. Now, explain syntax of "switch", and how this operator works.
Just for the keyword "switch" in parentheses should be variable, a value which will be compared with several meanings. Following this, the operator in parentheses placed options "case" (one or more), each of which contains the verifiable value. After the program, go to the construction of "switch ... case", there has been a consistent comparison of the variable specified after the keyword "switch" with the values following the keyword "case".
At the very end of comparison may attend optional "default". If the program fails to comply with any of the blocks of "case", then it goes to the block "default". It should be read as a block, running by default, that is executed when there are no blocks of "case", the processing of the situation.
Please note that each block of "case" ends with the keyword "break". If you do not put at the end of the processing unit "case" operator "break", it will be performed next block "case" and "default" without any checks and until not meet "break" or not to finish the scope of the operator "switch". This nuance has its application in cases where multiple values of the target variable should be compared the same handler.

switch (my_var) (
case condition1:
case condition2: (
/ / Execute this block,
/ / If the following first
/ / Or the second condition.
) Break;
case condition3: (
/ / Execute this block,
/ / If the third
/ / Condition.
) Break;
)

Due to the fact that MetaEditor 4 became available the masses, we can look at examples of programs that comes with it. Using operator "switch" is illustrated in the display "Moving Average 4. The following code shows how to calculate different types of MA is considered by us in this article, the operator of "switch".

/ / Calculate current moving
/ / Average value
switch (g_MAType) (
case 0:
CalculateSMA ();
break;
case 1:
CalculateEMA ();
break;
case 2:
CalculateSMMA ();
break;
case 3:
CalculateLWMA ();
break;
)




Alexander Ivanov
to Forex Magazine

Programming in MQL 4: Variables. Part 2

In this article we will continue to talk about variables, explaining their purpose and some of the nuances associated with their use.

Pre-defined variables

In MQL 4 built predefined variables (predefined variables), such as Ask, Bid, Bars, Close, Open, High, Low, Time and Volume.

These variables are "tied" to a particular schedule, any of the tools offered by you on each of its time intervals has its own set of predefined variables mentioned above. Access to the values of these variables from the user program, attached to the schedule of a time period can be made at any time. Change the value of these variables is not possible.

It should be noted that the variables Close, Open, High, Low, Time and Volume are not single values, and arrays containing the historical data for the reporting tool. Access to the latter (we call this value "the youngest") of any of these variables is carried out on the variable name with an indication of the zero index. For example, the most recent sale price traded instrument is equal to Ask [0].

Variables Bid and Ask are relevant only to the current bar, so they are not arrays. It stores information about the proposed price of the seller and requested a price on a purchase.

Price schedules adopted seen across some time periods - the bars.

Bar - this is a graphic representation of the price of one period. Bar has its price discovery (the Open) - the price, which has been on the market at the time of the interim period, depicts a bar, the maximum (the High) and minimum (the Low) price achieved in the time bar and the closing price of the bar (the variable Close) - the price of traded instrument on the market at the end of the interim period, depicts a bar. The following figure explains what the graph correspond to these variables.

As we already mentioned, the rooms are convenient to think of bars, as they age. The current bar has not yet been formed before the end, and therefore its age is equal to zero. Bar, which was formed at the previous time interval, is the age of one period, and so on. In the above figure the number of bars shown with blue numbers, and can be seen as right to left with increasing age of the bars are increasing their numbers.

To find out how many bars are available to us in the program, we can use predefined variables Bars. To understand better the figure missed the average bars (instead of them, you will see the three-point bold), and left the last few bars. As you can see, the first bar on the left (the most senior in age) has a number equal Bars-1, the second from the left bar is the number equal Bars-2, and so on.

Many were put to a standstill by the fact that the oldest bar number is equal Bars-1. This is due to the fact that the numbering of the bars is not with the unit, and from scratch. Suppose, with ten bars, numbered from zero, we get the following set of their indices:

9, 8, 7, 6, 5, 4, 3, 2, 1, 0

As a result, the variable will contain a number of Bars bars (ten), and the most senior bar code will be equal Bars-1 (nine).

Array of Time contains the time periods depicted the opening bars.

The array contains the values of Volume ticks volume bars. They can be judged only on the number of transactions rather than on the actual volume of goods sold or purchased, whether the currency, stocks or other traded instruments.

Global Variables

Global variables (global variables) - a convenient tool for exchanging information between programs or to save the numerical values of your program at the time of shutdown or MetaTrader'a computer.

To create or change the value of global variable, you need to call GlobalVariableSet (). This function is create a global variable, if all of a sudden it does not already exist, as in the case when the variable already exists, change its value. The first parameter of this function is the name of global variable, the second parameter - a numeric value.

In order not to wonder whether or not already created a global variable with a certain name, you can use the GlobalVariableCheck (). Usually functions GlobalVariableSet () and GlobalVariableCheck () used together for the first initialization of a global variable as follows:

/ / If there is no global
/ / Variable with the name "g1", then
/ / Create it and assign it to
/ / Value 12345

if (! GlobalVariableCheck ( "g1")) (
GlobalVariableSet ( "g1", 12345);
)

Get the value of global variable using the function GlobalVariableGet ().

Remove a global variable using the function GlobalVariableDel (). If you need to delete all global variables that are present in the current system, you can do so by calling GlobalVariableDeleteAll ().

Variable scope

Devoting little attention to variables that are used to store the values when writing programs. In the article "Programming in MQL 4: Variables", printed in 21 issue of the journal Forex Magazine, we provide brief guidance on the application of the rules of naming, and now we have a little more space. Perhaps the readers have already noticed that in many programs, some variables have the prefix "g_", and some do not have this prefix. Try to explain what it involves.

When writing a program is necessary to take into account the so-called "scope" variable. The point is that in the original text of the program also have their global variables and local variables. Local variables are those declared inside any function. Scope of such variables is the function of the body enclosed in curly brackets, inside which they are declared. Global variables are the same - it is those who declared outside the body of a function, they are available to all functions of the file, which saved the program.

In order to facilitate understanding of the original text and the process of debugging programs, the names of global variables, ie variables that have a scope the entire file, beginning with the prefix "g_". This is not compulsory, but believe that adherence to this recommendation, you will greatly facilitate the process of writing the program and save your nerves when debugging. The example below shows the declaration of global and local variables:

/ / Global variable
int g_nLots;

void Function1 (int param1)
(
/ / Local variable
int nLots;

/ / ...
/ / Perform some action
/ / ...
);

By the way, the parameters passed to the function (in this case, param1), have the status of local variables and the area of visibility - the body functions.

If it does happen that the global and local variables will be named the same, the local variable is still in its visibility, it will be used. After exiting the scope of a local variable, the program will use a global variable.

/ / Declare a global
/ / Variable nLots
int nLots = 0;

void Function1 ()
(
/ / Declare a local
/ / Variable nLots
int nLots;
/ / ...
/ / Reference to the local
/ / Variable nLots
nLots = 100;
);

void Function2 ()
(
/ / Reference to global
/ / Variable nLots
nLots = 3;
)

It is clear that given the same name global and local variables are not best practice, we recommend you adhere to the data in this article additions to the naming of variables.




Alexander Ivanov
to Forex Magazine

Wednesday, March 4, 2009

Moving programs to MQL MQL II 4

In forums on programming for MetaTrader'a sometimes appear unhappy with remarks on the incompatibility between the new language MQL 4 language MQL II, used in earlier versions of the popular trading platform. Many users have a set of favorite MetaTrader'om custom indicators written in MQL II and, of course, be saddened by the fact that these indicators will not work in the new version of the trade information system MetaTrader 4. But it turns out, not so dramatic as it might seem. If there is a handy indicator of the source code to MQL II, a shift indicator on the new platform will not take too much time, and can be done is not even a man skilled in programming.



In this article we try to give advice, which can facilitate the process of converting "old" indicators on the new platform.



The first thing I would like to note - this will change the set of functions of language MQL 4.



Naturally, the change that has the language MQL, aimed at creating a more user-friendly tools and environment for writing programs. In this case, it would be logical to expect from the developers only enhance functionality and other features of language, rather than vice versa. This means that any feature of language MQL II duplicated version of the language MQL 4.



The new version of the language MQL supports a large set of functions and that are not entangled in the abundance, function names, with rare exceptions, it helps to understand which group belongs to a particular function. For example, the names of all the functions for working with arrays begin with the prefix Array, and the names of mathematical functions - with the prefix Math. In this regard, not all features in the new version of the language are exactly the same name as the old programs, but almost certainly can say that their "twin" exists in the new version.



The second point to be addressed - is that the program advisors and indicators are now divided into three mandatory functions: init (), start () and deinit (). We already wrote about this in one of the rooms Forex Magazine (Forex Magazine, June 7, 2004, ? 20 "Programming in MQL 4: Introduction.").



The majority of indicators includes a cycle in which each bar is calculated value of the indicator. Indeed, this cycle is precisely the place which is considered an indicator, but that was before this cycle, and sometimes beyond - is the code, "serving" its correct working. If you transfer the program to MQL 4, the entire cycle, most likely, no additional changes needed to be put into the body of the function start ().



Initialize variables, which takes place before completing the cycle, can be placed in the function init ().



The input parameters of the indicator, which were advertised in the MQL II with the keyword inputs, should be converted to options function init ().



Function deinit (), is likely to remain empty, as well as programs for MQL II often did not contain any action to address the effects of their work.



Third, what is required to make when transferring the program to a new version of the language MQL, - this is the syntax to bring it into conformity with the requirements of MQL 4. This process will try to describe the steps:



Step 1:



All operator brackets "begin" and "end" replaced by "(" and ")" respectively. All those who are already used when writing programs in the MQL II braces as operator brackets have already saved themselves from the extra effort at this stage of the transfer program to a new language. Next you need to remove all occurrences in the future program on MQL 4 language official word MQL II - the word "then".



Step 2:



We change all the logical operators "and", "or" and "not" to "&&", "| |" and "!" respectively. If someone has used in programs for MQL II operators "&" and "|", then do not forget, and they also translate into "& &" and "||", respectively.



Step 3:



The peculiarity of the operator "=" in the MLQ II was that in places where the result of its expected logical, comparison of values was carried out, rather than assigning a variable facing the left side of the value of the right-hand side. That is, in such situations, the operator "=" play the role of the operator "==". This is common in an "If" and "While". In MQL 4, in order to exclude the ambiguity, the developers clearly separated these two operators, and now, if you want to compare two values, use the operator "==". This observation is very important and should not be ignored in any case. Otherwise, a new version of the indicator will deliver you to the unexpected "surprises" every time instead greeted by comparing two variables of their assignment.



Step 4:



Previously, when writing programs in the MQL II could not think about how to write the name of a variable or an operator - using capital letters or lowercase? Compiler did not care whether the program is written, "While" or "while". Programmers to decide in accordance with their preferences registration code, how to write not only the names of variables, but also the official language of the word.



The new version of the language MQL, the situation has changed, and now, if you write "If", then the compiler will try to interpret it as a variable name, rather than as the beginning of the operator of choice, and could not find the announcement of such a variable, will return an error. Therefore, one should pay attention to it, and when transferring programs to MQL 4 to ensure that operators in the writing of "if", "while", "for" and others do not use capital letters. The same attention should be drawn to the fact that the register of letters plays a role in the ads of variables and functions. That is, if you declare a variable as "Var1", then it will not turn on behalf of "var1" or "VAR1". The compiler will accept each of the three names as the names of the different variables.



Given all this, the following, correct from the standpoint of MQL II, code:



Variable: Var1 (0);

Variables: Var2 (0.), Var3 (0.)



/ / ...

/ / Perform some action

/ / ...



If ((Var1
((VAR2 = 0) Or (VAR2 = 0)))

then Begin

/ / Perform some action

End;



would look like this:



int Var1 = 0;

double Var2 = 0;

double Var3 = 0;



/ / ...

/ / Perform some action

/ / ...



if ((Var1
((Var2 == 0) | | (Var2 == 0)))

(

/ / Perform some action

);



Step 5:



Fifth step could be asked to "carry" variables for the clusters where they are used, and thus divide their ads on the global and local, regarding the scope of functions. But this is one step that does not give the program new functionality, but will improve its readability and, perhaps, increase the speed of its work. At the first stage, you can do without this step, simply by placing obyavlniya all variables in global scope, that is, declaring them immediately before the announcement of the first function in your source program.



If all the above steps have been carefully executed, the lamp should compile and work.



Of course, do not predict, and while moving indicators MQL 4 there will be some moments that will require an individual approach, but, in general, the procedure for transfer of indicators with MQL II on MQL 4 should be consistent with the procedure described in the article.



For example, transport the reader is invited to compare the version indicator "median smoothing", written in MQL II and MQL 4, and published in the 15 th and 20 th issues of the journal Forex Magazine.









Alexander Ivanov

to Forex Magazine

Tuesday, March 3, 2009

Programming in MQL 4: Trading System


The history of trade in financial markets with the use of indicators has a lot of evidence that can be advantageous to carry out the transaction, based solely on the recommendation of technical analysis. Traders of this sort are one of the basic tenets of technical analysis, states that all the necessary information, including fundamental and important factors are already reflected in market price. The essence of their trade is reduced to the tracking signal to the transaction filed by a set of indicators.

The combination of an individual set of indicators, a clear interpretation of the rules filed by the signals and the methodology for determining involvement in the transaction of funds (the size of the position) are known as "trading system" (TS). These rules of the TC should be linked logically to one another, and their truth must be confirmed by the history of prices. The latter requirement is due to have one of the tenets of technical analysis, which is to say that history repeats itself.

Of course, in order to develop a logical trading system, traders will have to understand the principles of multiple indicators and to try some of them in practice. As almost every indicator has one or more parameters, they require the fitting of the selected features of the market. Market volatility, the time interval, cyclical behavior of prices, liquidity of traded goods, are just a few factors that can be attributed to the characteristics of the market. Fit parameters of the indicators is to understand and check the background of the work vehicle, built on the same indicators, but with modified parameters.

It is because of the need to fit the parameters of particular indicators chosen market and the consequent massive amount of work for many of the development of their vehicle can take many years to come, which will inevitably be accompanied by frustration, sometimes so strong that not everyone will remain loyal to the chosen destination. However, it is hoped that the outcome of the effort, nerves, time and money the trader will receive the exact set of rules and the experience of trading, which would make it fortunate financial speculator.

Ease and, more importantly, greatly accelerate the development of the TC will help your computer. Who does not like, he is best suited to carry out routine work on the results of the multiple re-TC with different parameters.

Many believe that the advisers could be used not only for the test vehicle, but also for automated, fully autonomous trade without the involvement of a trader. Author skeptical about this kind of statements, and therefore can not recommend to take full advantage of what he said about the advisers for the writing of a fully automated vehicle, operating without the participation of the trader.

Trade Information System MetaTrader 4 allows you to write and test on historical data of the so-called advisors (Expert Advisors), which are ideal for writing, mechanical trading system (MTS).

For writing the adviser should be in the editor program MetaEditor 4 select the File menu, point to New.. " We have a "Wizard adviser." After choosing the type of object as the "Advisor" and clicking the "Next", we turn to the dialog, which you need to specify the name of the created adviser, author, links to resources and parameters adviser.

For definiteness let Adviser name MyFirstExpert, graphs "Author" and "Reference" can be left unchanged.

Now add the parameters adviser. They will be used during the attachment of advisers to the schedule for sending quotes to the program some values.

The right of the table "Settings" and press "Add" button and see that the list has the option "Param1" type int (integer) with no initial value. Clicking the mouse on the table fields that correspond to this parameter, we will be able to edit its name, type, or the default value. Let us change the name of the parameter to StopLoss, its type to double, and the default value enter "5". After all this, push the button "Finish" and proceed to the generated "Wizard advisers" skeleton code future adviser.

Established skeleton present title, which indicates we have entered the second phase of "Wizard of advisers" "Name", "author" and "Reference".

For the ad title should be a global variable, and three are still empty function "init", "deinit" and "start". The function "init" has one parameter "StopLoss", which was given us in the third phase of "Wizard of advisers." It also has the type specified by us and double the default value "5".

The function "init" preserves the input parameter "StopLoss" in the global variable with a very similar name "g_StopLoss". This is done to ensure that after the conclusion of the function "init", the value of its input parameter was not lost. Since the parameter is a function of the variable visible only within the body of this function, then, is not whether we have a global variable "g_StopLoss", other options would not be able to get the input parameter value "StopLoss" function "init". Preserving the same value for "StopLoss" in the global variable "g_StopLoss", we ensure the availability of the input parameter value to all the functions of adviser to the whole duration of the program.

If the third phase of "Wizard of advisers, we have indicated a greater number of parameters, it generates a code that contains the global" doubles "for each of them. Naturally, those of the parameters that are needed only during initialization, may not have global counterparts, "and we can safely remove unnecessary global variables after the" Wizard of advisers. "

The value function "init", "deinit" and "start" has been discussed in previous issues Forex Magazine and, nevertheless, recall again that the main phase of the Adviser is in the function "start". That it is performed each time a change takes place quotes traded instrument, and it is responsible for analyzing the market situation and deal-making, based on signals of indicators included in the described vehicle.

Now, in order not to overload the article unnecessary detail, let us aside created skeleton adviser and proceed to self-study examples Adviser "MACD.mq4", supplied with the editor program MetaEditor 4. Suggest steps to consider each of the three functions, and understand the essence, an overall scheme of the advisor, which we explain in the next article.




Alexander Ivanov
to Forex Magazine

Monday, March 2, 2009

Programming in MQL 4: Options

Article about programming in MQL 4 in the previous issue of the journal Forex Magazine ended promise to consider the options - new language MQL 4 missing in MQL II. In fact, the language MQL II allows to write custom functions that are compiled by individual modules, but work with them have some restrictions that prevented the full benefit of this achievement, structured programming.

In this article we will try to explain that such a function in MQL 4, for which they want as their right to declare and use.

As noted in the previous article, the functions - it is one of the "bricks" for constructing programs. This concerns not only the language MQL 4, it refers to almost all programming languages. Programmers of all stripes use a function to create a more intuitive programming and more effective programming. If it were not for the functions (as in MQL II), often to several times during the same program to copy the code that performs the same action. Such duplication of code not only increases the labor of writing and debugging programs, it also impairs its readability. Features a large help to solve this problem.

Options can be viewed as named blocks programs that hide themselves in the details of an algorithm. Once written and debugged the function can be used in several places in the program (or even in several different programs) without much effort. They usually have a descriptive name that facilitates the understanding of its purpose. Well written and documented using the function does not require understanding of the algorithm of its work. It is as if a black box, which at the entrance to take any parameters, and on completion of their work gives no result.

Options MQL 4 can be made in two ways. First - this is the successor of custom functions, the language MQL II, is executed as a separate module. In the new version they are called "script". Second - it is writing functions in the same module as the main program for local use.

To create Script'a enough to run the wizard to create a program in the editor 4 Meta Editor and select "Script program". The wizard will guide you through the entire process of creating a custom function, after which you will be open skeleton code script'a.

To create a second type of functions is simply to describe it in the same file, where it will be used.

Language MQL 4 has three predefined function names which should not be used as the names of their own functions, it is init, deinit and start. Also, function names should not begin with numbers. Otherwise, by choosing a function name, the programmer has complete freedom.

The function can have input parameters. To specify the parameters of the function should list their names and types separated by commas in the line of ads function.

double SomeFunction (color LineColor, string LineName, int Range)

In the above example shows the definition of the function SomeFunction with three parameters: the parameter is of type LineColor color, setting LineName - type string and the parameter Range - type int.

You probably have already noticed that the front of the type of function, too. The point is that functions can not only take some parameters as input parameters, they can return values. These values can be used in different ways.

In the case where the result of the work function should be a single value, you can do so, that function will be to recover it. Suppose that our function SomeFunction must display some sort of line, and as a return value of the maximum closing price over the last few bars. Since we are talking about the functions of some of the "black box", then let's not think about the implementation of the functions just assume that it has already been written by someone, but we only known about it that:

1. The first parameter specifies the color that you need to put a line on schedule;
2. The second parameter specifies the signature to be affixed on the schedule next to the line;
3. The third parameter specifies the number of bars that will be processed by the function for finding the maximum cost-closure;
4. When the function returns a value of type double, which is equal to the maximum cost of closure on the period specified in the third parameter.

Use this function in your code will be as follows:

/ / Somewhere in the code declared variable of type double,
/ / Which will hold the greatest value closing double fHighestClose;

/ / Perform some action
...

/ / Then, to execute code "hidden" in the body function
/ / SomeFunction need her to call.
fHighestClose = SomeFunction (Yellow, "Line subscript", 50);

/ / Now the variable contains the result fHighestClose
/ / Function SomeFunction

Also, often a function return value is used to indicate the correctness of the conclusion of "hidden" in its algorithm, or occurred during the execution error. How to use it, shows a little lower.

But it is not always necessary that the function returns a result. To describe such a role exists type void. For example, the following ad features suggests that the function OtherFunction nothing to return:

void OtherFunction (int Param1)

Options can take a variety of options, and usually only part of them should be unique to address the functions of the program, as ostavshayasyachast repeated calls to the call from. For ease of use features, the opportunity to ask MQL4 built default values for parameters of functions. This means that using the function, the parameters of which already have some predefined value, we can either use them or specify your own. For ads such parameters should function immediately after him, through a sign ravno specified by the default. One important note - if you specify a default value for one of the parameters of the function, then all options facing him right in the ad must also have default values. Parameters with no default values, called "required parameters". Consider this example:

/ / This is the correct ad - all options
/ / Param2 has the right to Defaults
int SomeFunction1 (int Param1, int Param2 = 10, int Param3 = 123)
(
/ / Do something
)

/ / This is wrong ads - parameter
/ / Param2 right do not have default values
int SomeFunction2 (int Param1, int Param2 = 10, int Param3)
(
/ / Do something else
)

Accordingly, the call SomeFunction1 could be three options, indicating the importance of only the first mandatory parameter, by specifying the first two parameters, and specifying all three parameters.

/ / Somewhere in the code declared variable of type int,
/ / That will store the value returned by the function
/ / SomeFunction1
int nSomeResult = 0;

/ / Call SomeFunction1 indicating only compulsory
/ / Parameter. Other parameters and Param2 are Param3
/ / Have a value of 10 and 123, respectively
nSomeResult = SomeFunction1 (10);

/ / Call SomeFunction1 indicating the two parameters.
/ / Parameters Param3 will be a factor 123
nSomeResult = SomeFunction1 (10, 20);

/ / Call SomeFunction1 with a clear indication of all three
/ / Parameters
nSomeResult = SomeFunction1 (10, 20, 30);

Now back to the fact that through the return value of functions to communicate the user code, which can be used to determine whether the function completed, or in the process of its implementation has occurred is a mistake.

Below is the circuit function, which returns a value of type int. Condition is that if funktsiyavernula value is nonzero, then it occurred some error. If the function returns zero, then it has successfully completed its programmed algorithm:

int SmartFunction ()
(
bool bReturn = false;
/ / Do something
...
if (bReturn) (
return (1);
)
/ / Do something else
...
if (bReturn) (
return (2);
)
return (0);
)

Due to the fact that the function returns different error codes, we can diagnose the presence of errors and locate the place of its occurrence.

When writing programs are often enough to pay attention to the return code of a function. Well, that, in MQL 4 the opportunity to analyze the return code of the function, but this same procedure, and parse error occurs almost always in one scenario - namely, when an error occurs, it is necessary to inform the user as can be more informative. Why not "turn" into a separate function of the code analyzing the return value of some function?

AnalyzeIt (bool bCondition, string sModuleName, string sDescription = "Something is wrong")
(
if (bCondition) (
Alert ( "WARNING:" + sDescription + "in" + sModuleName);
)
)

In the above example shows a function that analyzes the return value of another function, and in case of error, the user is warned. Next, an example of its use:

AnalyzeIt (SmartFunction (), "MyFileName.mq4");

SmartFunction will return an error code, it is transmitted as the first parameter to the function bCondition AnalyzeIt. In the event that an error code other than zero, the user will see the message "WARNING: Something is wrong in MyFileName.mq4".

In case you need to get more clearly a description of the bug - you can use a third parameter, as is done in the following example:

AnalyzeIt (SmartFunction (), "MyFileName.mq4", "Wrong SmartFunction termination");

Now you will see the message "WARNING: Wrong SmartFunction termination in MyFileName.mq4".

Today all. We hope that this article was able to show which opens the horizons for the introduction of more flexible roles in the language MQL 4. Their skilful use will greatly facilitate the life and work of programmers writing software for the new version of the trading system Meta Trader 4.



Alexander Ivanov