Questions from Beginners MQL5 MT5 MetaTrader 5 - page 815

 
pivomoe:
I just can't figure out if it's normal that .

There are a lot of things that are difficult to understand here. In particular, when dealing with the sequence of transactions, I have found that there are some inconsistencies in a number of cases.
For example, when a position is opened, a market order is formally opened first, which then turns into a position. However, during this machine-gun series of transactions there is a situation where a position has already been opened, but the order has not yet been closed. Clearly this is the same event, but the transactions are organised piecemeal, issued sequentially, and with this approach it is in principle impossible to correctly reflect the transformation of a market order into a position.

In my opinion, it is best to organise your trade control: remember your trade orders and monitor the composition of orders and positions simply by the fact of their presence in the relevant lists.
 

Speaking of birds.

Did you know that market orders are issued in these transactions with a zero price?
For example, a person wants to open a Buy position at 1.2000, Sl=1.1000, Tr=1.3000.
When this transaction is executed, the first thing the transaction appears where the market order is listed with the following data:
Sl= 1.1000, Tr= 1.3000, i.e. with the specified numbers and Price=0 (equal to zero). Just a kind of market order with zero price :) And think what you want.

 
pivomoe:

For convenience. A small function is called from MqlTradeTransaction. The required element is found there through searching for elements of the class. And for this element, one of the class functions is called which does something useful.


Please describe in more detail what exactly you want to get? Why do you call something from OnTradeTransaction?

First just in words, then we'll correct it in the right direction.

 
User_mt5:
The user's function Abc() is executed, and it implements a long (in terms of time) algorithm.
During the execution of this function, some events take place, for example - Trade, Timer, etc.
Is it possible to know that these events occurred without finishing execution of the Abc() function?

No. While one function is counting, everything else will be skipped.

It is similar totheSleep()function- i.e. while your function is counting for a very long time, its behavior is similar to Sleep - all the other events will be skipped.

 
User_mt5:

...


Absolutely everything is transparent in OnTradeTransaction.

First:MqlTradeTransaction structure is filled differently depending on trade transaction type (ENUM_TRADE_TRANSACTION_TYPE).

read here:Structure of a Trade Transaction (MqlTradeTransaction)

Second: To visualize results, we can extract this code block fromOrderSendAsync example

//+------------------------------------------------------------------+ 
//| TradeTransaction function                                        | 
//+------------------------------------------------------------------+ 
void OnTradeTransaction(const MqlTradeTransaction &trans, 
                        const MqlTradeRequest &request, 
                        const MqlTradeResult &result) 
  { 
//--- получим тип транзакции в виде значения перечисления  
   ENUM_TRADE_TRANSACTION_TYPE type=(ENUM_TRADE_TRANSACTION_TYPE)trans.type; 
//--- если транзакция является результатом обработки запроса, выведем только её название 
   if(type==TRADE_TRANSACTION_REQUEST) 
     { 
      Print(EnumToString(type)); 
      //--- выведем строковое описание обработанного запроса 
      Print("------------RequestDescription\r\n",RequestDescription(request)); 
      //--- выведем описание результата запроса 
      Print("------------ResultDescription\r\n",TradeResultDescription(result)); 
      //--- запомним тикет ордера для его удаления на следующей обработке в OnTick() 
      if(result.order!=0) 
        { 
         //--- удалим этот ордер по его тикету при следующем вызове OnTick() 
         order_ticket=result.order; 
         Print(" Тикет отложенного ордера ",order_ticket,"\r\n"); 
        } 
     } 
   else // для транзакций другого типа выведем полное описание 
//--- выведем описание полученной транзакции в Журнал 
      Print("------------TransactionDescription\r\n",TransactionDescription(trans));
 
//---      
  } 
//+------------------------------------------------------------------+ 
//| Возвращает текстовое описание транзакции                         | 
//+------------------------------------------------------------------+ 
string TransactionDescription(const MqlTradeTransaction &trans) 
  { 
//---  
   string desc=EnumToString(trans.type)+"\r\n"; 
   desc+="Symbol: "+trans.symbol+"\r\n"; 
   desc+="Deal ticket: "+(string)trans.deal+"\r\n"; 
   desc+="Deal type: "+EnumToString(trans.deal_type)+"\r\n"; 
   desc+="Order ticket: "+(string)trans.order+"\r\n"; 
   desc+="Order type: "+EnumToString(trans.order_type)+"\r\n"; 
   desc+="Order state: "+EnumToString(trans.order_state)+"\r\n"; 
   desc+="Order time type: "+EnumToString(trans.time_type)+"\r\n"; 
   desc+="Order expiration: "+TimeToString(trans.time_expiration)+"\r\n"; 
   desc+="Price: "+StringFormat("%G",trans.price)+"\r\n"; 
   desc+="Price trigger: "+StringFormat("%G",trans.price_trigger)+"\r\n"; 
   desc+="Stop Loss: "+StringFormat("%G",trans.price_sl)+"\r\n"; 
   desc+="Take Profit: "+StringFormat("%G",trans.price_tp)+"\r\n"; 
   desc+="Volume: "+StringFormat("%G",trans.volume)+"\r\n"; 
   desc+="Position: "+(string)trans.position+"\r\n"; 
   desc+="Position by: "+(string)trans.position_by+"\r\n"; 
//--- вернем полученную строку 
   return desc; 
  } 
//+------------------------------------------------------------------+ 
//| Возвращает текстовое описание торгового запроса                  | 
//+------------------------------------------------------------------+ 
string RequestDescription(const MqlTradeRequest &request) 
  { 
//--- 
   string desc=EnumToString(request.action)+"\r\n"; 
   desc+="Symbol: "+request.symbol+"\r\n"; 
   desc+="Magic Number: "+StringFormat("%d",request.magic)+"\r\n"; 
   desc+="Order ticket: "+(string)request.order+"\r\n"; 
   desc+="Order type: "+EnumToString(request.type)+"\r\n"; 
   desc+="Order filling: "+EnumToString(request.type_filling)+"\r\n"; 
   desc+="Order time type: "+EnumToString(request.type_time)+"\r\n"; 
   desc+="Order expiration: "+TimeToString(request.expiration)+"\r\n"; 
   desc+="Price: "+StringFormat("%G",request.price)+"\r\n"; 
   desc+="Deviation points: "+StringFormat("%G",request.deviation)+"\r\n"; 
   desc+="Stop Loss: "+StringFormat("%G",request.sl)+"\r\n"; 
   desc+="Take Profit: "+StringFormat("%G",request.tp)+"\r\n"; 
   desc+="Stop Limit: "+StringFormat("%G",request.stoplimit)+"\r\n"; 
   desc+="Volume: "+StringFormat("%G",request.volume)+"\r\n"; 
   desc+="Comment: "+request.comment+"\r\n"; 
//--- вернем полученную строку 
   return desc; 
  } 
//+------------------------------------------------------------------+ 
//| Возвращает текстовое описание результата обработки запроса       | 
//+------------------------------------------------------------------+ 
string TradeResultDescription(const MqlTradeResult &result) 
  { 
//--- 
   string desc="Retcode "+(string)result.retcode+"\r\n"; 
   desc+="Request ID: "+StringFormat("%d",result.request_id)+"\r\n"; 
   desc+="Order ticket: "+(string)result.order+"\r\n"; 
   desc+="Deal ticket: "+(string)result.deal+"\r\n"; 
   desc+="Volume: "+StringFormat("%G",result.volume)+"\r\n"; 
   desc+="Price: "+StringFormat("%G",result.price)+"\r\n"; 
   desc+="Ask: "+StringFormat("%G",result.ask)+"\r\n"; 
   desc+="Bid: "+StringFormat("%G",result.bid)+"\r\n"; 
   desc+="Comment: "+result.comment+"\r\n"; 
//--- вернем полученную строку 
   return desc; 
  }

and paste it into an Expert Advisor that can be attached to a chart. Then you can manually open/close positions and look at printout of results in Experts tab.

 
Vladimir Karputov:

No. While one function is counting, everything else will be skipped.

It is analogous totheSleep()function- that is, while your function is counting for a very long time, its behavior is anflogical to Sleep - all the rest events will be skipped.

Thank you, that's unfortunate.
And how to use the PC resource effectively then? Again looped code and periodical polling of parameters?

 
Vladimir Karputov:

Absolutely everything is transparent in OnTradeTransaction.

Thanks for the reply, that's pretty much what I did. More questions than insights so far...

 
Vladimir Karputov:

Please describe in more detail what exactly you want to get? Why do you call something from OnTradeTransaction?

First just in words, then we'll correct it in the right direction.

I understood that the problem is not with OnTradeTransaction. Look what a mess I've got here:

Here is the code.

 CPositionInfo PositionInfoKotiryemii,PositionInfoVedygii;
 
 if( !PositionInfoKotiryemii.Select("SBRF-3.18") )Print("Не удалось выбрать позицию по символ SBRF-3.18 ");
 if( !PositionInfoVedygii.Select("SBRF-12.17")   )Print("Не удалось выбрать позицию по символ SBRF-12.17 ");

 Print(PositionInfoKotiryemii.Symbol()," Объем ",PositionInfoKotiryemii.Volume()," ",PositionInfoVedygii.Symbol()," Объем ",PositionInfoVedygii.Volume());

And here is the result of its execution

2017.09.22 10:30:12 Failed to select position by symbol SBRF-12.17
2017.09.22 10:30:12 Volume 0.0 Volume 0. 0

I swap lines 2 and 3. i.e. the code is now

CPositionInfo PositionInfoKotiryemii,PositionInfoVedygii;
 
 if( !PositionInfoVedygii.Select("SBRF-12.17")   )Print("Не удалось выбрать позицию по символ SBRF-12.17 ");
 if( !PositionInfoKotiryemii.Select("SBRF-3.18") )Print("Не удалось выбрать позицию по символ SBRF-3.18 ");
 
 Print(PositionInfoKotiryemii.Symbol()," Объем ",PositionInfoKotiryemii.Volume()," ",PositionInfoVedygii.Symbol()," Объем ",PositionInfoVedygii.Volume());

I get a result like this.

2017.09.22 10:30:12 Failed to select position by symbol SBRF-12.17
2017.09.22 10:30:12 SBRF-3.18 Volume 1.0 SBRF-3.18 Volume 1.0

In both cases no warnings are generated by the compiler. Attached is the 80 line Expert Advisor code and testing settings. Broker BCS. The version 1730.

Ошибки - Инструменты - Пользовательский интерфейс - Справка по MetaEditor
Ошибки - Инструменты - Пользовательский интерфейс - Справка по MetaEditor
  • www.metatrader5.com
На данной вкладке отображается журнал компиляции программ, содержащий сообщения об использованных при компиляции файлах, а также ошибки и предупреждения, возникшие в этом процессе. — описание события. Иконки, расположенные слева от описания свидетельствуют о типе события. означает ошибку, — предупреждение, а — информационное сообщение; Если...
Files:
temp.mq5  7 kb
1.png  11 kb
 
pivomoe:

I realised that the problem is not with OnTradeTransaction. Look what a mess I've got going on:

Here's the code.

And here is the result of its execution

2017.09.22 10:30:12 Failed to select position by symbol SBRF-12.17
2017.09.22 10:30:12 Volume 0.0 Volume 0.0

I swap lines 2 and 3. i.e. the code is now

I get a result like this.

2017.09.22 10:30:12 Failed to select position by symbol SBRF-12.17
2017.09.22 10:30:12 SBRF-3.18 Volume 1.0 SBRF-3.18 Volume 1.0

In both cases no warnings are generated by the compiler. Attached is the 80 line Expert Advisor code and testing settings. Broker BCS. The version 1730.

I will reply this weekend. Sorry.

 

The error seems to be in trying to get information about more than 1 position, in 1 line(Print).

Only information about 1 (selected ) position is available at any time :

- In the second case it is correct, because last Select returns true , which you have not checked.

- And in the first case : last Select returns false , which you also didn't check, and the result is unpredictable.

..... obviously Select==false resets the information of the previous Select==true

Reason: