# Metatrader 4 language tutorial 2 case

The second property — portfolio set compression convergence — is opposite to the previous one. Calculated interval boundaries are shown as red dotted lines, while the portfolio graph tends to move along the target function line both in and out of the calculated interval. In addition, the free downloadable data from MetaTrader accessible via the Download button is not always complete, and can contain large gaps. These combinations may be defined in advance or generated according to certain rules. Without comments megatrader even if you are the code's creator — it can be very difficult to understand what all those puzzling lines mean. The same code fragment can be used for any function.

Do you llanguage the article? Share it with others - post a link to it! Tutrial new possibilities of MetaTrader 5 Magnus. Tutorila Maro, Eclogues The portfolio principle is known from long ago. By diversifying the funds in several directions, investors create their portfolios reducing the overall loss risk and making income growth more smooth. Cae portfolio theory has gained momentum in when the first portfolio mathematical model has been proposed by Harry Markowitz.

In s, a research team from Morgan Stanley has developed the first spread trading strategy paving the way for the group of market neutral strategies. The present-day portfolio theory is diverse and complex making it almost impossible to describe all portfolio strategies in a single article. Therefore, only a small range of speculative strategies metatrader 4 language tutorial 2 case with their possible implementation metatrader 4 language tutorial 2 case MetaTrader 4 platform will be considered here.

Classic investment portfolios are usually applied at stock markets. However, such an approach does not suit Forex much since most portfolios are speculative here. They are created and traded slightly differently. As far as Forex tutlrial concerned, the portfolio trading is actually a multi-currency trading, however, not all multi-currency tutorkal are portfolio ones. If symbols are traded independently and no total result dynamics is tracked, this is a multi-symbol trading.

If several independent systems trade on a single trading account, this is a strategy portfolio. Here we will consider a portfolio trading in the narrow sense — when a synthetic position is formed out of several symbols and is managed afterwards. Portfolio development consists of the two stages: selecting symbols and calculating lots and directions for them. Here we will discuss only a few simple portfolio development methods along with algorithm samples.

In particular, we propose the ordinary least squares method OLS and principal component analysis PCA as a basis. More information can be found here: When developing a portfolio, it is usually necessary to define the desired portfolio graph behavior. Portfolio graph represents the changes of the total profit of all positions included into the portfolio within a certain time interval.

Portfolio optimization is a search for thtorial combination of lots and directions best fitting the desired portfolio behavior. For example, depending on our task, it may be necessary for a portfolio to have a recurrence to the average value or attributes of a clearly marked trend or its chart should be similar to a mrtatrader of a function. This is a multivariate linear regression equation with a zero constant term.

Its roots can be easily found using OLS. First of all, time series should be made tutprial meaning that price points should be brought to a deposit currency. In this case, each element of **metatrader 4 language tutorial 2 case** timeseries will represent a virtual profit value of a single lot of the appropriate symbol at a particular time.

Preliminary price logarithmation or using price differences are usually recommended in statistical application tasks. However, that may be unnecessary and even harmful in our case since critical overall symbols dynamics data would be destroyed along the way. The target langyage defines the portfolio graph type. The target function values should be preliminarily calculated in each point accordingly. The OLS algorithm adds A, B, C, To achieve this, caxe OLS algorithm minimizes the sum of squared deviations between the series sum and mettarader target function.

This is a standard statistical task. No detailed understanding of the algorithm operation is required since you can use a ready-made library. It may also happen that the target function contains only zero values flat portfolio. The alternative is to move an equation term to the right making it a target function receiving the ratio of -1, while the remaining terms are optimized as usual.

In this case, we equate the basket of instruments cade a selected instrument, thus creating a spread portfolio. Finally, the more advanced PCA algorithm can be used to develop such portfolios. It applies the instrument covariance matrix to calculate the coefficient vector corresponding to the point cloud cross section hyperplane with the portfolio's minimum residual variance. Again, you do not need to understand the algorithm in details here since you can use a ready-made library.

Now, it is time to implement all the ideas described above using MQL language. We will use a well-known ALGLIB math library adapted for MT4. Sometimes, issues may arise during its installation, so I will dwell more on it. If several terminals are installed on a PC, it is very important to find the correct data folder since the compiler does not see the library if it is located in another terminal's data folder.

This function will always be used in the future. It works with currency pairs, indices, futures and CFDs. If we multiply the returned function value by the current symbol price, we obtain the price of the symbol's one lot. After tutorila all contract prices in the portfolio considering lots, we langage the price of the entire portfolio. If we multiply the function value by a price difference in time, we receive profit or loss generated during that llanguage change.

The next step is calculating the virtual profit for all individual lot contracts. The calculation is implemented as a two-dimensional array where the first dimension is a point index in the calculated interval, while the second dimension is a symbol index the second dimension size can be limited by a certain number knowing that the amount of symbols in the portfolio will obviously not exceed it : First, we should store initial prices for all symbols on the left boundary of the calculated interval.

Then, the difference between the initial and final prices is calculated at each point of the calculatied interval meyatrader multiplied by the contract price. The time label strict compliance rule is used in the example above. If a bar for a certain time label is absent even at one symbol, a position is skipped and a shift is made to the next one. Managing time labels is very important for preliminary data preparation, since data misalignment on different symbols may cause serious metatrader 4 language tutorial 2 case in the portfolio.

Now that we have prepared data, it is time to send them to the optimization model. The optimization is to be performed using LRBuildZ, LSFitLinearC and PCABuildBasis functions from ALGLIB library. Next, the code fragment considering the model features should be set for each optimization model. First, let's examine the sample trend model: At first, this may seem complicated, but basically everything is **metatrader 4 language tutorial 2 case.** At the start, the linear trend function is calculated and its values are placed to the MODEL array.

The matrix is created for calculations MATRIX. Data on the virtual lantuage of all contracts from EQUITY array, as well as the target function values from MODEL array are downloaded to the last row of the matrix. The number tutoral independent regression equation variables is stored in 'variables'. LRBuildZ function is called afterwards to perform calculation. After that, the regression equation roots are written to ROOTS array using LRUnpack function.

All complex math is located metatrader 4 language tutorial 2 case the library, while you can use the ready-made functions. The main difficulty is of technical nature here and related to setting all calls correctly and preserving the data during the preparations. The same code fragment can be used for any function. Simply replace MODEL array contents with your target function. Additionally, the vertical shift should be performed to metatraddr the function be equal to zero at a zero point to ensure the calculations are correct: These examples make it easy to develop a custom function.

You can create any function type depending on your task and trading setup. The more complex the function type, the more difficult it is to select the best solution, since the market is not obliged to follow the function. Here, the function is only an approximation. You do not need a target function to create spread and return flat portfolios. For example, if you want to create a spread between two symbol baskets, the optimized basket is downloaded to the main part of the matrix, while the reference basket is used as a target function and downloaded to the last column of the matrix as a total amount: Below is a sample flat portfolio calculation where LSFitLinearC function makes the portfolio as symmetrical metattrader possible around zero within the calculated interval: Below is yet another important example of calculating a flat portfolio with the minimum variance using PCA method.

Here, PCABuildBasis function calculates the ratios so that the portfolio graph remains as compressed within the calculation interval as possible: If use trailing stops metatrader version feel overwhelmed by all these math concepts, do not worry. As I have already said, you do not need to understand all the mathematical details to develop and use portfolios.

Generally, the sequence of stages looks as follows: Now that we have obtained ROOTS array of optimal ratios using a number of procedures, it is time to metatrader 4 language tutorial 2 case the ratios into lots. To do this, we need normalization: scaling and rounding. Setting a required scale makes lots convenient to trade. Rounding is necessary to bring the lots capacity in line with broker requirements. Sometimes, it is recommended to perform normalization by portfolio total margin, but this method has serious drawbacks since the margin of individual symbols varies and can change.

Therefore, it is much more reasonable to perform normalization by a portfolio price or its volatility. Here, the portfolio price is equated to the required one via the proportions. Lot values form the final portfolio structure. Positive lots correspond to a long position, while negative lots — to a short one. Knowing the portfolio structure, we can plot its chart and perform trading operations with the portfolio. Below is a sample portfolio structure after normalization: The portfolio graph is plotted only by Close prices and displayed in a separate indicator subwindow.

In order to build the portfolio graph, we need to calculate each chart bar the same way virtual profits for separate symbols have been previously calculated. I have skipped technical aspects related to indicator buffers, formatting and the like. The sample ready-made portfolio indicator is described in the section below. Calculated interval boundaries are shown as red dotted lines, while the portfolio graph tends to move along the target function line both in and out of the calculated interval.

You can perform technical analysis of portfolio graphs similar to ordinary symbol price charts, including applying moving averages, trend lines and levels. This extends analytical and trading mettrader allowing you to select the portfolio structure metatrader 4 language tutorial 2 case forming a certain trading setup on a portfolio graph, for example correction after a trend impulse, trend weakening, exiting a flat, overbought-oversold, convergence-divergence, breakout, level consolidation and other setups.

Trading setup quality is affected by portfolio composition, optimization method, target function and selected history segment. It is necessary to know the portfolio's volatility to select an appropriate trading volume. Since the portfolio chart is initially based on a deposit currency, you can assess a portfolio fluctuation range and potential drawdown depth directly in that currency using the "crosshair" cursor mode and "pulling".

A trading system should be based on portfolio behavior properties and setup statistics. Until now, we have not mentioned the fact that 22 portfolio behavior may change dramatically outside the optimization interval. A flat may turn into a trend, while a trend may turn into a reversal. A trading system should also consider that the portfolio properties are prone to change over time. This issue will be discussed below. For more convenience, it would be reasonable to have a special Expert Advisor to perform all the routine work, including obtaining portfolio structure data, preparing synthetic positions, tracking entry levels, fixing profit and limiting losses.

We will apply the following terms concerning the EA operation: long synthetic portfolio 22 and short synthetic portfolio position where long positions are replaced with short ones and vice versa. The EA should be able to accumulate positions, track synthetic volumes, as well as perform portfolio netting and transformation. The sample EA is considered in the next section, though its structure is not explained due to the article volume constraints.

Sometimes, it is necessary to build not one but several portfolios. In the simplest case, it is needed for comparing two portfolios. Some tasks require an entire portfolio series to be built on a single history segment resulting in a set of portfolios containing certain patterns. In order to implement such tasks, the algorithm generating portfolios according tutroial a certain template is required.

The example of implementing such an indicator can be found in the next section. Here, we are going to describe only its most critical operation features. Applying the structure array is more convenient and reasonable than using separate arrays. Portfolios within the set vary by their symbol combinations. These combinations may be defined in advance or generated according to certain rules. Working with a set of portfolios may include several stages depending on a task. Let's consider the following sequence of stages here: A vertical shift is used to combine portfolios.

Portfolio is reversed when multiplied by Finally, a filter is applied by sorting and sampling by values. No detailed description of these algorithms is provided here to avoid a huge bulk of routine code. The graph shows a set of portfolios calculated by PCA model with a short period. The calculated interval boundaries are shown as the red metatrade lines. Here we can see the expansion of the portfolio set on either side of the optimization interval. The zero point is selected at the left optimization interval boundary, while the moments of reversal relative to zero and the filter application are marked by the purple dotted lines.

The thick line outlines the superportfolio consisting of the most active portfolios and thereby having a decent run from the zero point. Combining portfolios provides additional possibilities for analysis and developing trading strategies, for example diversification between portfolios, spreads between portfolios, convergence-divergence of the set of cade, waiting for twisting of a portfolio set, moving from one portfolio to another and other approaches.

The methods langjage in the current article have been implemented as a portfolio indicator and a semi-automated EA. Here you can find the instructions, download the source code and adapt it to your needs: Portfolio Modeller — portfolio developer and optimizer. It features several optimization model types with configurable parameters. Besides, you can add your own models and tutorrial functions.

There are also basic tools for the technical analysis of portfolios, as well as various chart formatting options. Portfolio Multigraph — generator of portfolio sets with the same models and parameters and additional options for portfolio transformation and filtration as well as creating a superportfolio. Portfolio Manager — EA for working with portfolios and superportfolios.

It operates in conjunction with the portfolio indicator and allows opening and managing synthetic positions as well as has portfolio correction functionality and auto trading mode based on graphical lines of virtual orders. There are many trading strategies based on applying synthetic instruments. Let's consider a few basic ideas that can be useful when creating a portfolio trading strategy.

At the same time, let's not forget about risks and limitations. The classical approach to generating a portfolio is to identify undervalued assets having a growth potential and include them to the portfolio with the expectation of their rise. The portfolio volatility is always lower than the sum of volatilities of the instruments included. This approach is good for the stock market but it is of limited use on Forex since currencies usually do not demonstrate sustained growth, unlike stocks.

When working with standard investment portfolios, it is necessary to carefully evaluate the current asset status to buy it during the price downward movement. The first and easiest option for the speculative portfolio trading is a pair trading — creating a spread of two correlating symbols. At Forex, this approach is significantly limited since even highly correlating currency pairs have no cointegration and therefore, can considerably diverge over time.

In this case, we deal *metatrader 4 language tutorial 2 case* a "broken spread". Besides, such pair trading turns into trading a synthetic cross rate since pairs with a common currency are usually included into a spread. This kind of pair trading is a very bad idea. After opening opposite positions by spread, we sometimes have to wait a very long time before the curves converge again.

The development of this approach is a multilateral spread trading when three and more currency pairs are included into spread. This is already better than pair trading since it is easier to create a more even spread with greater number of combination options. However, the same risks remain: a spread can diverge and not converge again. It is much easier to achieve good spread return on a quiet market, but strong fundamental news cause a rapid and irreversible divergence after a while.

Interestingly, if we increase the number of instruments in a spread, the divergence probability is increased as well, since the more currencies are involved, the greater the probability that something happens during some news release. Waiting for the spread to converge again would be an extremely detrimental strategy, since this works only on a quiet flat market. Spread trading has more opportunities on stock or metatrader 4 language tutorial 2 case market in emtatrader there is a fundamental connection between assets.

However, there are still no guarantees against spread gaps on the dividend date or during futures contracts expiration. Spreads can also be composed of market indices and futures but this requires consideration of exchange trading features. A dead-end branch of the spread trading is represented by a multi-lock when cyclically related currency pairs for example, EURUSD-GBPUSD-EURGBP are selected and used to form a balanced spread.

In this case, we have a perfect spread which is impossible to trade since total spreads and commissions are too high. If we try to unbalance lots a bit, the graph becomes more trend-like which contradicts spread trading, while the costs remain high enough making this approach meaningless. Spread trading drawbacks make us switch to trend models. At first glance, everything seems to be harmonious enough here: identify trend, enter during a correction and exit with profit at higher levels.

However, trend models may turn out to be not so simple and handy at times. Sometimes, a portfolio refuses to grow further and sometimes it turns down sharply. In this case, we deal with a "broken trend". This occurs quite often on short and medium-term models. The trading efficiency depends heavily on the market phase here. When the market is trendy, the system works well. If the market is flat or especially volatile, numerous losses may occur. These drawbacks make us reconsider traditional approaches.

Now, let's have a look at spread breakout and trend reversal trading methods. The common supposition is that since we cannot avoid portfolio instability, we should learn how to use it. In order to develop metatrader 4 language tutorial 2 case spread breakout setup, we need to create a very compact short-period spread with the minimum volatility in anticipation of a strong movement.

The more we compress the portfolio volatility, the stronger it "bursts out". For accelerated spread breakout, it is possible to form a setup before beginning trade sessions and before the news selecting certain intervals of a quiet megatrader. PCA optimization method is best suited for volatility compression. In this setup, we do not know in advance, in which direction the breakout is to occur, therefore, the entry is already defined when moving from the spread boundaries.

Below is a sample exit from the short-period spread channel with the spread channel boundaries highlighted: Turorial method advantages: short-period spreads are frequent on charts and the volatility after the breakout often exceeds the spread corridor width. The drawbacks: spreads are expanded during news releases and a "saw" may form when the price moves up and down a few times.

The conservative entry can be proposed as an alternative after exiting a spread corridor during the correction to the corridor boundary if possible. In order metattader create a trend reversal setup, a trend model is created, as well as turning movements and portfolio price levels are tracked. The movement direction is clearly defined but we do metatarder know in advance when the trend reverses. An internal trend line crossing, reverse correction and roll-back are tracked for a conservative entry.

Touching an external trend lamguage and a roll-back metatrader 4 language tutorial 2 case tracked for an aggressive entry. The method advantages: good entry price, convenience, extreme price instability works in favor of the setup. Disadvantages: portfolio price may go up the trend due to fundamental reasons. In order to improve the situation, we may enter in fractional volumes from multiple levels. A similar setup can be implemented using square root parabolic function model.

The setup is based on a well-known property: when the price reaches a theoretical limit of a market distribution range, its further movement is hindered. Like in other cases, the target optimization function is adjusted for the current market distribution. If the markets had featured normal Gaussian distribution, the time-based square root law would have always worked perfectly but since the market distribution is fractal and non-stationary in its nature, the situational adjustment is required.

This setup is perfect for adapting to mid-term volatility. However, just like in case of a trend setup, a portfolio price may move upwards due to fundamental factors. The market is not obliged to follow any target function behavior, but neither it is obliged to deviate from it as well. Some degree of freedom and duality remain at all times. All trade setups are not market-neutral in the absolute sense but are based on some form of technical analysis.

The dual *metatrader 4 language tutorial 2 case* of trend and flat can be seen below. A trend model looks similar to an uneven flat on a bigger scale: Apart from symbol combination and model type, location of estimated interval boundaries is of great importance when developing a portfolio. When configuring the portfolio, it might be useful to move the boundaries and compare the results. Good choice of boundaries allows finding portfolios that are more suitable in terms of a trading setup.

If a portfolio position enters a drawdown, it is possible to correct the portfolio without closing existing positions. Shifting the boundaries changes the portfolio curve adapting it to a changing situation. Positions should be corrected accordingly after re-arranging the portfolio. This does not mean that the drawdown will decrease in a moment, but the corrected portfolio might become more efficient. Next, let's consider some properties of portfolio sets and their possible applications in trading systems.

The first property of portfolio sets to catch the eye is a tutoriak expansion, or divergence of portfolios with distance from the zero point. It would be only natural and reasonable to use this property for trading: buying rising portfolios and selling falling ones. The second property — portfolio set compression convergence — is opposite to the previous one. It happens after czse expansion. Expansion and compression cycles suggest that this behavior can be used tutoorial open synthetic positions in anticipation of returning to the center of the set after reaching an alleged highest degree of expansion.

However, the expansion highest degree always vary, and it is impossible to predict the final boundaries of the set curves expansion. Applying various target functions, filtration parameters, reversals and languwge provides good opportunities for experimenting and searching for efficient mdtatrader setups. Generally, all setups can be divided into two classes: trading breakouts and trading roll-backs. Below is an example of the first type trading setup with a reversal and shift of a portfolio set: Another recurring portfolio property is a set twist self-crossing.

Typically, this corresponds to a change of a market trend. If we trade in anticipation of an expansion of portfolios, a twist is a negative effect requiring the set re-arrangement. For other strategies, crossing of some portfolio curves can be used to identify promising and played-out portfolios. Besides, it is necessary to consider a distance traveled, levels, position in a set and position relative to the target function.

We have not focused out attention on the volume management issue up until now, though this is a critical part of any trading system. Generally, we can describe the following approaches: Specific volume management method should be selected considering trading system features. When planning a profit and a drawdown, your calculations should be based on a portfolio volatility. In the simplest case, the portfolio volatility can be evaluated as the movement range of its graph within a certain segment.

It is much better to evaluate volatility not only metatrdaer the optimization interval but on the previous history as well. Knowing the portfolio volatility, it is possible to calculate Discovered Secrets of JohnPaul77 Forex Signal Services theoretical value of the maximum total drawdown at a series of positions.

Traditionally, we caution against too frequent tutorizl volume adding. The total funds allocated for a portfolio coverage on a trading account should be able to withstand unfavorable movement considering all additional positions. Multi-portfolio trading means systematic portfolio selection and consolidation. If one portfolio is bought and another one is added to it, this may have a positive diversification effect if the portfolios have noticeable differences.

But if portfolios are correlating, this may have a negative effect, since they both may find themselves in a drawdown in case of an unfavorable movement. Normally, you should avoid adding correlating portfolios. At first glance, trading spread between two correlating portfolios may seem to be very promising but closer examination shows that such spreads are no different from usual spreads since they are not stationary.

For some strategies, the entry point is of critical importance. For example, if a strategy applies extreme prices before a trend reversal or correction, a period suitable for entry is very short. Other strategies are more reliant on the optimal calculation of a position adding system and portfolio selection principle. In this case, individual portfolios may enter a drawdown, but other more efficient portfolios within the consolidated series adjust the overall result. Portfolio trading advantages: optimization allows you to create a tytorial curve according to your preferences, as well as form a desired trading setup and trade it similar to trading symbols on a price chart.

However, unlike trading portfolios, buying and selling conventional assets leave traders in passive kanguage since they metatader only able to accept the current price chart or avoid using it. Besides, as the situation evolves, traders can adjust their portfolios to new market conditions. Generally, this is a rather specific approach in trading. Here we have only made an introductory overview of the portfolio properties and working methods. If you want to perform deeper studies of portfolio trading systems, I recommend using the MetaTrader 5 platform for that, while market distribution properties should be studied in specialized statistical packages.

Translated from Russian by MetaQuotes Software Corp. False trigger is typical for low quality performance of the main logic of a trading robot. Ways of solving the specified problem are considered in this tuforial. The article describes the application of text files for storing dynamic objects, arrays and other variables used as properties of Expert Advisors, indicators and scripts. The files serve as a convenient addition to the functionality of standard tools offered by MQL languages.

The article describes how currency pairs can be trading software for binary options one touch into groups baskets csse, as well as how to obtain data about their status for example, overbought and oversold using certain indicators and how to apply this data in trading. Tutorial to build a Binary Options strategy an test it in Strategy-Tester of MetaTrader 4 with Binary-Options-Strategy-Tester utility from marketplace.

MetaTrader 5 Examples Indicators Experts Tester Trading Trading Systems Integration Indicators Expert Advisors Statistics and analysis Interviews MetaTrader 4 Examples Indicators Experts Tester Trading Trading Systems Integration Indicators Expert Advisors Statistics and analysis. The **metatrader 4 language tutorial 2 case** principle is known from long ago.

Some definitions applied in this article are as follows:. Portfolio basket, synthetic instrument — set of positions at multiple trading instruments with calculated optimal volumes. Positions remain open for some time, are tracked as one and closed with a common financial result. Synthetic volume — number of synthetic positions number of times the portfolio was bought or sold.

More information can be found here:. Principal component analysis PCA. When developing a portfolio, it is usually necessary to define the desired portfolio graph behavior. Three portfolio types trend, flat, function :. A portfolio can be represented by the following equation:. F — target function set by values in time lanuage points.

First, separate portfolios within a set are calculated according to previously described principles. Combining portfolios at a zero point is needed for ease of analysis. To do this, a point, at which all portfolios are equal to zero, is selected. Reversing portfolios relative to a zero level can also be useful to simplify analysis. Falling portfolios become growing ones after lots are inverted. Filtering portfolios within a set means selecting the best portfolios by some criterion, for example a growth speed, deviation from zero, position within a set relative to other metatradeg.

So, the the best portfolios selected and combed into a basket of portfolios, or a superportfolio superposition of portfolios. Warning: All rights to these materials are reserved by MQL5 Ltd. Copying or reprinting of these materials in whole or in part is prohibited. False trigger protection for Trading Robot. Profitability of trading systems is defined not only by logic and precision of analyzing the financial instrument dynamics, but also by the quality of the performance algorithm of this logic.

Using text files for storing input parameters of Expert Advisors, indicators and scripts. Working with currency baskets in the Forex market. How to build and test a Binary Options strategy with the MetaTrader 4 Strategy Tester. Free technical indicators and robots. Articles labguage programming and *metatrader 4 language tutorial 2 case.* Order trading robots on the Freelance.

Market of Expert Advisors and applications. Low latency forex VPS. MetaTrader 5 Trading Platform. MetaTrader 5 User Manual. About Timeline Terms and Conditions. Join us — download MetaTrader 5! CopyrightMQL5 Ltd. Calculating virtual profit for portfolio symbols with single lots Graph calculation and trading using the portfolio Calculating charts of separate portfolios.

## Tutorial 2 - MetaTrader 4 Trade Window

Portfolio trading in MetaTrader 4. above using MQL language. strategy with the MetaTrader 4 Strategy Tester. Tutorial to build a Binary Options. MetaTrader 4 in brief In this case MetaTrader should not Languages and then choose the language. MetaTrader 4 Expert Advisors MetaTrader is a property of MetaQuotes Software Corp. MetaQuotes Language 4 color static case true.