Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1264

 
Hello.I was inspiredby the lesson " Using Structures for Effective Program Development"and created a simple structure like this in MT5.
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Expert\Money\MoneyFixedMargin.mqh>

CPositionInfo      m_position;// object of CPositionInfo class
COrderInfo         m_order;   // object of COrderInfo class
CTrade             m_trade;   // object of CTrade class
CSymbolInfo        m_symbol;  // object of CSymbolInfo class
CAccountInfo       m_account; // object of CAccountInfo class
CDealInfo          m_deal;    // object of CDealInfo class
CMoneyFixedMargin *m_money;   // object of CMoneyFixedMargin class
//+------------------------------------------------------------------+
//| Structure Positions                                              |
//+------------------------------------------------------------------+
struct STRUCT_POSITION
  {
   ENUM_POSITION_TYPE type;       // тип позиции
   ulong              ticket;     // тикет позиции
   long               identifier; // идентификатор
   long               magic;      // магический номер
   double             volume;     // объем позиции
   double             open_price; // цена открытия
   datetime           open_time;  // время открытия
   double             profit;     // профит позиции
   double             comission;  // комиссия
   double             swap;       // своп
   string             comment;    // комментарий
   
   void               GetCurrentPositionProperty();
  };
  STRUCT_POSITION StrPositionArray[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   STRUCT_POSITION.GetCurrentPositionProperty();
  }
//+------------------------------------------------------------------+
//---Заполнение массива свойств позиций                              +
//+------------------------------------------------------------------+
void STRUCT_POSITION::GetCurrentPositionProperty(void)
{   
   ZeroMemory(this);
   int pos_total = PositionsTotal();
   ArrayResize(StrPositionArray,pos_total,1000);
   for(int i=0; i<pos_total; i++)
      {
         if(m_position.SelectByIndex(i))
            {
               StrPositionArray[i].ticket     = m_position.Ticket();                  // тикет позиции
               StrPositionArray[i].identifier = m_position.Identifier();              // идентификатор
               StrPositionArray[i].magic      = m_position.Magic();                   // магический номер
               StrPositionArray[i].comment    = m_position.Comment();                 // комментарий
               StrPositionArray[i].type       =(ENUM_POSITION_TYPE)m_position.PositionType();// тип позиции
               StrPositionArray[i].volume     = m_position.Volume();                  // объем позиции
               StrPositionArray[i].open_price = m_position.PriceOpen();               // цена открытия
               StrPositionArray[i].open_time  = m_position.Time();                    // время открытия
               StrPositionArray[i].profit     = m_position.Profit();                  // профит позиции
               StrPositionArray[i].comission  = m_position.Commission();              // комиссия
               StrPositionArray[i].swap       = m_position.Swap();                    // своп
            }
      } 
} 
//+------------------------------------------------------------------+

In the structure

STRUCT_POSITION

structure contains method

GetCurrentPositionProperty(void)

which calculates and assigns values to the elements of the structure. Define the body of the method outside the structure. To do this, use the context resolution operation (::).

In OnTick() we call the function:

void OnTick() { //--- STRUCT_POSITION.GetCurrentPositionProperty(); }

And here we get an error:

'.' - name expected eSower_and_Gather_5.mq5 69 19
I don't know where it went wrong, please help.

 
Sergey Voytsekhovsky:

'.' - name expected eSower_and_Gather_5.mq5 69 19

What is line 69 19? Please publish the code line 69 and specify where the 19 position is. It will immediately become clear where the error is.

 
Vladimir Karputov:

What is line 69 19? Post code line 69 and specify where the 19th position is. It will immediately become clear where the error is.

STRUCT_POSITION.GetCurrentPositionProperty();

It is highlighted in red in the post above. Thank you for your prompt reply.

 
Vladimir Karputov:

What is line 69 19? Post code line 69 and specify where the 19th position is. It will immediately become clear where the error is.

This is a point that must give access to a function which in turn uses the structure context. But I cannot understand why it doesn't work.

 
Sergey Voytsekhovsky:

it is highlighted in red in the post above. Thank you for your prompt reply.

'STRUCT_POSITION' is a DATA TYPE. You need to create a variable with this type and then call VARIABLE.GetCurrentPositionProperty();

Документация по MQL5: Основы языка / Типы данных
Документация по MQL5: Основы языка / Типы данных
  • www.mql5.com
Любая программа оперирует данными. Данные могут быть различных типов в зависимости от назначения. Например, для доступа к элементам массива используются данные целочисленного типа. Ценовые данные имеют тип двойной точности с плавающей точкой. Это связано с тем, что в языке MQL5 не предусмотрено специального типа для ценовых данных. Данные...
 
Sergey Voytsekhovsky:

This is the point that should give access to the function, which in turn uses the context of the structure.This is what I understood from the textbooks. But why it doesn't work I can't understand.

Code: (just calling a function - EA function, not a structure method - that makes more sense)

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Expert\Money\MoneyFixedMargin.mqh>
//---
CPositionInfo      m_position;// object of CPositionInfo class
COrderInfo         m_order;   // object of COrderInfo class
CTrade             m_trade;   // object of CTrade class
CSymbolInfo        m_symbol;  // object of CSymbolInfo class
CAccountInfo       m_account; // object of CAccountInfo class
CDealInfo          m_deal;    // object of CDealInfo class
CMoneyFixedMargin *m_money;   // object of CMoneyFixedMargin class
//+------------------------------------------------------------------+
//| Structure Positions                                              |
//+------------------------------------------------------------------+
struct STRUCT_POSITION
  {
   ENUM_POSITION_TYPE type;       // тип позиции
   ulong              ticket;     // тикет позиции
   long               identifier; // идентификатор
   long               magic;      // магический номер
   double             volume;     // объем позиции
   double             open_price; // цена открытия
   datetime           open_time;  // время открытия
   double             profit;     // профит позиции
   double             comission;  // комиссия
   double             swap;       // своп
   string             comment;    // комментарий

   void               GetCurrentPositionProperty();
  };
STRUCT_POSITION StrPositionArray[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   GetCurrentPositionProperty();
  }
//+------------------------------------------------------------------+
//| Заполнение массива свойств позиций                               |
//+------------------------------------------------------------------+
void GetCurrentPositionProperty(void)
  {
   int pos_total = PositionsTotal();
   ArrayResize(StrPositionArray,pos_total,1000);
   for(int i=0; i<pos_total; i++)
     {
      if(m_position.SelectByIndex(i))
        {
         StrPositionArray[i].ticket     = m_position.Ticket();                  // тикет позиции
         StrPositionArray[i].identifier = m_position.Identifier();              // идентификатор
         StrPositionArray[i].magic      = m_position.Magic();                   // магический номер
         StrPositionArray[i].comment    = m_position.Comment();                 // комментарий
         StrPositionArray[i].type       =(ENUM_POSITION_TYPE)m_position.PositionType();// тип позиции
         StrPositionArray[i].volume     = m_position.Volume();                  // объем позиции
         StrPositionArray[i].open_price = m_position.PriceOpen();               // цена открытия
         StrPositionArray[i].open_time  = m_position.Time();                    // время открытия
         StrPositionArray[i].profit     = m_position.Profit();                  // профит позиции
         StrPositionArray[i].comission  = m_position.Commission();              // комиссия
         StrPositionArray[i].swap       = m_position.Swap();                    // своп
        }
     }
  }
//+------------------------------------------------------------------+
 
Vladimir Karputov:

STRUCT_POSITION' is a DATA TYPE. You need to create an object with this type and then call OBJECT.GetCurrentPositionProperty();

Tried it. Such an object is created, declared right after declaration of the

StrPositionArray[].

If you put it into OnTick

void OnTick()
  {
//---
   StrPositionArray[].GetCurrentPositionProperty();
  }

we get an error:

']' - expression expected eSower_and_Gather_5.mq5 69 21

This is the same line, only second bracket, the one just before the dot.
 
Vladimir Karputov:

Code: (just calling a function - EA function, not a structure method - that makes more sense)

So using :: was a futile idea?

Then why did you write the function

GetCurrentPositionProperty()

inside the structure? It would fill the structure without any filling inside it, wouldn't it? Please clarify, I'm confused, maybe this is an obsolete feature, I should forget about it ?

 
Sergey Voytsekhovsky:

So using :: was a waste of time?

Then why would you write a function

inside the structure??? I mean, it will fill the structure perfectly even without it. Please clarify, I'm confused, maybe this is an obsolete idea that should be forgotten.

Copypaste. There's a line left after copypaste.

It should be like this (there are no methods inside the structure)

//+------------------------------------------------------------------+
//| Structure Positions                                              |
//+------------------------------------------------------------------+
struct STRUCT_POSITION
  {
   ENUM_POSITION_TYPE type;       // тип позиции
   ulong              ticket;     // тикет позиции
   long               identifier; // идентификатор
   long               magic;      // магический номер
   double             volume;     // объем позиции
   double             open_price; // цена открытия
   datetime           open_time;  // время открытия
   double             profit;     // профит позиции
   double             comission;  // комиссия
   double             swap;       // своп
   string             comment;    // комментарий
  };
STRUCT_POSITION StrPositionArray[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
 
Vladimir Karputov:

Copypaste. There is a line left after the copypaste.

It should be like this (there are no methods inside the structure)

Well, I have spent so much time on the lesson. Although it was for MT4, it was presented there as a trick, so here is an extract from the text:

1
2
3
4
5
6
7
8
9
10
11
12
struct state
{
int buy_count; // number of buy orders
int sell_count; // number of sell orders
double buy_bottom_price; //open price of the lowest buy order
double sell_top_price; //open price of the highest sell order
double profit; // profit of all orders
// method for gathering information about the state of the account
// and refresh the elements of the structure
void Refresh() ;
} State;

The structure has a Refresh() method which calculates and assigns values to the elements of the structure. Let's define the body of the method outside the structure. To do this, we use the context resolution operation (::). The context is a descriptor (name) of the structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//+------------------------------------------------------------------+
//| The method collects information about the current state of the account |
//| and updates the relevant fields of the structure |
//+------------------------------------------------------------------+
void state::Refresh( void )
{
//zero the numeric fields of the structure
ZeroMemory( this );
for ( int i=OrdersTotal()-1; i>=0; i--)
if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
if (OrderSymbol()==_Symbol && OrderMagicNumber()==Magic)
{
double OpenPrice=OrderOpenPrice();
profit+=OrderProfit()+OrderCommission()+OrderSwap();
switch (OrderType())
{
case OP_BUY:
buy_count++;
if (OpenPrice<buy_bottom_price || buy_bottom_price==0)
buy_bottom_price=OpenPrice;
break ;
case OP_SELL:
sell_count++;
if (OpenPrice>sell_top_price || sell_top_price==0)
sell_top_price=OpenPrice;
break ;
}
}
}

Note that in the body of the method we refer to elements of the structure without using a dot, since we used the context resolution operation. Numeric fields are zeroed by ZeroMemory() with the this keyword before updating them at the beginning of the method body, so the structure passes a reference to itself.

The main EA code inside the OnTick() handler will now look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//+------------------------------------------------------------------+
//| Expert tick function|
//+------------------------------------------------------------------+
void OnTick()
{
for ( int i=0; i<2000; i++)
{
double b=MathSqrt(i);
}
// open new orders and take profit only at the opening of a new bar
if (IsNewBar())
{
// obtain a new signal
int Signal=GetSignal();
// immediately exit the function if the signal has not been generated on the closed bar.
if (Signal<0)
return ;
//refresh the structure
State.Refresh(); // (!!! )