Discussing the article: "Developing a multi-currency Expert Advisor (Part 2): Transition to virtual positions of trading strategies"

 

Check out the new article: Developing a multi-currency Expert Advisor (Part 2): Transition to virtual positions of trading strategies.

Let's continue developing a multi-currency EA with several strategies working in parallel. Let's try to move all the work associated with opening market positions from the strategy level to the level of the EA managing the strategies. The strategies themselves will trade only virtually, without opening market positions.

In the previous article, we started developing a multi-currency EA that works simultaneously with various trading strategies. At the first stage there were only two different strategies. They represented the implementation of the same trading idea, worked on the same trading instrument (symbol) and chart period (timeframe). They differed from each other only in the numerical values of the parameters.

We also determined the optimal size of open positions based on the desired maximum drawdown level (10% of the deposit). We did this for each strategy separately. When we combined the two strategies together, we had to reduce the size of the opened positions in order to maintain the given drawdown level. For two strategies, the decrease was small. But what if we want to combine tens or hundreds of strategy instances? It may well happen that we will have to reduce the position size to a value less than the minimum size of open positions, allowed by the broker, for some strategies. In this case, these strategies simply will not be able to participate in trading. How can we make them work?

To do this, we will take away from the strategies the right to independently open positions and place pending orders. Strategies will only have to conduct virtual trading, that is, remember at what levels positions of a certain size should be opened and report what volume should be opened now upon request. We will open real market positions only after surveying all strategies and calculating the total required volume, taking into account scaling to maintain a given drawdown.

We are now only interested in testing the suitability of this approach, and not the efficiency of its implementation. Therefore, within the framework of this article, we will try to develop at least some working implementation of this approach, which later will help us build a more beautiful one from an architectural point of view since we will already have knowledge on how to avoid mistakes.

Author: Yuriy Bykov

 

I haven't finished reading it yet. The inputs are a good example.

1.

input string      symbol_              = "EURGBP";    // Торговый инструмент (символ)
input ENUM_TIMEFRAMES  timeframe_       = PERIOD_H1;   // Период графика

input group "===  Параметры сигнала к открытию"
input int         signalPeriod_        = 13;    // Количество свечей для усреднения объемов
input double      signalDeviation_     = 0.3;   // Относ. откл. от среднего для открытия первого ордера
input double      signaAddlDeviation_  = 1.0;   // Относ. откл. от среднего для открытия второго и последующих ордеров

input group "===  Параметры отложенных ордеров"
input int         openDistance_        = 0;     // Расстояние от цены до отлож. ордера
input double      stopLevel_           = 10500; // Stop Loss (в пунктах)
input double      takeLevel_           = 465;   // Take Profit (в пунктах)
input int         ordersExpiration_    = 1000;  // Время истечения отложенных ордеров (в минутах)

input group "===  Параметры управление капиталом"
input int         maxCountOfOrders_    = 3;     // Макс. количество одновременно отрытых ордеров
2.
int OnInit() {
   expert = new CAdvisor(new CVolumeReceiver(magic_));
   expert.Add(new CSimpleVolumesStrategy(
                         symbol_, timeframe_,
                         fixedLot_,
                         signalPeriod_, signalDeviation_, signaAddlDeviation_,
                         openDistance_, stopLevel_, takeLevel_, ordersExpiration_,
                         maxCountOfOrders_)
                     );       // Добавляем один экземпляр стратегии

   return(INIT_SUCCEEDED);
}
3.
class CSimpleVolumesStrategy : public CStrategy {
private:
   //---  Параметры сигнала к открытию
   int               m_signalPeriod;       // Количество свечей для усреднения объемов
   double            m_signalDeviation;    // Относ. откл. от среднего для открытия первого ордера
   double            m_signaAddlDeviation; // Относ. откл. от среднего для открытия второго и последующих ордеров

   //---  Параметры отложенных ордеров
   int               m_openDistance;       // Расстояние от цены до отлож. ордера
   double            m_stopLevel;          // Stop Loss (в пунктах)
   double            m_takeLevel;          // Take Profit (в пунктах)
   int               m_ordersExpiration;   // Время истечения отложенных ордеров (в минутах)

   //---  Параметры управление капиталом
   int               m_maxCountOfOrders;   // Макс. количество одновременно отрытых ордеров

4.

public:
   //--- Публичные методы
   CSimpleVolumesStrategy(
      string           p_symbol,
      ENUM_TIMEFRAMES  p_timeframe,
      double           p_fixedLot,
      int              p_signalPeriod,
      double           p_signalDeviation,
      double           p_signaAddlDeviation,
      int              p_openDistance,
      double           p_stopLevel,
      double           p_takeLevel,
      int              p_ordersExpiration,
      int              p_maxCountOfOrders
   ); 

5-6.

//+------------------------------------------------------------------+
//| Конструктор                                                      |
//+------------------------------------------------------------------+
CSimpleVolumesStrategy::CSimpleVolumesStrategy(
   string           p_symbol,
   ENUM_TIMEFRAMES  p_timeframe,
   double           p_fixedLot,
   int              p_signalPeriod,
   double           p_signalDeviation,
   double           p_signaAddlDeviation,
   int              p_openDistance,
   double           p_stopLevel,
   double           p_takeLevel,
   int              p_ordersExpiration,
   int              p_maxCountOfOrders) :
   // Список инициализации
   CStrategy(p_symbol, p_timeframe, p_fixedLot), // Вызов конструктора базового класса
   m_signalPeriod(p_signalPeriod),
   m_signalDeviation(p_signalDeviation),
   m_signaAddlDeviation(p_signaAddlDeviation),
   m_openDistance(p_openDistance),
   m_stopLevel(p_stopLevel),
   m_takeLevel(p_takeLevel),
   m_ordersExpiration(p_ordersExpiration),
   m_maxCountOfOrders(p_maxCountOfOrders) {
   ArrayResize(m_orders, m_maxCountOfOrders);

   // Загружаем индикатор для получения тиковых объемов
   iVolumesHandle = iVolumes(m_symbol, m_timeframe, VOLUME_TICK);

// Устанавливаем размер массива-приемника тиковых объемов и нужную адресацию
   ArrayResize(volumes, m_signalPeriod);
   ArraySetAsSeries(volumes, true);
}

Each input parameter must be prescribed five or six times.

 
Сравнивая эти результаты с результатами аналогичного советника, но не использующего виртуальные позиции, можно отметить улучшение некоторых показателей: немного увеличилась прибыль и уменьшилась просадка, подрос коэффициент Шарпа и профит-фактор.
Roughly speaking, switched from hedging to netting, getting the corresponding stat. "improvements." For example, reduction of volumes on which swaps were charged.
 

Read the article. Thanks to the author, good probing, in which directions we can move.


Нас сейчас будет интересовать только проверка пригодности такого подхода, а не эффективность его реализации. Поэтому в рамках этой статьи мы постараемся написать хотя бы какую-то рабочую реализацию этого подхода, которая в дальнейшем поможет нам построить более красивую с архитектурной точки зрения. Поможет не в том смысле, что мы будем улучшать уже имеющуюся, а в том, что мы сможем понять, что вот так делать не надо, а можно сделать по-другому, и это будет лучше.

A powerful observation, after which there is no point in criticising, but should go straight to the constructive part - to suggest.


The article discusses the concept of virtual trading followed by one-way synchronisation of virtual trading with real trading. As an example for the Tester, it will do. But only as an example.

In practice, such TS portfolio is built from EX5 (free of charge for the Tester from the Market) - run it, get tst-files of single runs, make a joint single run from them with any MM rules.


For Tester, you need speed. Try to estimate how much the speed of optimisation changes for the variant with and without virtualisation.


The concept itself is good for real trading. But for the synchroniser you will have to keep the history of virtual trading. There is a lot of things. A serious way, to put it mildly.


Architecturally, virtualisation would be detached from the TS. I have only the current source of virtualisation 350 Kb. And it will grow.


Carefully approach the choice of trading API for virtual trading. Choose from the available ones. It is logical to give preference to the API, on which it is as easy as possible to program the TS. I don't really understand the common practice of all trading platforms to invent their own bicycle - trading API. To endow it with OOP-entities "out of the box", etc. In this sense, MQ went a good way - all APIs without OOP.

 

Before reading such articles, I always look at the test results. At least in the tester. When I saw 19% profit for 5 years, I felt light and happy! This is much more than the author of 75 articles on neural networks! ))

But now it's clear how to make guaranteed money on Forex. I used to think only to teach suckers on Elliot waves, but it turns out there is still a great way )).

 
fxsaber #:

Read the article. Thanks to the author, good insight into which directions to go.

Thanks a lot for your interest and constructive comments. I try to take them into account and utilise them as much as possible. I will reply in more detail later, I don't have time right now.

 
Alexey Volchanskiy test results. At least in the tester. When I saw 19% profit for 5 years, I felt light and happy! This is much more than the author of 75 articles on neural networks! ))

But now it's clear how to make guaranteed money on Forex. I used to think only to teach suckers on Elliot waves, but it turns out there is still a great way )).

I can't resist noting here that 19% of profits for five years on the test were made by a constant lot in the conditions of drawdown less than $1000, that is 1%. If we focus on a maximum drawdown of even 10% and use a variable lot, the results will look even more interesting.

 
//+------------------------------------------------------------------+
//|                                    SimpleVolumesExpertSingle.mq5 |
//|                                      Copyright 2024, Yuriy Bykov |
//|                            https://www.mql5.com/ru/users/antekov |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Yuriy Bykov"
#property link      "https://www.mql5.com/ru/articles/14107"
#property description "Советник отложенный ордер в тот момент, когда тиковый объем свечи превышает средний объем,"
#property description "в направлении текущей свечи."
#property description "Если ордера еще не превратились в позиции, то они удаляются по времени истечения."
#property description "Открытые позиции закрываются только по SL или TP."

#include "Advisor.mqh"
#include "SimpleVolumesStartegy.mqh"

A typo.

 
fxsaber #:

A typo.

Yes, I corrected it in several places, but it's still there somewhere.

 
fxsaber #:

In practice, such a portfolio of TS is built from EX5 (free of charge from the Market for the Tester) - run, get tst-files of single passes, from them make a joint single run with any MM rules.

I haven't considered this option yet, I'll keep in mind that it's also possible. However, if I manage to find a good set of ready-made Expert Advisors from the market, how can I use them together? Do I just run the whole set with the selected MM parameters?

 
fxsaber #:

For the Tester, you need speed. Try to estimate how much the speed of optimisation changes for the variant with and without virtualisation.

I will try, but it seems that the gain will be noticeable when the number of simultaneously running strategies is tens or hundreds of instances.

I keep meaning to go into more detail about using your Virtual library to speed up testing, but I haven't got round to it yet. The main reason is that I am used to MT5 trading functions, although when I had to redesign my Expert Advisors from MT4 to MT5, there were a lot of inconveniences related to it, and I learnt about Virtual later.

Now I am considering making a child class from CReceiver, which will use Virtual environment.