Konstantin Boykachev

CEO Proforexea LLC

Honest Coder

Professional Trader


No products in the cart.

Konstantin Boykachev

CEO Proforexea LLC

Honest Coder

Professional Trader

Blog Post

Portfolio trading in MetaTrader 4

Magnus ab integro saeclorum nascitur ordo
Publius Vergilius Maro, Eclogues


Portfolio investment principle known from very early times. Distributing funds on several fronts, the owner thus creates a portfolio reduces the overall risk of loss due to diversification and makes earnings growth smoother.
Significant development of portfolio theory received after year 1950 Harry Markowitz formulated the first mathematical model of the portfolio. Later, in the 1980 ‘s, a group of researchers from Morgan Stanley established the first spread trading strategy that has opened a new direction: market-neutral strategies. Modern portfolio theory is diverse and complex, and the number of cases portfolio strategies hardly indescribable. This article will be considered only a small range of speculative strategies and sample implementation in MetaTrader 4.

some definitions that apply to this article:

  • portfolio (shopping cart, a synthetic tool) is a set of positions on several trading tools with optimal amounts. Position held for some time are tracked as a whole and closed with a total financial result.
  • portfolio Adjustment (baskets, synthetic instrument) is the change in the composition of instruments and/or their volumes in the portfolio to minimize losses or commit intermediate results.
  • Synthetic volume is the number of synthetic position (how many times the portfolio was purchased or sold).
  • Virtual profit/loss — the financial result, which may be obtained when you hold positions in a certain time interval.

the stock market usually work with classic investment portfolios.
On the foreign exchange market this approach almost never works and portfolios here are speculative, they are created and traded slightly differently. In relation to the Forex market portfolio trading can be named the multi-currency trading, but not all Multicurrency strategy are, strictly speaking, portfolio.
If the instruments are traded independently and without tracking the dynamics of the overall result, it will be multiinstrumentalnaja trade. Also common approach on one trading account traded several independent systems, such an approach could be called portfolio management strategies. The article will be considered by the trade portfolio in the narrow sense when several instruments formed a synthetic position and next comes this management position.


Build portfolio includes two phases: the selection of tools and calculation of lots and directions for the selected toolbar. There are numerous ways of formation of portfolios, the article does not claim to universality, so here are some simple methods and examples of algorithms. In particular, it is proposed as a basis to use the method of least squares (OLS) and principal component analysis (CIM). More details about these methods can be found here:

when creating portfolio typically define desired behavior graphics portfolio.
Schedule of portfolio changes is the total profits of all items included in the portfolio, at a certain time interval. Portfolio optimization is a combination search lots and directions that best suit the desired behavior of the portfolio. For example, depending on the task, you can require that the portfolio had to return to the mean, or have signs of a pronounced trend, or that his schedule was similar to the graph of some function.

illustration to three types of portfolios (trend, flat, function):

Portfolio can be presented in the form of an equation of the following form:

A * k1 + k2 + B * (C) * k3 + … = F


A, B, C, … is a time series relevant INCE trumentam in bag

k1, k2, k3 …-lots in tools (positive-negative purchase-sale)

F-function (specified values, in pixels, of the time series)

this equation linear multifactor
regression with zero free Member, and its roots are easy to find using OLS. Pre need to do time series of comparable, i.e. transfer price points in the deposit currency. Then each element in each time series will be the value of virtual profit from a single lot of the instrument at a particular time. Statistics applications typically recommend a preliminary price or taking logarithm of price differences, but here it would be not only unnecessary but harmful, as will destroy important information about the joint dynamics of instruments.

function determines the appearance of the graphics on which chart would look like.
The value of the objective function you must first calculate at each point accordingly. For example, if you create a simple growing portfolio (portfolio trend), the target function will have values: 0, 1, 2 * S * S * S 3 and so on, where S is the increment, money value, which should grow the portfolio with every bar on the specified interval. MNCS algorithm adds time series A, B, C, … so that their total amount sought to repeat the schedule of the target function. For this algorithm MNCS minimizes the sum of squares of deviations between the series and the target function. This standard task statistics, a detailed understanding of the algorithm, not necessarily because you can use ready-made library.

special situation occurs when the target function contains only null values (flat portfolio). In this case, you must enter an additional restriction on amount of coefficients, for example: k1 + k2 + k3 + … = 1 to circumvent degenerate solution of regression equation with zero roots. An alternative approach: move one Member to the right side of the equation, which itself becomes the target function and receive the -1 ratio, and the remaining members will be optimized as usual.
In this case, consider shopping cart tools to one selected symbol, i.e. create a portfolio of spredovogo type. Finally, you can use to generate these portfolios more advanced algorithm of CIM, which through the matrix covariances instruments corresponding coefficients vector counts hyperplane section point cloud with a minimum residual portfolio variance. Here again you should not worry about the detailed understanding of the algorithm, since you can use ready-made library.

Algorithms Now described ideas to be realized in MQL. Will be known for the math library, ALGLIB adapted for MT4. Sometimes there are issues with its installation, so it’s worth staying on this a bit more. If your computer has more than one terminal, it is very important to determine the correct data folder because the compiler will not see the library if it lies in the data folder of another Terminal.

ALGLIB library:

  1. download library (https://www.mql5.com/ru/code/11077), unpack the zip file;
  2. open the folder inside the folder will include Math;
  3. run the Metatrader 4 Terminal, where you want to put the library;
  4. select menu: File-Open data catalog data folder opens Terminal;
  5. open in this folder a subfolder of MQL4 and next subfolder
  6. from the unpacked Library copy folder Math in the Include folder of the Terminal;
  7. check are: *.mhq files must be within MQL4IncludeMathAlglib.

the first key step: time series transfer of price points in the deposit currency.
For this task you will need to write a special function that will calculate the value of the contract at any time. The standard function MarketInfo identifier for this are not entirely suitable, because it can get the correct value only for the last bar on the chart, and in the history of the deviation will inevitably arise, because the value of some tools is constantly changing. It is very important to accurately convert data series, otherwise can be serious distortions in the portfolio.

is an example of a function that will calculate the value of the contract is below:

double ContractValue (string symboldatetime, int ') {
   dou ble value =MarketInfo (symbol,MODE_LOTSIZE);                     
    string quote =SymbolInfoString(symbol,SYMBOL_CURRENCY_PROFIT);     

   if(quote! ="USD") {
      string direct = FX_prefix + quote +"USD"+ FX_postfix;                
      if(MarketInfo (directMODE_POINT)! =0) {
          int shift =(iBarShift direct , period, time);                    
          double price =iClose(direct, period, shift);                   
         if(price >0) value * = price;                                   
         string indirect = FX_prefix +"USD"+ quote + FX_postfix;           
         int shift =iBarShift(indirect, period, time);                  
          double price =iClose(indirect, period, shift);                 
         if(price >0) = value/price;                                   

   if (Chart_Currency! ="USD") {
      string direct = FX_prefix + Chart_Currency +"USD"+ FX_postfix;       
      if(MarketInfo (directMODE_POINT)! =0) {
          int shift =iBarShift (dir ECT, period, time);                    
          double price =iClose(direct, period, shift);                   
         if(price >0) = value/price;                                   
         string indirect = FX_prefix +"USD"+ Chart_Currency + FX_postfix;  
         int shift =iBarShift(indirect, period, time);                  
          double price =iClose(indirect, period, shift);                 
         if(price >0) value * = price;                                   


this function will continuously be used in the future. It works not only with currency pairs, but with indexes, futures and CFD, and also takes into account the prefixes and suffixes for currency pairs (FX_prefix, FX_postfix) that use some brokers.  The result translates into a target currency Chart_Currency. If the return value of the function, multiply the current price tool, you get the value of one lot of this tool.
Totaling the value of all contracts in the portfolio, taking into account the cost, get lots total portfolio. If the value of the function multiplied by the difference in time it will get a profit or loss, the resulting price change.

the next step: calculation of virtual profit for all contracts for individual lots.
This is a two-dimensional array, the first dimension which is the index of the point in the current range, and the second dimension is the index tool (dimension for the second dimension you can limit some number, knowing that the number of instruments in a portfolio are notoriously It will not exceed):

double EQUITY[][100];

First remember the initial prices for all tools (on the left border of the settlement interval), then at each point where settlement interval calculate the difference of initial and final prices, multiply by the value of the contract. Each time the loop one time interval then move right:

   for(int i =0; (i) + constants variables <; i ++) {
      int shift =iBarShift(SYMBOLS[i]Timeframe, zero_time);               
      opening[i]=iClose(SYMBOLS[i]Timeframe, shift);                     
     } points =0;                                                             
    datetime current_time = zero_time;                                      
   while(current_time < = limit_time) {
      bool skip_bar =false;
      for(int i =0; (i) + constants variables <; i ++)                           
         if((iBarShift SYMBOLS[i]Timeframe, current_time,true) ==1) skip_bar =true;                                               
      if (! skip_bar) {points ++;                                                       
         Times[points-1]= current_time;                                   
         for(int i =0; (i) + constants variables <; i ++) {
             int shift =(iBarShift SYMBOLS[i]Timef Rame, current_time);      
            closing[i]=iClose(SYMBOLS[i]Timeframe, shift);               
            double CV = ContractValue (SYMBOLS[i]current_time, Timeframe);  
            profit[i]= ([i]closing-opening[i]) * CV;                        
            EQUITY[points-1i]= profit[i];                                
           }} current_time + = Timeframe *60;                                        

this code: zero_time-time left border settlement interval, limit_time is the time of the right border of the accounting interval Timeframe — the number of minutes in one bar working timeframe, points-total number of found points in the estimated
interval. This example uses a rule of strict compliance timestamps, and if at least one missing tool bar for certain timestamp, then the position is ignored and is done move to the next position.
Timestamp control is very important to preprocess data, as data synchronization on different instruments can lead to serious distortions in the portfolio.

Sample data prepared for a portfolio of three instruments and independent function (parabola square root):

03.08.16 14:00 0 0 0 0
03.08.16 15:00 -61.34 -155 230.06 10.21
03.08.16 16:00 -82.04 -433 219.12 14.43
03.08.16 17:00 -39.5 -335 356.68 17.68
03.08.16 18:00 147.05-230 516.15 20.41
03.08.16 19:00 169.73-278 -567.1
22.82 03.08.16 20:00 -14.81 -400 -703.02 25
03.08.16 21:00 -109.76 -405 -753.15 27
03.08.16 22:00 -21.74 -409 -796.49
28.87 03.08.16 23:00 51.37-323 -812.04
30.62 04.08.16 00:00 45.43-367 753.36 32.27
04.08.16 01:00 86.88-274 -807.34
33.85 04.08.16 02:00 130.26-288 -761.16
35.36 04.08.16 03:00 -1 321.92 94 -1018.51
36.8 04.08.16 04:00 148.58-205 927.15 38.19
04.08.16 05:00 -187 133 824.26 39.53
0 04.08.16 6:00 243.08-249 -918.82
40.82 04.08.16 07:00 325.85-270 -910.46
42.08 04.08.16 08:00 460.02 -476 -907.67
43.3 04.08.16 09:00 341.7-671 840.46 44.49

now, having prepared the data, you can send them in an optimization model.
Optimization will perform using the functions LRBuildZ, LSFitLinearC and PCABuildBasis from the library, ALGLIB. For a description of these functions (pretty meager, but generally friendly) can be found inside the library itself and on the official website of the project here: http://www.alglib.net/dataanalysis/linearregression.php and here: http://www.alglib.net/dataanalysis/principalcomponentsanalysis.php.

to get started with the library you want to connect it:


next to each model of optimization you want to write your code snippet with the peculiarities of the model. First, let’s look at an example build trend model:

   if (Model_Type == trend) {
      int info, i, j;                                                                                  
      CLinearModelShell LM;                                                                          
      CLRReportShell AR;                                                                             
      CLSFitReportShell report;                                                                      
      CMatrixDouble MATRIX (points + variables1);                                                      
      if (Model_Growth ==0) { Alert("Zero model growth!"); error =true; return; }                       
      for(j =0; j; j ++ < points) {
         double x = (double) (j)/(points1)-Model_Phase;                                                  
         if(Model_Absolute) x =MathAbs (x);                                                            
         MODEL[j]= Model_Growth * x;                                                                    
       double zero_shift =-MODEL[0]; if (zero_shift! =0), for(j =0; j; j ++ < points) MODEL[j]+= zero_shift;   
      for(i =0; i; i variables < ++) for(j =0; j; j ++ < points) MATRIX[j]. Set (i, EQUITY[j,i]);               
      for(j =0; j; j ++ < points) MATRIX[j]. Set (variables, MODEL[j]);                                     
      Calglib: LRBuildZ (MATRIX, points, variables, info, LM, AR);                                         
      if(info0 <) { Alert(' Error in regression model! "); error =true; return; } CAlglib: LRUnpack (LM, ROOTS, variables);                                                         

at first reading it may seem complicated, but it’s simple. First, calculate the linear trend function and its values are placed into the array MODEL, while Model_Growth parameter specifies the amount of gain for the entire calculation interval (how to grow the portfolio in deposit currency). The parameters Model_Absolute and Model_Phase optional and not yet at this stage. For the calculation of the MATRIX is created into which data is loaded virtual profits all contracts from an array of EQUITY, as well as the objective function values from an array of MODEL in the last row of this matrix. The number of independent variables in the regression equation is stored in the variable variables. It then calls the LRBuildZ function, which performs the calculation, then the roots of regression equations are written in an array of ROOTS by using LRUnpack. All the complicated math is inside the library, you can use the existing features. The complexity here is purely technical and is to correctly register all calls and do not lose data when preparing.

This same code snippet can be used for any given function, it is enough to replace the contents of the array MODEL to its target function. For example, the calculation of a parabolic function square root:

      for(j =0; j; j ++ < points) {
         double x = (double) j/(points1)-Model_Phase;         
         int sign = (int) MathSign (x);                         
         if(Model_Absolute) sign =1;                         
         MODEL[j]= sign * Model_Growth *MathSqrt(MathAbs (x));   

and here’s an example of a more complex function, the sum of the linear trend and harmonic oscillation:

      for(j =0; j; j ++ < points) {
         do uble x = (double) (j)/(points1) * Model_Cycles-Model_Phase;  
         if(Model_Absolute) x =MathAbs (x);                         
         MODEL[j]= Model_Amplitude *MathSin(2M_PI * x);              

in the latter example, you can adjust the amount of the trend by using the Model_Growth and amplitude fluctuations using the Model_Amplitude, with a set number of cycles of oscillations using Model_Cycles and do offset phase fluctuations using the parameter Model_Phase.

Optional for correctness of calculations to do the vertical offset to zero point function has a zero value:

    double zero_shift =-MODEL[0];   
   if (zero_shift! =0),              
      for(j =0; j; j ++ < points) MODEL[j]+= zero_shift;

Using these examples, you can create your own function to arbitrary types. Type can be any function, depending on the specific issue to be solved, and the trading Setup. Of course, the more complex type of functions, the harder it will be to choose the best solution, because the market is not obliged to behave according to any function, it is only a approximation.

to build spredovyh and return fljetovyh portfolios target function is not needed. For example, to build a spread between two baskets, basket optimiziruemaja toolbar is loaded in the main part of the matrix, and the reference basket stands instead of objective function and loaded into the last row of the matrix sum:

   for(i =0; i; i variables < ++)                    
      for(j =0; j; j ++ < points) MATRIX[j]. Set (i, EQUITY[j,i]);           
   for(i = variables; (i) + constants variables <; i ++)  
      for(j =0; j; j ++ < points) MODEL[j]+ = EQUITY[j,i]* LOTS[i];

an example of calculation of flat portfolio where the function LSFitLinearC makes portfolio maximally symmetric around zero within the accounting interval:

   if (Model_Type == fitting) {
      int inf o, i, j;                                                                        
      CLSFitReportShell report;                                                            
      CMatrixDouble TECHNIQUE (1+ variables 1);                                              
      CMatrixDouble MATRIX (points, variables);                                              
      ArrayInitialize (MODEL,0);                                                            
      TECHNIQUE[0]. Set (variables1);                                                       
      for(i =0; i <; i ++ variables) TECHNIQUE[0]. Set (i1);                                    
      for(i =0; i; i variables < ++) for(j =0; j; j ++ < points) MATRIX[j]. Set (i, EQUITY[j,i]);     
      Calglib: LSFitLinearC (MODEL, MATRIX, TECHNIQUE, points, variables1info, ROOTS, report);  
      if(info0 <) { Alert(' Error in linear fitting model! "); error =true; return; }}

and another important example of calculation of flat portfolio with minimum variance of the CIM method. Here the function PCABuildBasis calculates the coefficients so that the portfolio schedule was compressed in the maximum estimated range:

   if(principal == Model_Type) {
      int info, i, j;                                                                        
      double Var[];                                                                        
      ArrayResize (VAR, variables);                                                          
      VECTOR CMatrixDouble (variables variables);                                           
      CMatrixDouble MATRIX (points, variables);                                              
      for(i =0; i; i variables < ++) for(j =0; j; j ++ < points) MATRIX[j]. Set (i, EQUITY[j,i]);     
      Calglib::P CABuildBasis (MATRIX, points, variables, info, VAR, VECTOR);                     
      if(info0 <) { Alert(' Error in principal component model! "); error =true; return; }     
      for(i =0; i <; i ++ variables) ROOTS[i]= VECTOR[i][variables-1];                          

If you are reading this article you have a feeling of confusion — do not despair: as was mentioned earlier, don’t necessarily understand mathematical insides to build portfolios and trade them. The General sequence of steps is as follows:

1 virtual profit for Calculation Tools portfolio with individual lots of
2 calculation of values of the objective function
3 Algorithm Optimizing lots
4 portfolio volume Normalization
5 Calculation chart and trading portfolio

to the current time by using a series of procedures was received an array of optimal coefficients of ROOTS. Now you need to turn the odds in lots. This requires a normalization procedure: scaling and rounding.
Scaling need to make lots of easy to trade, i.e. to choose the desired scale. Rounding is necessary to bring the bitness of lots in accordance with the requirements of the broker. Sometimes recommend normalization on overall margin portfolio, but this method has significant disadvantages (as margin of individual instruments is not tantamount to and may vary), it is much better to do normalization on portfolio value, either on its volatility.

simple example of normalization algorithm on portfolio value:

       double total_value =0;                                                                         
      for(int i =0; (i) + constants variables <; i ++) + total_value = closing[i]* ContractValue (SYMBOLS[i]limit_time, Timefra me) *MathAbs (LOTS of[i]);   

      if(total_value =0) { Alert("Zero portfolio value!"); error =true; return; } scale_volume = Portfolio_Value/total_value;                                                     

      for(int i =0; (i) + constants variables <; i ++) LOTS of[i]=by NormalizeDouble (LOTS of[i]* scale_v olume, Lots_Digits);

Here the portfolio value is equal to the required through proportions. Portfolio_Value-portfolio value required,-the total value of the portfolio total_value with default coefficients, scale_volume is a scaling factor, Lots_Digits-bitness lots LOTS — an array of lots suitable for trading.

value of the lots is the ultimate structure of the portfolio. Lots of long position correspond to positive, negative lots — a short position. Knowing the structure of the portfolio, you can build his schedule and to execute trades with a portfolio. An example of the structure of the portfolio after normalization:

EURCAD Lot -0.07 0.11 -0.11

schedule of portfolio will be formed only on price closing, and for understandable reasons, it will be built in a separate indicator. To build the chart portfolio, you need to calculate each bar chart is exactly the same as previously calculated virtual profit for individual instruments, but now they will be considering embezzled lots:

   for(int j = draw_begin; j > = draw_end; j-) {
       double profit =0;                                                                       
      for(int i =0; i <; i ++ variables) {
         if(Fast_Period >0 & & Slow_Period >0 & & number! = N_TOTAL) {
             int shift =(iBarShift SYMBOLS[i]Period(),Time[j]);                                
            double CV = ContractValue (SYMBOLS[i]Time[j]Period());                            
             double fast =iMA(SYMBOLS[i]Period(), Fast_Period,0MODE_SMAPRICE_CLOSE, shift);   
             double slow =iMA(SYMBOLS[i]Period(), Slow_Period,0MODE_SMAPRICE_CLOSE, shift);   
            profit + = (fast-slow) * CV * LOTS of[i];                                                  
             int shift =iBarShift(SYMBOLS[i]Period(),Time[j]);                                
             double closing =iClose(SYMBOLS[i]Period(), shift);                                
            double CV = ContractValue (SYMBOLS[i]Time[j]Period());                            
            profit + = (closing-OPENINGS[i]) * CV * LOTS of[i];                                        
           }} BUFFERS[number]. buffer[j]=by NormalizeDouble (profit,2);                                   

in this code snippet, you can see that the chart is built on a plot between the start and end bars: draw_begin and draw_end. When the value of the portfolio is the sum of the profit and loss on all instruments that are calculated as the difference in price, multiplied by the value of the contract and the previously calculated lot. Technical routine points related to the indicator buffers, formatting and so on, are omitted here. An example of a finished portfolio indicator is available in the following section.

build Example graphics portfolio (basement window indicator) with cash on delivery schedule target functions:

in this example as the target function is a parabola, which is made of a square root of symmetric
relative to the origin (Model_Absolute = true). Border settlement interval are marked on the graph red dotted lines, the portfolio schedule tends to move along the lines of the objective function, and, as you can see, both inside and outside the settlement interval.

Graphics portfolios are amenable to technical analysis in the same way as conventional charts trading instruments: you can put Ma, trend lines and line levels.
This expands the possibilities for analysis and trade, gives the possibility to pick up the structure of the portfolio so that the graph of the portfolio formed a certain desired trade Setup, for example: after correction of a trend impulse, breaking the trend of flat,
overbought-oversold, convergence-divergence, breakout and consolidation level, other custom. On the quality of trade setapov influence: composition of portfolio optimization method, objective function, and selected site history.

when working with portfolios is very important to know its volatility to select an adequate volume for trade. Since the portfolio schedule originally built in the deposit currency, using “crosshair” cursor mode by “pulling” evaluate potential oscillation depth drawdown portfolio directly in the deposit currency.

trading system should be based on the behavior properties of portfolios and setapov statistics. Until this moment not mentioned that overseas portfolio behavior optimization interval can change significantly. Flat may change the trend, and the trend may go into a u-turn. Trading system must take into account the fact that it is impossible to reliably guarantee the preservation properties portfolio in the future. This issue has to be discussed further.

transactions with a portfolio is the purchase/sale-all instruments in a portfolio with calculated amounts. For convenience, it is advisable to have the Special Adviser, which will assume all the routine work: getting information about a portfolio structure and preparation of synthetic positions, tracking levels for logging, record profits limitation of damages. In the context of the work of the expert advisor will have the meaning of the terms: long synthetic portfolio position and short synthetic positions on the portfolio (in which Longhi change on shorts and vice versa). Adviser should be able to accumulate positions track synthetic volumes, perform netting and the transformation of the portfolio. An example of such Advisor is available in the following section,

but his device does not comment here for reasons of economy seats.

an example of a simple minimalistichnogo interface to portfolio adviser:

sometimes you need to build not one, but multiple portfolios. In the simplest case, it is the task of comparing two portfolios. Some tasks require constructing a series of portfolios on one period of history, and the result of these builds will bundle of portfolios, in which there may be certain patterns. To implement these tasks require an algorithm that generates portfolios with a specific pattern. The following section provides an example of a complete implementation of this indicator, here only key moments of his work.

for storing data, many portfolios must organize an array of structures, for example:

struct MASSIVE
   {string symbol[MAX_SYMBOLS];     
   double lot[MAX_SYMBOLS];        
   string formula;                 
   double direction;               
    double filter;                  


in this code snippet, DIM_SIZE sets the maximum size for storing portfolios. The structure is arranged as follows: symbol is an array of tools portfolio, a lot — an array of lots for portfolio tools, formula is a text string with the formula portfolio direction-the direction to the portfolio (long or short), filter — the filter sign ( included/excluded). Using an array of structures easier and more logical than separate arrays.

For buffer storage arrays for graphics portfolios too conveniently create an array of structures:

struct STREAM { double buffer[];};     

Portfolios in the beam will vary its composition, i.e., combinations of instruments. These combinations can be spelled out in advance or be generated on certain rules. Working with a bunch of portfolios can include several different phases, depending on the specific issue to be solved. In this case, consider the following sequence of steps:

1 Calculation charts of individual portfolios
2 Combining beam portfolios in the zero point
3 Coup portfolios relative to the zero
4 filter lift portfolios
5 Summarizacija-formation of superportfelja

First consistently calculated separate portfolios in a beam on the previously described principles. Combining portfolios in the zero point is needed for ease of analysis. For this you select the point at which all the portfolios will accept a null value. Coup portfolios relative to the zero level can also be fit for ease of analysis, while falling briefcases are becoming increasing after inverting lots. Filtering portfolios in the beam is a selection of the best portfolios on one or another criterion, e.g., growth rate, deviation from zero, the status of the beam relative to other portfolios.
The final outcome is the choice of the best portfolios and combining them into a basket of portfolios is superportfel (you can call it superposition portfolios).

next picture illustrates these steps:

the combination of portfolios is achieved due to vertical shear. The coup of the portfolio achieved multiplied by -1. A filter is implemented sorting and sample values. A detailed description of these algorithms are not given here, as it would contain a lot of routine code.

example of beam based on portfolios above principles:

Here the graph formed by a beam of portfolios, calculated according to the CIM model with a short period. Border settlement interval shtrihpunktirnymi red lines. The graph shows the beam extension portfolios on either side of the interval optimization. Zero point was selected at left margin optimization interval, and purple dotted lines marked the time of zero and the time of relative coup with the filter applied. A bold line is marked by the superportfel, composed of some of the most moving portfolios and as a consequence has decent acceleration from zero.

Combining portfolios offers additional opportunities to analyze and create trading strategies, such as: diversification between portfolios, spreads between portfolios, convergence-divergence beam portfolios, waiting twist beam portfolios, switching from portfolio to portfolio and other approaches.

implementation examples described in this article are implemented as methods of portfolio indicator and semi-automatic drag. Here you can see the instructions, download the sources, to study and adapt to fit your tasks:

  • Portfolio Modeller-Builder-portfolio optimizer. Has several types of optimization models with custom settings, you can append your own models and trust functions, there are basic tools for technical analysis of portfolios, different options for formatting graphics.
  • Portfolio Multigraph-generator portfolio beams using the same models and options, with additional options for filtering and transformation of portfolios and compile superportfelja.
  • Portfolio Manager is an advisor to work with portfolios and superportfeljami, works in conjunction with the portfolio indicator allows you to open and manage synthetic positions, has the functionality of adjusting portfolios, has
    Auto-graphics-based trade virtual lines of orders.

download link: https://www.mql5.com/ru/code/11859

trading strategies there are a great variety of trading strategies, based on the use of synthetic instruments. Let’s look at some basic ideas that may be useful when creating a portfolio trading strategy. When you do this, don’t forget about the risks and constraints.

the classic approach to compiling the portfolio: identify undervalued assets with the prospect of growth and include them in a Briefcase, waiting for rising costs.
Portfolio volatility is always less than the sum of its volatilnostej tools. This approach is good for the stock market and the Forex market has severely limited use as currency have usually no sustained growth, as have shares.

Long-term portfolio Warren Buffett:

to work with the classic investment portfolios need to very carefully evaluate the current state of assets, to buy assets not at the peak of growth and reduction.

the first and easiest option for speculative portfolio trade was doubles trading is creating a spread of two correlated tools. In the Forex market, this approach is significantly limited because even highly correlated pairs have no Cointegration, and as a consequence, can dramatically fled after some time. This situation is called “broken spread”. In addition, because the spread is usually get a pair with a common currency, the pair trading turns to trade synthetic cross rate. Pair trading in this form is a very bad idea. Opening the counter position on the spread, sometimes have to wait very long before they meet again curves.

an example well correlated pairs and their gradual and inevitable takeoff:

this approach is multilateral spread-trading when the spread included three or more pairs. It’s already better than doubles trading because of multiple pairs are easier to compose a smoother spread, and RIMM anymore. However, here the same risks as the pair trading: spread can go away and not come again. On a calm market easily achieved good repayment spread, but after some time a strong fundamental news to cause rapid and irreversible takeoff.
Funny, but when you increase the number of tools in probability increases, the field spread as the more currencies involved, the more likely it is that the regular news, “something happens”. Expect that the spread will definitely be come again is devastating. This works only in a quiet flat market.

an example of conduct multilateral spread the news:

Spread trading has more prospects on the stock or futures market, if there is a fundamental relationship between the assets.
But even there may be tears spreads date dividends or by the expiration of futures contracts.
You can collect more of stock indices spreads and futures, but it requires accounting peculiarities of trading.

Deadlock branch spread trading is a multifaceted Lok when selected cyclically interconnected pairs (for example, EURUSD GBPUSD-EURGBP) and one of them is drawn up balanced spread.
Spread it turns out perfect, but trade it is impossible because the summary spreads and commissions are too large. Attempt a little unbalance lots leads to schedule begins to acquire trend components that contradicts the multileg trade and costs still remain large. Such an approach is completely nonsensical.

an example of balanced multi-currency Castle, total spread showed two red lines:

disadvantages of spread trading make logical jump to trend models. Here everything seems very harmonious at first glance: identify a trend, we enter the correction and exit at higher levels, with a profit, the classic trading.

na good example of the trend model:

but not always with trendy models everything turns out so well and simply. In some cases a portfolio does not want to grow taller, and sometimes sharply down unfolds altogether. This situation is called “trend was broken”. In the short and medium term models such situations happen quite often. The effectiveness of such trade would heavily depend on the phase of the market. When the market is trending, the system will work well, but on quiet fljetovom or reciprocating vibration market there will be numerous losses.

an example of the dramatic conclusion of the trend:

these shortcomings are being forced to reconsider traditional approaches. Now consider a trade on a break of the spread and trade on a reversal of the trend. The overall premise is this: because you cannot get rid of the averages in the portfolios, you must learn to use it.

to create a Setup for a breakout of the spread creates a very compressed korotkoperiodnyj spread with minimum volatility in anticipation of a larger movement. The more compact the volatility of the portfolio, the more he “shoots”. To accelerate the spread gap you can generate setup before you start trading sessions and before the news, choosing local patches of quiet market. Optimization method of ICG is best suited for compression of volatility. This setup is not known in advance which way will depart, so input is assumed to be already in motion from the borders of the spread.

an example of an exit corridor korotkoperiodnogo spread, marked the boundaries of the corridor spreads:

the advantages of this method: short-period spreads routinely in charts, volatility after the breakdown often exceeds the width of the corridor spreads.
Cons: expansion of spreads on news and the possibility of “saw” when the price goes up and down a few times. Alternatively, you can invite a conservative entry after exiting the corridor spreads with correction to the border corridor, if that option is available.

to create the trend reversal Setup creates a trend model and tracked turning movements and price levels of the portfolio. When the direction of movement unambiguously, but is unknown in advance, at what point will happen fracture trend. Login for conservative tracked crossing an internal trend line, reverse correction and rebound. For aggressive entrance external tangency is tracked the trend line and bounce.

an example of a reversal of the trend of the portfolio, showing exterior and Interior trend lines:

the advantages of this method: affordable entry price, technical, extreme price volatility works in favor of Setapa. Cons: price can go higher for portfolio trend due to fundamental causes.
As improvements you can offer input fractional amounts from multiple levels.

a similar setup, you can implement a parabolic model of the square root function. The rationale for this Setup is a known property: when the price reaches the theoretical boundaries of cocoon market distribution, its further promotion would be difficult. Here, as in other cases, the objective function of optimization is selected under current market distribution. If the markets were a normal Gaussian distribution, always perfectly worked would be the law of the square root of the time, but since the market distribution of fractal and the combined receptacle situational adjustment is required.

learn more about the properties market distributions the following books can be read by Edgar Peters:

  • “chaos and order in the capital markets”
  • “fractal analysis of financial markets”

Example care portfolio of parabolic

This setup is perfect for adaptation to the medium volatility. But here, as in trend Setup, there is a risk that the price of a portfolio will go up by virtue of the fundamental factors. In General, the market is not obliged to follow a particular behaviours, as well as the objective function and is not obliged to violate it. This is always some freedom and duality.
All custom are not market-neutral in the absolute sense, and are based on some form of technical analysis.

an illustration of the dual nature of the trend and flat, the trend model on large scale recalls uneven flat:

when creating a portfolio, in addition to a combination of tools and model type, the more important the position of boundaries
settlement interval. When configuring, you may find it useful to move the border and see what the results are. Good choice of borders allows us to find more suitable from the point of view of trade Setapa portfolios. If the portfolio position goes into drawdown, there is the possibility to adjust the portfolio without closing existing positions. Shift changes the curve boundaries portfolio and to adapt it to the changed situation. After rebuilding the portfolio you want to perform the appropriate adjustment position.
This does not mean that the drawdown will decrease immediately, but adjusted portfolio can be more successful than the original.

next, consider some portfolio properties of beams and their possible uses in trade systems.

the first property portfolio beams that catches the eye is the extension beam-takeoff (divergence) portfolios from zero point. Looks natural and justified the use of this property for trading: buying and selling portfolios growing falling portfolios.

an example of the expanding beam portfolios:

the second property portfolio beams opposite first-beam compression — convergence (convergence) portfolios after the expansion.
Cycles of expansion and contractions suggest that you can try to use this behavior, discovering the synthetic position on return to the center of the beam after the alleged maximum expansion.
But the maximum expansion of different each time-off limit curves of beam in advance is unknown.

an example of shrinking beam portfolios:

Use different task functions, filtering options, the coup d ‘ état and combining opportunities to experiment and find the original trade setapov. In the most general form of all custom can be divided into two classes: trading on continued movement and trade.

Example trade Setup for the continuation of the movement with the coup and offset beam:

Example trade Setup to return to multitrendovoj models:

one more duplicate property portfolios — twist beam (samoperesechenie). This usually corresponds to the changing trends in the market.
To trade in the range of portfolios of the conduit is evil and requires rebuilding beam. For other policies, the intersection of individual portfolio curves can be used to identify promising and emission portfolios. In addition, you can take into account the mileage (distance), levels, position in the beam and position relative to the target function.

an example of a multiple twisting beam:

behind-the-scenes questions management volumes, which is an essential part of any trading system. Here on a general basis, you can mark these approaches:

  • trade one synthetic position (the simplest case)
  • crushing volumes (spanning the entrance levels)
  • adding to growing portfolio (pyramiding to trend)
  • Add prosevshij portfolio (averaging)
  • adding to the portfolio after adjustments (finishing method)
  • adding to the portfolio after the coup (expansive strategy)
  • add new portfolios ( consolidation of portfolios)
  • combined approach (a combination of approaches)

a specific approach to the management of volumes should be designed taking into account the features of the trading system. When planning your profit and drawdown must be based on the amount of volatility of the portfolio. In the simplest case, you can estimate the volatility of a portfolio as the magnitude of the movements of his graphics on some station. It is desirable to estimate volatility not only in the interval of optimization, but also on past history. Knowing the volatility of a portfolio, you can calculate the theoretical value of the maximum total drawdown for a series of positions. Traditionally, should warn against the abuse of too aggressive by adding volumes. The amount of funds on the trading account, allokirovannaja under the cover of portfolio, shall withstand an adverse movement of all incremental positions.

Multiportfelnaja trade is systematic selection and consolidation of portfolios. If you bought one and another is added to it, it can have a positive effect if the diversification of portfolios have noticeable differences. But if both correlated portfolio, this could have a negative effect, as in the case of adverse developments, both of them will leave in the drawdown.
Typically, you should avoid adding correlated portfolios. Trade spread between two korrelirovanymi portfolios, at first glance, it might seem very promising, but careful study leads to the understanding that these spreads do not differ from normal spreads, because they have no stationarity.

multiportfelnoj commerce may apply different exit strategies, in particular:

  • closing on outcome of all portfolios
  • closing group portfolios on outcome groups
  • closing on the objectives and limits for individual portfolios.

for some strategies crucial entry point. For example, if the strategy uses extreme prices before the break the trend or correction red continuation of the trend, while for entrance will be very short. Other strategies for entrance accuracy is less important, and the key is the optimal calculation schemas add positions and selection principle of portfolios. In this case, individual portfolios may give the drawdown, but other profitable portfolios in consolidated adjusted series, the overall result.


Benefits of portfolio trading: using optimization, you can create a curve of a portfolio to suit your preferences, to form the desired trade Setup and trade it as on a normal schedule, whereas for normal trading tools position trader purely passive (take the schedule as is, or give it up). Also the situation evolves trader can adjust portfolio, rebuilding it under the new market conditions.

Disadvantages of portfolio trading: not applicable standard pending orders, the minimum requirements for more volume, more spreads on the graphs below M30 intraday scalping is the chart portfolio no OHLC data, not all indicators can be applied to portfolios.

in General, however, this direction in trading is very nishevoe and specific, you can say, “chosen”. The article made an introductory overview of the properties of the portfolios and methods of working with them. Deeper study of portfolio trading systems for MetaTrader 5 platform is desirable, and the property market allocations study in specialized statistical packages.

  • AlgoTrader 11:34 am February 11, 2019 Reply

    Greetings We must learn the mat part, dear. In particular, the theory of reliability. Namely:

    1. The reliability of a simple system is equal to the product of the reliability of its elements (and not the sum, like yours).

    2. Reliability decreases with increasing number of elements (and you have more than three of them).

    3. The reliability of the system is determined by the reliability of its weakest element (one share can kill the entire portfolio).

    So, my friends.

    • Ziga 12:20 pm February 12, 2019 Reply

      Keep us updated… )))

Write a comment