Questions from Beginners MQL5 MT5 MetaTrader 5 - page 242

 

You can go like this:

void OnStart()
{
  int select=10;
  MqlRates rates[];
  CopyRates(_Symbol,_Period,0,select,rates);
  for(int i=1;i<select;i++)
  {
    if(rates[i].close<rates[i-1].close)
    {
      //тут какой-нибудь код
    }
  }
}
 
Fleder:

That's fine:

Thank you.

Question aboutArraySize, if I have the number of select [9] elements defined, will the function return a value of 10? or until I assign a value it will be 0?

 
websafe25:

Thank you.

Question aboutArraySize, if I have select [9] defined at once, will the function return a value of 10? or until I assign a value it will be 0?

Group functions for working with arrays

No more than four-dimensional arrays are allowed. Each dimension is indexed from 0 todimension_size-1. In a particular case of a one-dimensional array of 50 elements, calling the first element is array[0], the last one is array[49].

Here is a script to test it:

//+------------------------------------------------------------------+
//|                                                  test_script.mq5 |
//|                              Copyright © 2014, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2014, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   double select[9];
   Print ("Количество элементов массива select =",ArraySize(select));
  }
//+------------------------------------------------------------------+
Документация по MQL5: Операции с массивами
Документация по MQL5: Операции с массивами
  • www.mql5.com
Операции с массивами - Документация по MQL5
 
websafe25:

Thank you.

Question onArraySize, if I have the number of elements select [9] defined immediately, will the function return a value of 10? or until I assign a value it will be 0?

If the array is static and has a size of 10 cells, the ArraySize function will always return the number 10, regardless of the content of each cell.

If the array is dynamic, however, the ArraySize function will return its actual size (and this size can be changed).

 

Continuing to build my generator) The module is located in Include\Expert\Signal

1. I can't find it in the list of modules for the signal.

2. I'm confused by this line:

 double buy    =Signal_open_b(1);
I need to get the difference between
Main(index)-Signal(index)

On a bar with index 1. If I understand correctly, is the index in brackets?

3. Does this line specify the number of all buffers of the indicator or those to be used?

 if(!m_TSI.NumBuffers(11)) return(false);

4. Please advise how to request the data of this generator from the script for verification?

Below is all the code. Maybe I have made a mistake somewhere else, please advise.

#include <Expert\ExpertSignal.mqh>
// wizard description start
//+------------------------------------------------------------------+
//| Description of the class                                         |
//| Title=Сигнал индикатора 'Blau_Ergodic'                           |
//| Type=SignalAdvanced                                              |
//| Name=MyCustomIndicator                                           |
//| ShortName=MyCustomIndicator                                      |
//| Class=CSignalMyCustInd                                           |
//| Page=signal_envelopes                                            |
//| Parameter=q                                                      |
//| Parameter=r                                                      |
//| Parameter=s                                                      |
//| Parameter=u                                                      |
//| Parameter=ul                                                     |
//+------------------------------------------------------------------+
// wizard description end
//+------------------------------------------------------------------+
//| Class CSignalMyCustInd.                                          |
//| Purpose: Класс генератора торговых сигналов на основе            |
//|          пользовательского индикатора.                           |
//| Является производным от класса CExpertSignal.                    |
//+------------------------------------------------------------------+
class CSampleSignal : public CExpertSignal
  {
protected:
   CiCustom           m_TSI;              // объект для доступа к значениям TSI
   CiClose            m_close;           // объект для доступа к ценам закрытия баров
  //--- настраиваемые параметры
   int      q;  // q - период, по которому вычисляется моментум
   int      r; // r - период 1-й EMA, применительно к моментуму
   int      s;  // s - период 2-й EMA, применительно к результату первого сглаживания
   int      u;  // u - период 3-й EMA, применительно к результату второго сглаживания
   int      ul; // ul - (сигнальная линия) период EMA, применительно к эргодике
   double             m_stop_loss;       // уровень установки ордера "stop loss" относительно цены открытия
   double             m_take_profit;     // уровень установки ордера "take profit" относительно цены открытия
public:
              CSampleSignal();
 //--- методы установки настраиваемых параметров              
   void               Q(int value)                 { q=value;   }
   void               R(int value)                 { r=value;   }
   void               S(int value)                 { s=value;   }
   void               U(int value)                 { u=value;   }
   void               UL(int value)                { ul=value;  }
   void               StopLoss(double value)       { m_stop_loss=value;   }
   void               TakeProfit(double value)     { m_take_profit=value; }
   //--- метод проверки параметров настройки
   virtual bool       ValidationSettings();   
   virtual bool       InitIndicators(CIndicators* indicators);
    //--- методы проверки, если модели рынка сформированы 
   virtual bool      CheckOpenLong(double& price,double& sl,double& tp,datetime& expiration);
   virtual bool      CheckOpenShort(double& price,double& sl,double& tp,datetime& expiration);
protected:
   //--- метод инициализации объектов
   bool               InitMyCustomIndicator(CIndicators* indicators);
   bool               InitClose(CIndicators* indicators);
   //--- методы доступа к данным объектов
   double             Main(int index)                     { return(m_TSI.GetData(0,index)); }
   double             Signal(int index)                   { return(m_TSI.GetData(1,index)); }
   double             Signal_open_b(int index)           {return(Main(index)-Signal(index));}
   double             Signal_open_s(int index)           {return(Signal(index)-Main(index));}
   double             Close(int index)                    { return(m_close.GetData(index)); }
  };
//+------------------------------------------------------------------+
//| Конструктор CSampleSignal.                                       |
//| INPUT:  нет.                                                     |
//| OUTPUT: нет.                                                     |
//| REMARK: нет.                                                     |
//+------------------------------------------------------------------+
void CSampleSignal::CSampleSignal()
  {
   q=2; 
   r=7;
   s=5;
   u=3;
   ul=5;   
  }
//+------------------------------------------------------------------+
//| Проверка параметров настройки.                                   |
//| INPUT:  нет.                                                     |
//| OUTPUT: true-если настройки правильные, иначе false.             |
//| REMARK: нет.                                                     |
//+------------------------------------------------------------------+
bool CSampleSignal::ValidationSettings()
  {
  //--- проверка параметров
   if(q<=0||r<=0||s<=0||u<=0||ul<=0)
     {
      printf(__FUNCTION__+": период должен быть больше нуля");
      return(false);
     }
//--- успешное завершение
   return(true);
  }
//+------------------------------------------------------------------+
//| Инициализация индикаторов и таймсерий.                           |
//| INPUT:  indicators - указатель на объект-коллекцию               |
//|                      индикаторов и таймсерий.                    |
//| OUTPUT: true-в случае успешного завершения, иначе false.         |
//| REMARK: нет.                                                     |
//+------------------------------------------------------------------+
bool CSampleSignal::InitIndicators(CIndicators* indicators)
  {
//--- проверка указателя
   if(indicators==NULL)       return(false);
//--- инициализация TSI
   if(!InitMyCustomIndicator(indicators))    return(false);
   //--- инициализация таймсерии цен закрытия
   if(!InitClose(indicators)) return(false);
   return(true);
  }
//+------------------------------------------------------------------+
//| Инициализация индикаторов.                                       |
//+------------------------------------------------------------------+
bool CSampleSignal::InitMyCustomIndicator(CIndicators *indicators)
  {
//--- добавление объекта в коллекцию
   if(!indicators.Add(GetPointer(m_TSI)))
     {
      printf(__FUNCTION__+": error adding object");
      return(false);
     }
//--- задание параметров индикатора
   MqlParam parameters[6];
//---
   parameters[0].type=TYPE_STRING;
   parameters[0].string_value="Blau_Ergodic.ex5";
   parameters[1].type=TYPE_INT;
   parameters[1].integer_value=q;
   parameters[2].type=TYPE_INT;
   parameters[2].integer_value=r;
   parameters[3].type=TYPE_INT;
   parameters[3].integer_value=s;
   parameters[4].type=TYPE_INT;
   parameters[4].integer_value=u;
   parameters[5].type=TYPE_INT;
   parameters[5].integer_value=ul;
//--- инициализация объекта
   if(!m_TSI.Create(m_symbol.Name(),0,IND_CUSTOM,6,parameters))
     {
      printf(__FUNCTION__+": error initializing object");
      return(false);
     }
//--- количество буферов
   if(!m_TSI.NumBuffers(11)) return(false);
//--- ok
   return(true);
  }
//+------------------------------------------------------------------+
//| Инициализация таймсерии цен закрытия.                            |
//| INPUT:  indicators - указатель на объект-коллекцию               |
//|                      индикаторов и таймсерий.                    |
//| OUTPUT: true-в случае успешного завершения, иначе false.         |
//| REMARK: нет.                                                     |
//+------------------------------------------------------------------+
bool CSampleSignal::InitClose(CIndicators* indicators)
  {
//--- инициализация объекта таймсерии
   if(!m_close.Create(m_symbol.Name(),m_period))
     {
      printf(__FUNCTION__+": ошибка инициализации объекта");
      return(false);
     }
//--- добавление объекта в коллекцию
   if(!indicators.Add(GetPointer(m_close)))
     {
      printf(__FUNCTION__+": ошибка добавления объекта");
      return(false);
     }
//--- успешное завершение
   return(true);
  }
//+------------------------------------------------------------------+
//| Проверка выполнения условия для покупки.                         |
//| INPUT:  price      - ссылка для размещения цены открытия,        |
//|         sl         - ссылка для размещения цены stop loss,       |
//|         tp         - ссылка для размещения цены take profit,     |
//|         expiration - ссылка для размещения времени истечения.    |
//| OUTPUT: true-если условие выполнено, иначе false.                |
//| REMARK: нет.                                                     |
//+------------------------------------------------------------------+
bool CSampleSignal::CheckOpenLong(double& price,double& sl,double& tp,datetime& expiration)
  {
//--- подготовка данных
   double buy    =Signal_open_b(1);
   double unit  =PriceLevelUnit();
//--- проверка условия
   if(buy>1)
     {
      price=m_symbol.NormalizePrice(Close(0));
      sl   =m_symbol.NormalizePrice(price-m_stop_loss*unit);
      tp   =m_symbol.NormalizePrice(price+m_take_profit*unit);
      expiration+=m_expiration*PeriodSeconds(m_period);
      //--- условие выполнено
      return(true);
     }
//--- условие не выполнено
   return(false);
  }
 
forexman77:

Continuing to build my generator) The module is located in Include\Expert\Signal

1. I can't find it in the list of modules for the signal.

2. I'm confused by this line:

I need to get the difference between

On a bar with index 1. If I understand correctly, is the index in brackets?

3. Does this line specify the number of all buffers of the indicator or those to be used?

4. Please advise how to request the data of this generator from the script for verification?

Below is all the code. Maybe I made a mistake somewhere else, please advise.

In the header after Class you should write CSampelSignal
 
barabashkakvn:
In the header after Class you need to write CSampelSignal

I made it like this:

//+------------------------------------------------------------------+
//| Description of the class                                         |
//| Title=Сигнал индикатора 'Blau_Ergodic'                           |
//| Type=SignalAdvanced                                              |
//| Name=MyCustomIndicator                                           |
//| ShortName=MyCustomIndicator                                      |
//| Class=CSampelSignal                                              |
//| Page=signal_envelopes                                            |
//| Parameter=q                                                      |
//| Parameter=r                                                      |
//| Parameter=s                                                      |
//| Parameter=u                                                      |
//| Parameter=ul                                                     |
//+------------------------------------------------------------------+
// wizard description end
//+------------------------------------------------------------------+
//| Class CSampelSignal.                                          |
//| Purpose: Класс генератора торговых сигналов на основе            |
//|          пользовательского индикатора.                           |
//| Является производным от класса CExpertSignal.                    |
//+------------------------------------------------------------------+
I can't find it. In the menu I choose Generate EA.
 
forexman77:

Made it like this:

I can't find it. In the menu I choose to generate an EA.
Need to restart MetaEditor.


Мастер MQL5: Как написать свой модуль торговых сигналов
Мастер MQL5: Как написать свой модуль торговых сигналов
  • 2010.12.28
  • MetaQuotes Software Corp.
  • www.mql5.com
Генератор торговых стратегий Мастера MQL5 значительно упрощает проверку торговых идей. В статье рассказывается о том, как написать и подключить в Мастер MQL5 свой собственный класс торговых сигналов с реализацией сигналов по пересечению ценой скользящей средней, рассматривается структура и формат описания созданного класса для Мастера MQL5.
 
barabashkakvn:
I have to restart MetaEditor.

https://www.mql5.com/ru/articles/226

Opened it a few times, closed it. There's nothing.

Maybe it's because I missed the destructor. It doesn't compile, it gives an error.

//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CSampleSignal::~CSampleSignal(void)
  {
  }
~CSampleSignal' - member function not defined
 
forexman77:

Made it like this:

I don't find it. In the menu I select Generate EA.

Ah, in full, with the name of the hat, post the code, what religion doesn't allow :) ?

And yet, it's still worth reading:

MQL5 Wizard: How to write your own trading signals module

https://www.mql5.com/ru/forum/3724/page3#comment_66962

The error in the code is incorrect parameter description in the header. The colour highlighted is the modified code:

#include <Expert\ExpertSignal.mqh>
// wizard description start
//+------------------------------------------------------------------+
//| Description of the class                                         |
//| Title=Сигнал индикатора 'Blau_Ergodic'                           |
//| Type=SignalAdvanced                                              |
//| Name=MyCustomIndicator                                           |
//| ShortName=MyCustomIndicator                                      |
//| Class=CSampleSignal                                              |
//| Page=signal_envelopes                                            |
//| Parameter=q,int,12,Parametr_q                                    |
//| Parameter=r,int,6,Parametr_r                                     |
//| Parameter=s,int,9,Parametr_s                                     |
//| Parameter=u,int,24,Parametr_u                                    |
//| Parameter=ul,int,8,Parametr_ul                                   |
//+------------------------------------------------------------------+
// wizard description end

Of course, I entered the parameter values from the ceiling. These values are just for example.

Reason: