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

 
Vladimir Pastushak:

How do I know the type of input parameter?

the compiler itself substitutes the types at the moment of template function call, if such call was not yet in the code, then the compiler will create another function copy and set the types itself - well, as if logically - a template


if the question is about how to define the type in such a function, use

typename

UPD: added to the example above the parameter type printers:

#define  PRINT(VAL) Print(#VAL," = ",VAL, ", typename = ", typename(VAL))
template<typename T1, typename T2>
int myfunc(T1 val1=0, T2 val2=0)
{
   Print(__FUNCSIG__);
   PRINT(val1);
   PRINT(val2);
   return((int) (val1 + val2));
}

//+------------------------------------------------------------------+
void OnStart()
{
   int i1 = 2, i2 = 3;
   Print(myfunc(i1, i2));
   double d1 = 10.0, d2 = 30.0;
   Print(myfunc(d1, d2));
}
//+------------------------------------------------------------------+

2020.09.16 18:58:21.679 tst (EURUSD,M5) int myfunc<int,int>(int,int)

2020.09.16 18:58:21.680 tst (EURUSD,M5) val1 = 2, typename = int

2020.09.16 18:58:21.681 tst (EURUSD,M5) val2 = 3, typename = int

2020.09.16 18:58:21.681 tst (EURUSD,M5) 5

2020.09.16 18:58:21.681 tst (EURUSD,M5) int myfunc<double,double>(double,double)

2020.09.16 18:58:21.681 tst (EURUSD,M5) val1 = 10.0, typename = double

2020.09.16 18:58:21.681 tst (EURUSD,M5) val2 = 30.0, typename = double

2020.09.16 18:58:21.681 tst (EURUSD,M5) 40


UPD: added__FUNCSIG__ to this example

 

Afternoon.
I am facing some strange thing when writing an indicator in MQL5 (indicator in a separate subwindow, 4 lines).

The initial buffer descriptions are as follows:

//------------------------------------------------------------------
#property indicator_buffers   6
#property indicator_plots     4
//-------------------------------------------------------------------
// == RSI ==
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrMagenta
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
//------------------------------------------------------------------
// == MA_fast ==
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2
//------------------------------------------------------------------
// == MA_slow ==
#property indicator_type3   DRAW_COLOR_LINE
#property indicator_color3  clrWhite, clrBlack
#property indicator_style3  STYLE_SOLID
#property indicator_width3  3
//------------------------------------------------------------------
// == MA_slow_glob ==
#property indicator_type4   DRAW_COLOR_LINE
#property indicator_color4  clrYellow, clrRed
#property indicator_style4  STYLE_SOLID
#property indicator_width4  2
//------------------------------------------------------------------
//--- buffers (массивы под буферы индикатора)
//--------------------------------------------------------------------
double      RSI[];                                                         // буфер под RSI
//--------------------------------------------------------------------
double      MAr1_fast[];                                                   // буфер под быструю МА
double      MAr2_slow[];                                                   // буфер под медленную МА
double      MAr2_slowColor[];                                              // буфер под цвета медленной МА
//--------------------------------------------------------------------
double      MAr3_slow_glob[];                                              // буфер под глобальную медленную МА
double      MAr3_slow_globColor[];                                         // буфер под цвета глобальной медленной МА
//--------------------------------------------------------------------

Next in OnInit:

   //--------------------------------------------------------------------
   SetIndexBuffer       (0,   RSI,                 INDICATOR_DATA);
   ArraySetAsSeries     (     RSI,                 true);
   PlotIndexSetString   (0,   PLOT_LABEL,          "RSI(" + IntegerToString(RSI_per) + ")");
   PlotIndexSetInteger  (0,   PLOT_SHOW_DATA,      true);
   PlotIndexSetInteger  (0,   PLOT_DRAW_BEGIN,     RSI_per);
   PlotIndexSetDouble   (0,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------
   SetIndexBuffer       (1,   MAr1_fast,           INDICATOR_DATA);
   ArraySetAsSeries     (     MAr1_fast,           true);
   PlotIndexSetString   (1,   PLOT_LABEL,          "MA (" + IntegerToString(MA_fast_period) + "), EMA");
   PlotIndexSetInteger  (1,   PLOT_SHOW_DATA,      true);
   PlotIndexSetInteger  (1,   PLOT_DRAW_BEGIN,     MA_fast_period);
   PlotIndexSetDouble   (1,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------
   SetIndexBuffer       (2,   MAr2_slow,           INDICATOR_DATA);
   ArraySetAsSeries     (     MAr2_slow,           true);
   PlotIndexSetString   (2,   PLOT_LABEL,          "MA (" + IntegerToString(MA_slow_period) + "), SMA");
   PlotIndexSetInteger  (2,   PLOT_SHOW_DATA,      true);
   PlotIndexSetInteger  (2,   PLOT_DRAW_BEGIN,     MA_slow_period);
   PlotIndexSetDouble   (2,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------
   SetIndexBuffer       (3,   MAr2_slowColor,      INDICATOR_COLOR_INDEX);
   ArraySetAsSeries     (     MAr2_slowColor,      true);
   PlotIndexSetDouble   (3,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------
   SetIndexBuffer       (4,   MAr3_slow_glob,      INDICATOR_DATA);
   ArraySetAsSeries     (     MAr3_slow_glob,      true);
   PlotIndexSetString   (4,   PLOT_LABEL,          "MA (" + IntegerToString(MA_slow_glob_period) + "), SMA");
   PlotIndexSetInteger  (4,   PLOT_SHOW_DATA,      true);
   PlotIndexSetInteger  (4,   PLOT_DRAW_BEGIN,     MA_slow_glob_period);
   PlotIndexSetDouble   (4,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------
   SetIndexBuffer       (5,   MAr3_slow_globColor, INDICATOR_COLOR_INDEX);
   ArraySetAsSeries     (     MAr3_slow_globColor, true);
   PlotIndexSetDouble   (5,   PLOT_EMPTY_VALUE,    EMPTY_VALUE);
   //--------------------------------------------------------------------

Essentially: the indicator draws 4 lines: the first two are just single-coloured, the next two are bicoloured (they change colour on kinks).

Bicolor is due to the way of drawing DRAW_COLOR_LINE.

Question: first line (buffers 2 and 3 in the code above) is perfectly drawn and all code written for it in OnInit works;
second line shows up for some reason, for example line doesn't work:

PlotIndexSetString   (4,   PLOT_LABEL,          "MA (" + IntegerToString(MA_slow_glob_period) + "), SMA");
I.e. instead of the text I set in the data window, just the name of the indicator is displayed in place of the buffer. Although the line itself is drawn, and it is, as it should be, multicoloured.
I think the trick is in the numbering shift? For example, I'm not sure why in the upper part of the code, when I declare the last line with #property directive, the index should be 4, not 5, as 4 buffers have already been used before. Is there any relation at all between line numbering when declaring with #property and buffer numbering when linking with arrays in OnInit?

Please advise what is wrong in the code above. Maybe someone can find an example of indicator where at least two lines are drawn using DRAW_COLOR_LINE.... drawing method

One more related question: how do the colorful line buffers get tied together? I mean, how does the compiled code know that if I put a value into a colour buffer, this colour should be used to colour a line from some other buffer?

 
satorifx:

Afternoon.
I am facing some strange thing when writing an indicator in MQL5 (indicator in a separate subwindow, 4 lines).

The initial buffer descriptions are as follows:

Next in OnInit:

Essentially: the indicator draws 4 lines: the first two are just single-coloured, the next two are bicoloured (they change colour on kinks).

Bicolor is due to the way of drawing DRAW_COLOR_LINE.

Question: first line (buffers 2 and 3 in the code above) is perfectly drawn and all code written for it in OnInit works;
second line shows up for some reason, for example line doesn't work:

I.e. instead of the text I set in the data window, just the name of the indicator is displayed in place of the buffer. Although the line itself is drawn, and it is, as it should be, multicoloured.
I think the trick here is in the numbering shift? For example, I'm not sure why in the upper part of the code, when I declare the last line with #property directive, the index should be 4, not 5, as 4 buffers have already been used before. Is there any relation at all between line numbering when declaring with #property and buffer numbering when linking with arrays in OnInit?

Please advise what is wrong in the code above. Maybe someone can find an example of indicator where at least two lines are drawn using DRAW_COLOR_LINE.... drawing method

One more related question: how do the colorful line buffers get tied together? I mean, how does the compiled code know that if I put a value into a colour buffer, this colour should be used to colour a line from some other buffer?

Mappings are numbered differently than buffers.

PlotIndexSetString   (3,   PLOT_LABEL,          "MA (" + IntegerToString(MA_slow_glob_period) + "), SMA");

This should work.

 

Good afternoon everyone!

I made a function to modify stoploss. But when it works it gives out EURUSD,H1: OrderModify error 130.

And the price is far from the place where stoploss should be set.

Here is the function:

void open_bu(string walpa, int op)
{
bool err;
int spred=(int)MarketInfo(walpa,MODE_SPREAD);
double point=MarketInfo(walpa,MODE_POINT);
int digits=(int)MarketInfo(walpa,MODE_DIGITS);
for(int is=OrdersTotal()-1; is>=0; is--)
 {
  if(OrderSelect(is, SELECT_BY_POS, MODE_TRADES) && OrderSymbol()==walpa)
   {
    if(OrderType()==op && NormalizeDouble(OrderStopLoss(),digits) < NormalizeDouble(OrderOpenPrice()+spred*point, digits) )
     {
      err=OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()+spred*point, digits), OrderProfit(), 0, clrNONE);
      if(!err) error(GetLastError());
     }
    if(OrderType()==op && (NormalizeDouble(OrderStopLoss(),digits) > NormalizeDouble(OrderOpenPrice()-spred*point, digits) || OrderStopLoss()==0))
     {
      Print(walpa,"  ",spred,"   ",point,"   ",digits,"     ",NormalizeDouble(OrderOpenPrice()-spred*point, digits));
      err=OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice()-spred*point, digits), OrderProfit(), 0, clrNONE);
      if(!err) error(GetLastError());
     }
   }
 }
return;
}
 
Good day. I want to write an EA based on measuring the angle of slope of a moving average (or better a set of them, namely the Alligator), so that the EA would give an alert on a strong price impulse, preferably with a small lag. Please advise how to measure the angle of the MA or "tell the EA" that the pulse occurred. Maybe there are already known ways to do that. Or for example a free indicator based on impulse calculation?
 

Wrote a function to find the bar number of a fractal out of 3 bars. On the online chart it seems to find it correctly. But during visual testing in the tester it lies. May any of the professionals take a look at the code and find some errors?

I'd be most grateful.

//+----------------------------------------------------------------------------+
//|  Описание : Возвращает номер бара трёхбарного фарактала по его номеру.     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента        ("" или NULL - текущий символ)     |
//|    tf - таймфрейм                       (    0       - текущий ТФ)         |
//|    nf - номер экстремума                (    0       - последний)          |
//+----------------------------------------------------------------------------+
int BarLocExtr(string sy="0", int tf=0, int ne=0, int mode=MODE_UPPER)
{
 if(sy=="" || sy=="0") sy=Symbol();
 int nlext=0,k=iBars(sy,tf);
 nlext=0;
 if(mode==MODE_UPPER)
   {
    for (int i=2; i<=k; i++)
     {
      if(High[i]>High[i+1] && High[i]>High[i-1])
        {
         nlext++;
         
         if(nlext>ne) return(i);
        }
     }    
   }        
 if(mode==MODE_LOWER)
   {
    for (i=2; i<=k; i++)
     {
      if(Low[i+1]>Low[i] && Low[i-1]>Low[i])
        {
         nlext++;
         if(nlext>ne) 
           {
            //Print("i=",i," Low[i+1]=",Low[i+1]," Low[i]=",Low[i]," Low[i-1]=",Low[i-1]);
            return(i); 
           }
        }
     }    
   }       
    Print("Бар локального экстремума не найден");
    return(-1);     
  }
Как в MetaTrader 5 быстро разработать и отладить торговую стратегию
Как в MetaTrader 5 быстро разработать и отладить торговую стратегию
  • www.mql5.com
Скальперские автоматические системы по праву считаются вершиной алгоритмического трейдинга, но при этом они же являются и самыми сложными для написания кода. В этой статье мы покажем, как с помощью встроенных средств отладки и визуального тестирования строить стратегии, основанные на анализе поступающих тиков. Для выработки правил входа и...
 

Good afternoon. WHAT CODE SHOULD I ADD SO THAT THE INDICATOR STOPS WORKING IN THE TESTER AFTER A MONTH ? I.E. I WROTE ALL OK ! BUT WHEN I DO A BACKTEST IT WORKS AGAIN. (mgl4)

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
  datetime data=D'2020.09.16 20:07';  // Time Block
    if(TimeCurrent()>data)  
      {
       Print("Демонстрационный период закончился, покупайте индикатор :)");
       Alert("Демонстрационный период закончился, покупайте индикатор :)");
       return(INIT_FAILED);
     } 
  
  
  if(IsTesting() && TimeCurrent() >= D'2020.09.16 20:07')// для тестировщиков, ограничение работы по времени
{
    Comment("Демонстрационный период закончился, покупайте индикатор :)  Демонстрационный период закончился, покупайте индикатор :)   Демонстрационный период закончился, покупайте индикатор :)");
    return(0);
}    
     
Files:
 

Hello!

I wanted to put a condition in the order closing cycle onthe order opening day, so that the ones that were opened on Friday would not be closed.

while (OrdersTotal()>0)
    { 
      if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))  
        {   
            if ((OrderMagicNumber()==Magic) && (TimeDayOfWeek(OrderOpenTime())<5)) 
            {    
               if (OrderType()==OP_BUY)          result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(nameSym,MODE_BID),MarketInfo(nameSym,MODE_DIGITS)),3,CLR_NONE); 
               if (OrderType()==OP_SELL)  result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(nameSym,MODE_ASK),MarketInfo(nameSym,MODE_DIGITS)),3,CLR_NONE); 
            
                 if(result!=TRUE) { error=GetLastError();
                    Print("LastError = ",error, " ",Symbol()); }
                 else error=0; 
            }
            else  Print("NoMagic ", OrderMagicNumber());  // for Debug
         }
        else Print( "Error when order select ", GetLastError());
   
     } 
 
Tabazhan_Dajhiov:

Good afternoon. WHAT CODE SHOULD I ADD SO THAT THE INDICATOR STOPS WORKING IN THE TESTER AFTER A MONTH ? I.E. I WROTE ALL OK ! BUT WHEN I DO A BACKTEST IT WORKS AGAIN. (mgl4)

You need to write this code not in OnInit, but in OnTick().

 
Yerkin Sagandykov:

Hello!

I wanted to put a condition in the order closing cycle onthe order opening day, so that the ones opened on Friday would not be closed.

Try it this way:

for(int is=OrdersTotal()-1; is>=0; is--)
    { 
      if(OrderSelect(is,SELECT_BY_POS,MODE_TRADES))  
        {   
            if ((OrderMagicNumber()==Magic) && (TimeDayOfWeek(OrderOpenTime())<5)) 
            {    
               if (OrderType()==OP_BUY)   result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(nameSym,MODE_BID),MarketInfo(nameSym,MODE_DIGITS)),3,CLR_NONE); 
               if (OrderType()==OP_SELL)  result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(nameSym,MODE_ASK),MarketInfo(nameSym,MODE_DIGITS)),3,CLR_NONE); 
            
                 if(result!=TRUE) { error=GetLastError();
                    Print("LastError = ",error, " ",Symbol()); }
                 else error=0; 
            }
            else  Print("NoMagic ", OrderMagicNumber());  // for Debug
         }
        else Print( "Error when order select ", GetLastError());
   
     } 

Reason: