Questions from Beginners MQL5 MT5 MetaTrader 5 - page 223

 
Afternoon. Please help a beginner trader to find a suitable advisor for automated trading, which is able to open locked orders in currency pairs with the possibility of arbitrary take profit setting. Thank you.
 
abcxyzabcxyz:
Afternoon. Please help a beginner trader to find a suitable advisor for automated trading, which is able to open locked orders in currency pairs with the possibility of arbitrary take profit setting. Thank you.
If you really need locking you are on the right place. There is no locking on MetaTrader 5 as MetaTrader 5 is a netting platform.
MQL4: форум по механическим торговым системам и тестированию стратегий
  • www.mql5.com
MQL4: форум по механическим торговым системам и тестированию стратегий
 
micle:
Alternatively: declare Type method in all of them, in which return type identifier.

Heh, if you could edit the source code... You don't have to simplify things so much. And still - is there a class name in mql5?

 
YAndrey:

Heh, if you could edit the source code... You don't have to simplify things so much. Still - is there any way to find out the class name on mql5???

Look in the direction of templates. This code will return the name of the class or a primitive type.

#include<Trade\Trade.mqh>
//+------------------------------------------------------------------+
//||
//+------------------------------------------------------------------+
voidOnStart()
{
//---
CTrade trade;
double d_value=M_PI;
int i_value=INT_MAX;
Print("d_value: type=",GetTypeName(d_value),", value=", d_value);
Print("i_value: type=",GetTypeName(i_value),", value=", i_value);
Print("trade: type=",GetTypeName(trade);
//---
}
//+------------------------------------------------------------------+
//| Returns type in string form|
//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T&t)
{
//---return type as string
return(typename(T))
//---
}

 
C-4:

Look towards patterns. This code will return the name of a class or primitive type.

#include<Trade\Trade.mqh>
//+------------------------------------------------------------------+
//||
//+------------------------------------------------------------------+
voidOnStart()
{
//---
CTrade trade;
double d_value=M_PI;
int i_value=INT_MAX;
Print("d_value: type=",GetTypeName(d_value),", value=", d_value);
Print("i_value: type=",GetTypeName(i_value),", value=", i_value);
Print("trade: type=",GetTypeName(trade);
//---
}
//+------------------------------------------------------------------+
//| Returns type in string form|
//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T&t)
{
//---return type as string
return(typename(T))
//---
}

I've got something! But it doesn't work with new - in the code there is an example of what I need - may be someone can suggest how?

class a{
public:
virtual void Print(){Print("Print class a");}
};

class b:public a{
public:
virtual void Print(){Print("Print class b");}
};

class c:public a{
public:
virtual void Print(){Print("Print class c");}
void Print2(){Print("!Print2! class c");}
};


void add(a *&arr[], bool var)
{
   ArrayResize(arr, ArraySize(arr)+1);
   if (var)
      arr[ArraySize(arr)-1] = new b;
   else
      arr[ArraySize(arr)-1] = new c;
   
}

void OnStart()
  {
//--- 
   
   
   a *arr[];

   add(arr, true); // На самом деле здесь я НЕ знаю, какой класс добавит функция add
   add(arr, false); // Это потомок класса а или сам класс а, исходный код которого я править не могу.
   for (int i = 0; i < ArraySize(arr); i++)
   {
      // Вот тут то мне и надо узнать, что за класс там
      // шаблон вернет *а, как и объявлено. Но мне надо проверить - можно ли вызвать функцию, которая есть только в с
      if (i == 1) // Вот тут должна быть проверка на имя класса
      {
         c *tmp = arr[i];
         tmp.Print2();
      }
    }  
   
   
   
   
   
//--- 
  }
 
YAndrey:

I've got something! But it doesn't work with new - there's an example in the code of what I need - can anyone suggest any ways?

This is a template method problem. Unfortunately, the template method returns the name of the class referencing the instance. The type of the instance itself is still unknown.
 

Can someone explain me why this code does not work in the tester, while in real-time it works!!!? Specifically interested in why in the tester, after HistorySelect(0, TimeCurrent()) the HistoryOrderGetInteger...

#include <Trade\Trade.mqh>

CTrade trade;

int OnInit()
{
   trade.LogLevel(LOG_LEVEL_NO);
   return INIT_SUCCEEDED;
}
void OnTick()
{
   if(!DetectNewBar())return;
   trade.Sell(0.1);
   HistorySelect(0, TimeCurrent());
   for(; dealsCount < HistoryDealsTotal(); dealsCount++)
   {
      ulong ticket = HistoryDealGetTicket(dealsCount);
      RecalcDeal(ticket);
   }
}

bool DetectNewBar(void)
{
   MqlRates bars[1];
   CopyRates(Symbol(), PERIOD_M1, 0, 1, bars);
   if(bars[0].time != timeLastBar)
   {
      timeLastBar = bars[0].time;
      //printf(expertName + " new bar detected: " + TimeToString(bars[0].time));
      return true;
   }
   return false;
}

void RecalcDeal(ulong ticketDeal)
{
   //History is selected in OnTick()!
   ulong ticketOrder = HistoryDealGetInteger(ticketDeal, DEAL_ORDER);
   //if(!HistoryOrderSelect(ticketOrder))
   //   printf("order not select.");
   ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticketOrder, ORDER_TYPE);
   datetime time = HistoryOrderGetInteger(ticketOrder, ORDER_TIME_SETUP); 
   ulong time_msc = HistoryOrderGetInteger(ticketOrder, ORDER_TIME_SETUP_MSC); 
   printf("Order: " + (string)ticketOrder + " Type: " + EnumToString(type) + " Time: " + (string)time +
          " Time msc: " + (string)time_msc + " Total Orders: " + HistoryOrdersTotal());
}

int dealsCount;

datetime timeLastBar;

Screenshot in the strategy tester:

Real-time screenshot in the demo:

p.s. What is interesting, the first order in the tester is handled correctly but the others are not. Also, if we comment HistroryOrderSelect(ticketOrder), we get a message in the Strategy Tester that the order has not been selected and in the Strategy Tester, everything starts working, except for the first order.

 

And I have some problem with HistorySelect(). I open a position with the script by sending a market order, and if a deal has opened, I immediately look at the number of deals in the history since the script was launched, and I check it 10 times at an interval of a second. Obviously, there should be one trade. Here is the script:

void OnStart()
{
        // время запуска скрипта
        datetime dtStartTime = TimeCurrent();
        
        // структуры запроса
        MqlTradeRequest oRequest = {0};
        MqlTradeResult oResult = {0};
        
        // формируем запрос
        oRequest.action = TRADE_ACTION_DEAL;
        oRequest.magic  = 15;
        oRequest.symbol = _Symbol;
        oRequest.volume = 0.1;
        oRequest.type   = ORDER_TYPE_BUY;
        oRequest.type_filling = ORDER_FILLING_FOK;
        oRequest.price  = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        oRequest.deviation = 1000;
        
        // шлём ордер
        bool bResult = OrderSend(oRequest, oResult);
        
        // если позиция успешно открыта
        if(bResult == true && oResult.retcode == 10009) // если позиция открыта
        {
                for(int i = 0; i < 10; i++)
                {
                        // запрашиваем историю за время работы скрипта
                        HistorySelect(dtStartTime, TimeCurrent());
                
                        // количество сделок за время работы скрипта (должна быть одна)
                        Print("Шаг: ", i, " Совершено сделок: ", HistoryDealsTotal());
                        
                        Sleep(1000);
                }
        }
}

And here is the result in Alfa-Forex:

A trade is actually made, but it's not in the history even after 10 seconds. What is it? A MT bug? Alpha glitch? Some kind of chip that I don't know? Alpari's script works normally, only occasionally zero is detected at the first (zero) step (well, it is understandable - the history has not yet had time to update), all other steps are one. But after ten seconds, why is there no deal in the history?

 
Algo:

And I have some problem with HistorySelect(). I open a position with the script by sending a market order, and if a deal has opened, I immediately look at the number of deals in the history since the script was launched, and I check it 10 times at an interval of a second. Obviously, there should be one trade. Here is the script:

And here is the result from the Alpha broker:

A trade is actually made, but it's not in the history even after 10 seconds. What is this? A MT bug? Alpha glitch? Some kind of chip that I don't know? Alpari's script works normally, only occasionally zero is detected at the first (zero) step (well, it is understandable - the history has not yet had time to update), all other steps are one. But why is there no deal in the history in ten seconds?

What bothers me is the following line

datetime dtStartTime = TimeCurrent();

Are you sure that dtStartTime and TimeCurrent() are not the same number by the moment for? Maybe the rounding to one second puts the completed transaction outside of dtStartTime.

 
C-4:

The line

datetime dtStartTime = TimeCurrent();

Are you sure that dtStartTime and TimeCurrent() are not the same number by the time for? Perhaps the rounding to one second puts the completed transaction outside of dtStartTime.

And even if it's one, shouldn't MT output the history for that second? I.e. doesn't it output the history within the specified limits, INCLUDING the limits themselves?

But anyway, I tried writing both dtStartTime = TimeCurrent() - 1, and dtStartTime = TimeCurrent() - 10. Doesn't work.