Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1517

 

I found this article https://www.mql5.com/ru/articles/286

and in the source code of his advisor is this code

   criterion_Ptr=new TCustomCriterionArray();
   if(CheckPointer(criterion_Ptr)==POINTER_INVALID)
     {
      return(-1);
     }
   criterion_Ptr.Add( new TSimpleCriterion( STAT_PROFIT ));
   criterion_Ptr.Add( new TSimpleDivCriterion( STAT_BALANCE_DD ));
   criterion_Ptr.Add( new TSimpleMinCriterion( STAT_TRADES, 50.0 ));

but I can't figure out how to set the necessary parameters, specifically:

  1. Minimum drawdown
  2. Maximum balance
  3. Maximum profit
  4. Maximum number of orders
Создание собственных критериев оптимизации параметров эксперта
Создание собственных критериев оптимизации параметров эксперта
  • www.mql5.com
Терминал МetaTrader 5 дает новые возможности для оптимизации параметров создаваемых экспертов. Кроме уже имеющихся в тестере критериев оптимизации, разработчики получили инструмент для создания собственных критериев. Это открывает поистине безграничные возможности в тестировании и оптимизации экспертов. В статье рассматриваются практические способы построения таких критериев - как простых, так и достаточно сложных.
 
Alexey Viktorov #:

No.

It is necessary to select position not by symbol, but by ticket using the PositionGetTicket(i) function and then check magick and symbol.

   int         total            = PositionsTotal();
   for(int i=total-1; i>=0; i--)
   {
      string position_symbol       = PositionGetString(POSITION_SYMBOL);
      ulong  ticket                = PositionGetTicket(i);
      if(total == 0 || (ticket > 0 && position_symbol==Symbol() && magic != Magic_m))

Do I understand correctly that in this case position_symbol and magic refer to this particular ticket? Does concatenation like ticket.magic or ticket.symbol work? Is the entry correct now?

Is the next entry correct?

   int         total            = PositionsTotal();
   for(int i=total-1; i>=0; i--)
   {
      int      position_magic        = position.Magic();
      string position_symbol       = position.Symbol(); /*PositionGetString(POSITION_SYMBOL)*/;
      ulong  position_ticket        = position.SelectByIndex(i);
      string symbol                      = Symbol();
      if(total == 0 || (position_ticket > 0 && position_symbol == symbol && position_magic != Magic_m))
 

A small clarification to your code:

  1. first you need to get the position ticket by index in the list of open positions;
  2. then get the symbol of the open position.
Why this way and not the other way round? Everything is clearly stated in the documentation:

Функция PositionGetTicket возвращает тикет позиции по индексу в списке открытых позиций
и автоматически выбирает эту позицию для дальнейшей работы с ней при помощи функций PositionGetDouble, PositionGetInteger, PositionGetString.

Regards, Vladimir.

 
maxvoronin74 #:
Do I understand correctly that in this case position_symbol and magic refer to this particular ticket? Does concatenation like ticket.magic or ticket.symbol work? Is the entry correct now?

it's almost correct.

    for(int i = PositionsTotal(); i-- > 0;)
     {
      ulong posTicket = PositionGetTicket(i);
      long posMagic = PositionGetInteger(POSITION_MAGIC);
      string posSymbol = PositionGetString(POSITION_SYMBOL);
      if(posSymbol == _Symbol && posMagic == Magic_m)
       {

Everyone has his own programming principle and this line of your code looks strange to me

      if(total = 0 || (ticket > 0 && position_symbol==Symbol() && magic != Magic_m))

Why check if(total = 0 ......... because if there are no open positions, the loop will not be executed.

And the check if(.........magic != Magic_m)) does not give anything. After all, if a position has a different magic, the loop will simply start a new iteration without additional commands.

But it's all for amateurs. If you like it this way, write it this way...

 
MrBrooklin #:
automatically selects this position for further work with it using the PositionGetDouble, PositionGetInteger, PositionGetString functions

Thanks. I was just finding out what exactly this "automatically" could mean.

 
Alexey Viktorov #:

it's almost right.

Everyone has his own programming principle and this line of your code looks strange to my mind

Why check if(total = 0 ......... because if there are no open positions, the loop will not be executed.

And the check if(.........magic != Magic_m)) does not give anything. After all, if a position has a different magic, the loop will simply start a new iteration without additional commands.

But it's all for amateurs. If you like it this way, write it this way...

Perhaps it is because I have i >= 0. Yours is greater than zero. And the concatenation I asked about is not accepted by MetaEditor. Although I took it from MetaQuotes article(https://www.mql5.com/ru/articles/12103)...

Why don't you check posTicket for equality to zero? After all, equality to zero according to the documentation indicates an error?

I don't understand the unnecessary checking of magik yet. The point of the code is to be sure that a position is not opened by this particular Expert Advisor on this instrument. There are several Expert Advisors on an instrument. Each of them has its own window. Experts are distinguished by magik.

Тестирование и оптимизация стратегий для бинарных опционов в MetaTrader 5
Тестирование и оптимизация стратегий для бинарных опционов в MetaTrader 5
  • www.mql5.com
Проверяем и оптимизируем стратегии для бинарных опционов в MetaTrader 5.
 
maxvoronin74 #:

And the concatenation I was asking about is not accepted by MetaEditor. Although I took it from MetaQuote article(https://www.mql5.com/ru/articles/12103)...

By concatenation I found out that, apparently, the class dictates to write m_position instead of position.

 
maxvoronin74 #:

By concatenation I found out that apparently the class dictates to write m_position instead of position.

You can name the variable position or m_position as you like, for example, pos, posit, k_pos, k_position, etc., etc.

Regards, Vladimir.

 
MrBrooklin #:

You can name the position or m_position variable anything you want, such as pos, posit, k_pos, k_position, etc. etc. etc.

Regards, Vladimir.

You are right with variables. But in the CTrade class this string m_position must be called something else. To open a position, we write m_trade.Buy(), instead of position.Magic(), as in the article, we write m_position.Magic(). This prefix m_ is everywhere.
 

You seem to be confused. Take a look and read the comments on each line carefully:

#include <Trade\PositionInfo.mqh>  // включим файл PositionInfo.mqh
#include <Trade\Trade.mqh>         // включим файл Trade.mqh
#include <Trade\SymbolInfo.mqh>    // включим файл SymbolInfo.mqh
#include <Trade\AccountInfo.mqh>   // включим файл AccountInfo.mqh

CPositionInfo m_position; // CPositionInfo - класс для работы со свойствами открытой позиции;  m_position - переменная для упрощенного доступа к свойствам открытой позиции
CTrade        m_trade;    // CTrade        - класс для совершения торговых операций;           m_trade    - переменная для упрощенного доступа к торговым операциям
CSymbolInfo   m_symbol;   // CSymbolInfo   - класс для работы со свойствами торг. инструмента; m_symbol   - переменная для упрощенного доступа к свойствам торгового инструмента
CAccountInfo  m_account;  // CAccountInfo  - класс для работы со свойствами торгового счета;   m_account  - переменная для упрощенного доступа к свойствами торгового счета

I hope everything will be clear now. As for the variable, I have already written in this thread that it can be called either position or m_position, etc. etc.

And, please, ask questions in this topic, so it will be easier to get help.

Regards, Vladimir.

Reason: