Questions from Beginners MQL5 MT5 MetaTrader 5 - page 580

 
Artyom Trishkin:
While I'm still on my mobile, I'll say this: where in the code Alert and the loop with the print, the structure is already filled in.

Alert is just outside the loops in the On Start () function

 
Andrey Koldorkin:

Alert is just outside the loops in the On Start () function

Well, that's where you need to read the structure filled in the loop.
 
Andrey Koldorkin:

Alert is just outside the loops in the On Start () function

Here I show you approximately how to make it into a function. Then you call it whenever you need it:

//+------------------------------------------------------------------+
//|                                                     TestCopy.mq4 |
//|              Copyright 2016, Artem A. Trishkin, Skype artmedia70 |
//|                       https://login.mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Artem A. Trishkin, Skype artmedia70"
#property link      "https://login.mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property strict
#property script_show_inputs

enum enumYN
  {
   enYes=1, // Да
   enNo=0,  // Нет
  };

//--- input parameters
input int StartCopy=1;        // Номер бара, с которого начинаем копировать
int startCopy=(StartCopy<0)?0:StartCopy;
input int Search_Period=10;   // Количество копируемых свечей
int searchPeriod=(Search_Period<1)?1:Search_Period;
input int Delta=2;            // Количество пунктов допуска
int delta=(Delta<0)?0:Delta;
input enumYN AsSeries=enYes;  // Массив array как таймсерия
MqlRates array[];             // Массив структур для копирования Open, High, Low, Close, Time
  
struct DataCandle             // Структура для хранения всех совпадений
  {
   int number_matched;           // Количество совпадений
   MqlRates reference_candle;    // Данные эталонной свечи
   MqlRates matched_candles[];   // Массив свечей, совпадающих с эталонной по нужному критерию 
  };
  DataCandle dataCandle[];    // Массив структур данных свечей и их совпадений
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   int copy_bars=(int)fmin(searchPeriod,Bars(Symbol(),Period()));                                  // количество копируемых свечей
   int searchResult=GetDataCandles(Symbol(),PERIOD_CURRENT,startCopy,copy_bars,array,dataCandle);  // Вызываем функцию поиска совпадающих свечей
   
   //--- если результат есть какой-то ...
   if(searchResult>0) {
      //--- ... посмотрим чего понаписали в массивы
      Alert("Array is series: ",ArrayIsSeries(array),
            "\ntime array[0]: ",TimeToString(array[0].time,TIME_DATE|TIME_MINUTES),
            "\ntime array[",string(searchPeriod-1),"]: ",TimeToString(array[ArraySize(array)-1].time,TIME_DATE|TIME_MINUTES));
      for(int i=0; i<ArraySize(dataCandle)-1; i++) {
         string refs_txt="";
         string matched_txt="";
         refs_txt="Свеча "+IntegerToString(i,2,'0')+": время "+TimeToString(dataCandle[i].reference_candle.time)+", high: "+DoubleToString(dataCandle[i].reference_candle.high,Digits())+" имеет совпадений: "+(string)dataCandle[i].number_matched+" шт. ";
         if(dataCandle[i].number_matched>0) {
            for(int j=0; j<ArraySize(dataCandle[i].matched_candles); j++) {
               matched_txt="Совпадение "+IntegerToString(j+1)+": "+TimeToString(dataCandle[i].matched_candles[j].time)+", high: "+DoubleToString(dataCandle[i].matched_candles[j].high,Digits());
               }
            }
         Print(refs_txt,matched_txt);
         }
      }
  }
//+------------------------------------------------------------------+
int GetDataCandles(string sy, ENUM_TIMEFRAMES timeframe, int begin_copy, int number_copy, MqlRates &array_rates[], DataCandle &data_candle[]) {
   int copied=0;
   copied=CopyRates(sy,timeframe,begin_copy,number_copy,array_rates);      // копируем данные
   if(copied>0) {                                                          // если скопировали
      ArraySetAsSeries(array_rates,AsSeries);                              // Задаём массив как таймсерию или нет
      ArrayResize(data_candle,copied);                                     // задаём размер структуры равным числу скопированных данных
      ZeroMemory(data_candle);                                             // Обнуляем данные в структуре
      //--- основной цикл по "эталонным" свечам в массиве array. Их параметры будем искать в доп. цикле
      for(int i=0; i<copied-1; i++) {                                      // цикл по скопированным данным от начала до "на один меньше размера массива"
         data_candle[i].reference_candle.high=array_rates[i].high;         // ищем этот high
         data_candle[i].reference_candle.low=array_rates[i].low;           // запомнили low для сравнения
         data_candle[i].reference_candle.time=array_rates[i].time;         // запомнили time для вывода в журнал
         //--- поиск совпадений с эталонной свечой, индексируемой индексом основного цикла i
         int size=0;                                                       // размер массива совпадающих свечей
         ArrayResize(data_candle[i].matched_candles,size);                 // Размер массива совпадений в ноль
         data_candle[i].number_matched=size;                               // Инициализируем количество совпадений нулём
         //--- теперь ищем совпадения по high свечей в цикле j с high эталонной свечи с индексом i
         for(int j=0; j<copied; j++) {                                     // в цикле от i+1 до copy_bars
            if(j==i) continue;                                             // пропустим свечу "саму себя"
            //--- если совпадают high эталонной свечи (i) и свечи с индексом j (с допуском на величину Point)
            if(NormalizeDouble(delta*Point()-fabs(array_rates[i].high-array_rates[j].high),Digits())>=0) {
               size++;                                               
               ArrayResize(data_candle[i].matched_candles,size);                 // увеличим размер массива совпадающих свечей
               data_candle[i].number_matched=size;                               // запишем количество совпадений
               data_candle[i].matched_candles[size-1].high=array_rates[j].high;  // запишем в массив high совпадающей свечи
               data_candle[i].matched_candles[size-1].low=array_rates[j].low;    // запишем в массив low совпадающей свечи
               data_candle[i].matched_candles[size-1].time=array_rates[j].time;  // запишем в массив время совпадающей свечи
               }
            }
         }
      }
   return(copied);
}
//+------------------------------------------------------------------+
 
Koldun Zloy:

You can.

Amazing possibilities.

Thank you very much.

Can you please tell me where to read more about this?

I'm trying to publish text to the url now, but the code given in the help doesn't want to authorize even on my home site.

I wonder what information I need to gather about a third-party site, other than the url address, in order to authorize and publish the text.

 
mila.com:

Can you please tell me where to read more about this?

Here

 

Greetings.
Guys who know the subject, I don't know how to solve the problem.
I'm writing
a trading panel for myself under MT4 using classes of panel creation and dialogs available in MT4.
To enter data into the opening price
of the deal, as well as to set the SL and TP, I use the CEdit class (it is a class of simple control based on the "Input field " object). As an alternative, there isthe CSpinEdit class(it is a class of the combined "Increment-Decrement field" control), but it is used for integer data. In general, I'm more comfortable using CEdit, as I don't need the increment .

So,
how to make itpossible to enter only digits in CEdit input field ? It would be better to mask the entry. As it is implemented in MT4 terminal when we press "New Order", we see that stop loss and take profit fields are masked as 0.0000, etc. How to do the same withCEdit? I'm just not very deep into the class topic and some things are unclear.

 
Andrey Zuev:

Greetings.
Guys who is in the subject advise, don't know how to solve the problem.
I am writing
a trading panel for myself under MT4 using the panel creation classes and dialogs available in MT4.
I use
CEdit class (it is a class of simple control based on "Entry field" object). As an alternative, there is the CSpinEdit class (it is a class of the combined "Increment-Decrement field" control), but it is used for integer data. In general I'm more comfortable usingCEdit, as I don't need the increment .

So,
how to make itpossible to enter only digits in CEdit input field ? It would be better to mask the entry. As it is implemented in MT4 terminal when we press "New Order", we see that stop loss and take profit fields are masked as 0.0000, etc. How to do the same with CEdit? I'm just not very deep into the class topic yet and some things are not clear.

Here is the dialog panel with the CEdit control (for clarity, the example is made as a single file) - the panel checks the characters entered. Only numbers are allowed:

//+------------------------------------------------------------------+
//|                                                 ControlsEdit.mq5 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property description "Панель индикации и диалогов управления. Демонстрация работы класса CEdit"
#include <Controls\Dialog.mqh>
#include <Controls\Edit.mqh>
//+------------------------------------------------------------------+
//| defines                                                          |
//+------------------------------------------------------------------+
//--- indents and gaps
#define  INDENT_LEFT                         (11)      // indent from left (with allowance for border width)
#define  INDENT_TOP                          (11)      // indent from top (with allowance for border width)
#define  INDENT_RIGHT                        (11)      // indent from right (with allowance for border width)
#define  INDENT_BOTTOM                       (11)      // indent from bottom (with allowance for border width)
#define  CONTROLS_GAP_X                      (5)       // gap by X coordinate
#define  CONTROLS_GAP_Y                      (5)       // gap by Y coordinate
//--- for buttons
#define  BUTTON_WIDTH                        (100)     // size by X coordinate
#define  BUTTON_HEIGHT                       (20)      // size by Y coordinate
//--- for the indication area
#define  EDIT_HEIGHT                         (20)      // size by Y coordinate
//--- for group controls
#define  GROUP_WIDTH                         (150)     // size by X coordinate
#define  LIST_HEIGHT                         (179)     // size by Y coordinate
#define  RADIO_HEIGHT                        (56)      // size by Y coordinate
#define  CHECK_HEIGHT                        (93)      // size by Y coordinate
//+------------------------------------------------------------------+
//| Class CControlsDialog                                            |
//| Usage: main dialog of the Controls application                   |
//+------------------------------------------------------------------+
class CControlsDialog : public CAppDialog
  {
private:
   CEdit             m_edit;                          // CEdit объект

public:
                     CControlsDialog(void);
                    ~CControlsDialog(void);
   //--- create
   virtual bool      Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
   //--- chart event handler
   //--- chart event handler
   virtual bool      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);

protected:
   //--- create dependent controls
   bool              CreateEdit(void);
   //--- handlers of the dependent controls events
   void              OnChangeEdit(void);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CControlsDialog::CControlsDialog(void)
  {
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CControlsDialog::~CControlsDialog(void)
  {
  }
//+------------------------------------------------------------------+
//| Event Handling                                                   |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CControlsDialog)
ON_EVENT(ON_END_EDIT,m_edit,OnChangeEdit)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Create                                                           |
//+------------------------------------------------------------------+
bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  {
   if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
      return(false);
//--- create dependent controls
   if(!CreateEdit())
      return(false);
//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Create the display field                                         |
//+------------------------------------------------------------------+
bool CControlsDialog::CreateEdit(void)
  {
//--- coordinates
   int x1=INDENT_LEFT;
   int y1=INDENT_TOP;
   int x2=ClientAreaWidth()-INDENT_RIGHT;
   int y2=y1+EDIT_HEIGHT;
//--- create
   if(!m_edit.Create(m_chart_id,m_name+"Edit",m_subwin,x1,y1,x2,y2))
      return(false);
//--- разрешим редактировать сожержимое
   if(!m_edit.ReadOnly(false))
      return(false);
   if(!Add(m_edit))
      return(false);
//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Global Variables                                                 |
//+------------------------------------------------------------------+
CControlsDialog ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create application dialog
   if(!ExtDialog.Create(0,"Controls",0,40,40,380,344))
      return(INIT_FAILED);
//--- run application
   ExtDialog.Run();
//--- succeed
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- очистим комментарии
   Comment("");
//--- destroy dialog
   ExtDialog.Destroy(reason);
  }
//+------------------------------------------------------------------+
//| Expert chart event function                                      |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,         // event ID  
                  const long& lparam,   // event parameter of the long type
                  const double& dparam, // event parameter of the double type
                  const string& sparam) // event parameter of the string type
  {
   ExtDialog.ChartEvent(id,lparam,dparam,sparam);
  }
//+------------------------------------------------------------------+
//| Event handler                                                    |
//+------------------------------------------------------------------+
void CControlsDialog::OnChangeEdit(void)
  {
//--- allowed to use 0 to 9 digits only
   string   text     =m_edit.Text();
   int      text_len =StringLen(text);
   string   sample   ="0123456789";
   for(int i=0;i<text_len;i++)
     {
      string substr=StringSubstr(text,i,1);
      if(StringFind(sample,substr,0)==-1)
        {
         m_edit.Text("Допустымы только цифры");
         break;
        }
     }
  }
//+------------------------------------------------------------------+
Files:
 
Koldun Zloy:

Here

The book is not on sale, but is freely available.

Thank you.

 
Hello. Can you tell me what code to write to close the order at the end of the day?
 
Hello gentlemen of the forum!!! I have a problem. I tested the Expert Advisor on weekdays and it got one result, but on weekends it gives me a totally different result! Please tell me why?
Reason: