Questions from Beginners MQL5 MT5 MetaTrader 5 - page 983

 

Hello colleagues.

Question: In mql4, in order to calculate the number of positions, you can write the function like this

//+------------------------------------------------------------------+
// Счетчик ордеров
//+------------------------------------------------------------------+
int OrderCount(int type)
{
  int count = 0;
  for (int trade = OrdersTotal() -1; trade >=0; trade--)
  {
    if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
    {
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == type)
      count++;
    }
  }
  return(count);
}

How is it implemented in mql5? How can I calculate the number of positions by magik or by type?

 
Comments not related to this topic have been moved to "Questions from MQL4 MT4 MetaTrader 4 beginners".
 
Nikita Chernyshov:

Hello colleagues.

Question: In mql4, in order to calculate the number of positions, you can write the function like this

How is it implemented in mql5? How can we calculate the number of positions by a magic number or by a type?

Example inEhlers_CG EA code, function CalculateAllPositions.

 
Vladimir Karputov:

Example inEhlers_CG EA code, function CalculateAllPositions.

Thank you very much. Tried to change it to a more understandable form. But it returns 0 and opens endless orders, please advise, where have I screwed up? I do not want to pay attention to my trading idea, I just want to learn it in general.


#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Expert\Money\MoneyFixedMargin.mqh>

CPositionInfo  m_position;                   // trade position object
CTrade         trade;                      // trading object
CSymbolInfo    symbol_info;                     // symbol info object
CAccountInfo   m_account;                    // account info wrapper
CDealInfo      m_deal;                       // deals object
COrderInfo     m_order;                      // pending orders object
CMoneyFixedMargin *m_money;


input double lot = 0.01;
input int    TakeP = 300;
input int    StopL = 300;
input int    Magic = 123;
input int    Slip  = 50;

input int    MA    = 50;

double ma[];
int    handle;
int    digits;
double point;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   handle = iMA(NULL,0,MA,0,MODE_SMA,PRICE_CLOSE);
   
   trade.SetExpertMagicNumber(Magic);
   trade.SetDeviationInPoints(Slip);
   trade.SetTypeFilling(ORDER_FILLING_FOK);
   trade.SetAsyncMode(false);
   
   digits=(int)SymbolInfoInteger(NULL,SYMBOL_DIGITS);
   point=SymbolInfoDouble(NULL,SYMBOL_POINT);
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   CopyBuffer(handle,0,0,50,ma);
   ArraySetAsSeries(ma,true); 
   
   double Ask=SymbolInfoDouble(NULL,SYMBOL_ASK);
   double Bid=SymbolInfoDouble(NULL,SYMBOL_BID);
   
   if(Ask > ma[1] && CalculateAllPositions(POSITION_TYPE_BUY) == 0)
     {
       double tp = NormalizeDouble(Ask+TakeP*point,digits);
       double sl = NormalizeDouble(Ask-StopL*point,digits);
       
       if(!trade.Buy(lot,NULL,Ask,sl,tp))
          {
      //--- сообщим о неудаче
      Print("Метод Buy() потерпел неудачу. Код возврата=",trade.ResultRetcode(),
            ". Описание кода: ",trade.ResultRetcodeDescription());
          } else
               {
                 Print("Метод Buy() выполнен успешно. Код возврата=",trade.ResultRetcode(),
                 " (",trade.ResultRetcodeDescription(),")");
               }
     }
     
   if(Bid < ma[1] && CalculateAllPositions(POSITION_TYPE_SELL) == 0)
     {
       double tp = NormalizeDouble(Bid-TakeP*point,digits);
       double sl = NormalizeDouble(Bid+StopL*point,digits);
       
       if(!trade.Sell(lot,NULL,Bid,sl,tp))
          {
      //--- сообщим о неудаче
      Print("Метод Sell() потерпел неудачу. Код возврата=",trade.ResultRetcode(),
            ". Описание кода: ",trade.ResultRetcodeDescription());
          } else
               {
                 Print("Метод Sell() выполнен успешно. Код возврата=",trade.ResultRetcode(),
                 " (",trade.ResultRetcodeDescription(),")");
               }
     }     
   Comment(CalculateAllPositions(POSITION_TYPE_BUY));
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Счетчик ордеров                                                  |
//+------------------------------------------------------------------+
int CalculateAllPositions(const ENUM_POSITION_TYPE type)
  {
   int count=0;   
  
   for(int i=PositionsTotal()-1;i>=0;i--)
      {
      if(m_position.SelectByIndex(i)) 
        {
         if(m_position.Symbol()==NULL && m_position.Magic()==Magic && m_position.PositionType()==type)
         count++;
       }
         
     }
    return(count);
  }
 
Nikita Chernyshov:

Thank you very much. Tried to change it to a form that makes more sense to me. But it returns 0 and opens endless orders, please advise, where did I screw up? Please do not pay attention to my trading idea, I am just trying to get acquainted with it.


The key word of your error is that I have not written so much verification code in my EAs for nothing. You have left out almost all the innards, and in particular OnTradeTransaction.

 

I faced a problem, the indicator based EA works correctly on the real account, but it is lying in the tester, in tick generation modes both by OHLC and by all ticks - the result is the same. The result of the error is the empty buffer of the indicator at zero bar (only when there is a new bar at the upper TF, which is used for the calculation of the indicator). However, I have managed to make indicator to be calculated by adding Sleep to my Expert Advisor. But I have found out that depending on the mode of ticks generation this Sleep should be different - for generation from all ticks Sleep(15000) is enough, while for OHLC Sleep(30000) is needed.

So the question arises - is the situation with Sleep normal, because it logically turns out that different delay times are modeled there depending on the mode of ticks generation!

Dear developers, I ask you to explain the situation with the indicator, because I myself cannot understand what the reason is - a bug in the code or in the tester!

I am ready to give the indicator and the Expert Advisor in the PM, but tell me to whom.

 
Aleksey Vyazmikin:

I faced a problem, the indicator based EA works correctly on the real account, but it is lying in the tester, in tick generation modes both by OHLC and by all ticks - the result is the same. The result of the error is the empty buffer of the indicator at zero bar (only when there is a new bar at the upper TF, which is used for the calculation of the indicator). But I have managed to make indicator to be calculated by adding Sleep, and it was found out, that depending on the mode of ticks generation this Sleep should be different - for generation from all ticks Sleep(15000) is enough, but for OHLC Sleep(30000) is needed.

So the question arises - is the situation with Sleep normal, because it logically turns out that different delay times are modeled there depending on the mode of ticks generation!

Dear developers, I ask you to explain the situation with the indicator, because I myself cannot understand what the reason is - a bug in the code or in the tester!

I am ready to give you the indicator and EA in the PM, but tell me to whom.

Sleep does not work in this indicator. Moreover, it is ignored even in the Expert Advisor, if we are talking about the tester.

 
Ihor Herasko:

Sleep does not work in the indicator. Moreover, it is ignored even in the Expert Advisor, if we are talking about the tester.

I have already written that Sleep is in the Expert Advisor, and if it is ignored, and you are 100% sure about it, then it is an extra confirmation that the error is in the tester.

The delay may not occur in time, but it may be emulated for the program.

Added: Sleep works in the tester, here is a simple code that confirms it

   Print(iClose(Symbol(),PERIOD_CURRENT,0));
   Sleep(15000);
   Print(iClose(Symbol(),PERIOD_CURRENT,0));

Result

2019.01.22 08:28:24.661 2019.01.21 23:49:00   66920.0
2019.01.22 08:28:24.661 2019.01.21 23:49:15   66928.0
 
Ihor Herasko:

Sleep does not work in the indicator. Moreover, it is ignored even in the EA when it comes to the tester.

It is not.

 
Aleksey Vyazmikin:

I have already written that Sleep is in the EA, and if it is ignored, and you are 100% sure of this, then it is an extra confirmation that the error is in the tester.

The delay may not occur in time, but it may be emulated for the program.

Added: Sleep works in the tester, here is a simple code that confirms it

Result

This was originally the case in your post:

However, I managed to get the indicator to read by adding Sleep, and here it was revealed...

That's why I reacted to Sleep in the indicator.

And about Sleep in the EA, I don't understand why you had to make it behave differently in 4 and in 5. In 4, it's like that:

void OnTick()
{
   Print("Before: ", TimeCurrent());
   Sleep(100000);
   Print("After: ", TimeCurrent());
}
2019.01.22 07:38:19.432 2018.11.08 00:02:05  Test AUDUSD,M5: After: 2018.11.08 00:02:05
2019.01.22 07:38:19.432 2018.11.08 00:02:05  Test AUDUSD,M5: Before: 2018.11.08 00:02:05
As for the fact of the question. Sleep should not have any effect on the recalculation of data in the indicator. Something is wrong with buffer filling. Maybe there is a reproducible piece of code?
Reason: