Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 785

 
Seric29:

Is it necessary to writetempl(T1) in front of each functionand it will take a variable or the required argument? Why istempl(T) declaredandtempl(T1) called, should I add a number before each function(templ(T1)templ(T2)templ(T3)) or should I writetempl(T1) everywhere?And if several parameters are scored intemplate<typename T>then how would it be, like thistemplate<typename T,typename P,typename Q>-templ(T,P,Q).

Yes, the record is still done before each function, where you want to turn a normal function into a function template. It's just this record is noticeably shorter now.
T1 is a name that denotes some type of data, which is stored in a variable with its name (a). It is not necessary to add a number. You can use the same name everywhere, even the same T without a number.
The templ is not called, but is automatically replaced with what is prepended to it in #define. This is a simple replacement of one text with another, but you can write the input parameters in brackets, just like functions.

#define  templ(T) template<typename T> // один входной параметр именуемый буквой "T" т. е. "T" это просто имя.

templ(T1) T1 Funct(T1 a) { return a;} // функция вернёт тот же тип, что и будет передан при вызове это функции

At compile time templ(T1) expression will be replaced with template<typename T1> and you will get this

template<typename T1>
T1 Funct(T1 a) { return a;}

For multiple parameters, yes, you guessed correctly how to describe.

Макроподстановка (#define) - Препроцессор - Основы языка - Справочник MQL4
Макроподстановка (#define) - Препроцессор - Основы языка - Справочник MQL4
  • docs.mql4.com
Директива #define подставляет expression вместо всех последующих найденных вхождений identifier в исходном тексте. identifier заменяется только в том случае, если он представляет собой отдельный токен. identifier не заменяется, если он является частью комментария, частью строки, или частью другого более длинного идентификатора. expression...
 
Ilya Prozumentov:

I see, thank you for the information, I've already tried it out - it's handy.

 
Vitaly Muzichenko:

I understand that you need to select via switch, and enter the names there

Your code prints an int value, while you need to select a string


I would use an array of string constants to select the indicator name, i.e. my example gives you the number of the record when the user selects it, and this number can be the number of an element (index) of the string array, where you would store the text names of indicators

sorry i don't have a terminal, i can't show the example in the code, but i think i've explained the idea

PS:

#property strict
#property show_inputs
enum Eind {
 ind_1, // Indicator 1
 ind_2, // Indicator 2
 ind_3, // Indicator 3
 ind_4  // Indicator 4
};

input Eind param = ind_1;
const string IndicatorName[] = {"Moving Average","ADX","ZigZag","Fractals"};
//+------------------------------------------------------------------+
void OnStart()
  {
   Alert("Выбран :",param, " . Удаляю индикатор : ",IndicatorName[param]);
  }
//+------------------------------------------------------------------+
 
Igor Makanu:

I would use an array of string constants to select the name of the indicator, i.e. my example gives you the number of the record when selected by the user, and this number can be the number of the element (index) of the string array where you will save the text names of the indicators

sorry i don't have a terminal, i can't show the example in the code, but i think i've explained the idea

PS:

Thanks, I did, it's quite handy.

And the final version, this is just the bomb. I've been missing this for a long time, as I have at least 20 charts open in the terminal

Delete Indicators
Delete Indicators
  • www.mql5.com
Удаляет выбранные индикаторы со всех графиков
 
Hello all. Help, please. I want the EA to wait for n hours after closing a trade. Can I also tweak this function. Would it be correct to change Mode_Trades to Mode_History? Thank you
int BarsAfterOrderBuy()
{
datetime t=0;int i;
for(i=OrdersHistoryTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
{if(t<OrderOpenTime())t=OrderOpenTime();}
return(iBarShift(Symbol(),0,t,true));
}
 
Carcass77:
Hi all. Help, please. I want the EA to wait for n hours after closing a trade. Can I also tweak this function. Would it be correct to change Mode_Trades to Mode_History? Thank you

MODE_HISTORY - of course it is needed, but there is another point: in the text "after closing" and in the codeOrderOpenTime

And don't go to bars, return time t and then use it somehow:

if(TimeCurrent()>t+n*3600) {можно открывать}
 
Igor Zakharov:

MODE_HISTORY - of course it is needed, but there is another point: in the text "after closing" and in the codeOrderOpenTime

And don't go to bars, return time t and then use it somehow:


I corrected to Mode_History, that's how the owl doesn't open the first order. Can you elaborate on the solution? Thanks

 
Carcass77:

I corrected to Mode_History, so the owl doesn't open the first order. Can you please elaborate on the solution? Thanks

Take a look at this.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает количество секунд после закрытия последней позиций. |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
datetime SecondsAfterCloseLastPos(string sy="",int op=-1,int mn=-1) 
  {
   datetime t=0;
   int      i,k=OrdersHistoryTotal();

   if(sy=="0") sy=Symbol();
   for(i=0; i<k; i++) 
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) 
        {
         if(OrderSymbol()==sy || sy=="") 
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
              {
               if(op<0 || OrderType()==op) 
                 {
                  if(mn<0 || OrderMagicNumber()==mn) 
                    {
                     if(t<OrderCloseTime()) t=OrderCloseTime();
                    }
                 }
              }
           }
        }
     }
   return(TimeCurrent()-t);
  }
 
Alekseu Fedotov:

Take a look at this.

How does the first order get resolved?

 
Carcass77:

And how do you resolve the first order?

Please note, the function has changed slightly.

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
// здесь пофиг какой символ и какая позиция ... последняя позиция и все
  int ClosePos = SecondsAfterCloseLastPos();
  
  
// здесь по тек. символу и пофиг какая позиция 
//  int ClosePos = SecondsAfterCloseLastPos(Symbol());  

// здесь по тек. символу и OP_BUY позиция 
//  int ClosePos = SecondsAfterCloseLastPos(Symbol(),OP_BUY); 

// здесь по тек. символу , OP_BUY позиция , и магик  5 
//  int ClosePos = SecondsAfterCloseLastPos(Symbol(),OP_BUY,5);

// продажи,  вместо OP_BUY прописываем  OP_SELL.

   if(ClosePos > 3600 || ClosePos == 0 )  {/*можно открывать*/}
   
  }
//+------------------------------------------------------------------+
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает количество секунд после закрытия последней позиций. |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int SecondsAfterCloseLastPos(string sy="",int op=-1,int mn=-1) 
  {
   datetime t=0;
   int      i,k=OrdersHistoryTotal();

   if(sy=="0") sy=Symbol();
   for(i=0; i<k; i++) 
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) 
        {
         if(OrderSymbol()==sy || sy=="") 
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
              {
               if(op<0 || OrderType()==op) 
                 {
                  if(mn<0 || OrderMagicNumber()==mn) 
                    {
                     if(t<OrderCloseTime()) t=OrderCloseTime();
                    }
                 }
              }
           }
        }
     }
  int CloseTime; 
     if(t==0)
        CloseTime=0;
     else 
        CloseTime = int(TimeCurrent()-t);
      
   return(CloseTime);
  }
//+----------------------------------------------------------------------------+  
Reason: