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

 
Alexey Viktorov:
Set the display colour to clrNONE.

So you can only output the buffer, but not the variable separately?

 
psyman:

So you can only output a buffer, but not a variable separately?

Yes, that's the only way. And one more trick that may come in handy, if you set SetIndexLabel(0, ""); then these values will not be displayed in the data window. And even the iCustom() function will not be available.
 
Igor Makanu:

Thank you for answering.

So what I understand is to create a buffer, then fill it with

with RSI values and then feed this buffer withiMAOnArray().

Has anyone did this for EA and it will be displayed when testing EA in the subwindow?

Usually EA tests through iCustom are sluggish.

 

Took the code from the example in https://www.mql5.com/ru/docs/strings/stringadd and pasted it into the script. The result is the same in MQL4 and MQL5:


HE      0       22:42:49.015    Test Script (EURUSD,H1) time for 'c = a + b' = 235 milliseconds, i = 1000000
OH      0       22:42:50.187    Test Script (EURUSD,H1) time for 'StringAdd(a,b)' = 1156 milliseconds, i = 1000000
EP      0       22:42:50.781    Test Script (EURUSD,H1) time for 'StringConcatenate(c,a,b)' = 594 milliseconds, i = 1000000


I thought StringAdd() and StringConcatenate() should run faster than "+". Why it is not so?

 
Northwest:

iCustom usually slows down the Expert Advisor's tests.

it's not true, usually it's vice versa, because the allocation of memory for the indicator buffers is done by the terminal, not by the MQL script, usually these problems are the problem of non-optimal calculation in the indicator, many newbies on one indicator call - tick, calculate the entire length of historical data

If you have understood the basics of MQL, read the articles, it's all written.

https://www.mql5.com/ru/articles/4602


Northwest:

Who has done this for an EA and it will be displayed when testing the EA in a subwindow?

no one has, read what is the difference between an EA and an indicator, who has indicator buffers and who does not, who has trading functions and who does....

ZZY: a subwindow can only create an indicator. If you create a subwindow, then you can add graphical objects to this subwindow using the Expert Advisorhttps://www.mql5.com/ru/docs/constants/objectconstants/enum_object

ZSYZZ: subwindow can be obtained by applying a template, there was a topic a couple of months ago, but I think you have a problem with other things so far

Как перенести расчетную часть любого индикатора в код эксперта
Как перенести расчетную часть любого индикатора в код эксперта
  • www.mql5.com
Когда программист создает советник, который получает сигналы от индикаторов, он всякий раз сталкивается с вопросом: использовать обращение к индикатору или перенести код индикатора в советник? Причины этому могут быть различные: желание сохранить в тайне используемые индикаторы и стратегию в целом, необходимость распространения советника единым...
 
Igor Makanu:

this is not true, usually it's vice versa, because the allocation of memory for the indicator buffers is done by the terminal, not by the MQL script, usually these problems are the problem of non-optimal calculation in the indicator, many newbies on one indicator call - tick, they calculate the entire length of historical data

If you have understood the basics of MQL, read the articles, it's been written for a long time.

https://www.mql5.com/ru/articles/4602


no one has, read what is the difference between an Expert Advisor and an indicator, who has indicator buffers and who does not, who has trading functions and who does ....

ZZY: a subwindow can only create an indicator, if you create a subwindow, then you can add graphical objects to this subwindow using the Expert Advisorhttps://www.mql5.com/ru/docs/constants/objectconstants/enum_object

ZSYZZ: subwindow can be obtained by applying a template, was a topic a couple of months ago, but I think you have a problem with something else so far

Sorry. Maybe I didn't phrase it right but

I don't mean to use it for testing, but I don't mean to run it.

As for visualization on the indicator chart during testing, if you use

When you use built-in indicator functions they are drawn on the chart in the process of testing

That's exactly what I mean.

But if you use some kind of custom indicator calculation code that is integrated in the EA code, then this indicator

will not be displayed in the process of testing the EA.

As for iCustom, when you use it in the process of testing the EA will be displayed on the chart

any indicator and the code of the indicator can be compiled with the EA into one ex4 but I don't need it.

I just wanted to know if there is a way to bypass iCustom in this matter, but if not, it's not a problem either.

Thank you very much for the comprehensive reply.

 

Artem posted an indicator template here, here is the part fromOnCalculate

//--- Проверка количества доступных баров (1 - минимально, 4 - оптимально для большинства расчётов. Но всё "по месту"...)
   if(rates_total<4) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated; // 0 - пришел новый тик, новый бар формироваться не начал. 1 - пришел новый тик и начал формироваться новый бар.
   if(limit>1) 
               // если вписать "limit>0", то на нулевом баре будет расчёт только нулевого бара, на каждом новом баре будет полный перерасчёт всей истории
               // если вписать "limit>1", то на нулевом баре будет расчёт только нулевого бара, на открытии нового бара - пересчёт первого и нулевого,
               // при подгрузке истории и на первом запуске - перерасчёт всей истории
     {
      limit=rates_total-1;
      // здесь должна быть инициализация всех используемых буферов индикатора необходимыми значениями (обычно EMPTY_VALUE и 0)
     }

I am using it but I have one question)

Why do I uselimit=rates_total-1 for full history calculation andnotlimit=rates_total?

 
psyman:

Why islimit=rates_total-1 used for full history calculation andnotlimit=rates_total?

Try to check it, you will be immediately "out of range " - numbering of bars from zero to ... Total -1 , a common situation in programming - numbering starts with 0. As an obvious example, declare array double x[5] and try to write something in the last element x[5] = 100;

ZS: answering the question you haven't asked yet.... OrderTotal() also numbers from zero to OrderTotal()-1 ;)

 
Igor Makanu:

ZS: answering a question that hasn't been asked yet.... OrderTotal() too numbering from zero to OrderTotal()-1 ;)

The question arose by the way, now I can't win an averaging on the array, though I do in five, but in what theme to write, I do not know, let it be here.

The indicator calculates the open-close difference and builds МА on it. I have chosen MA=2 for debugging but using SimpleMAOnBuffer and iMAOnArray I get unexplainable line shifts and iMAOnArray shows zero value on the last bar.


//+------------------------------------------------------------------+
//|                                                        _null.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_separate_window
#include <MovingAverages.mqh>

#property indicator_buffers 4
#property indicator_plots   2
//--- plot OC
#property indicator_label1  "OC"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_color1  clrSteelBlue, clrRed,clrGreen
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

#property indicator_label2  "MA1"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrBrown
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1


//--- indicator buffers
double   OC[], OC_color[], MA1_buf[];
input int MA1=2;

int OnInit()
  {
  
   IndicatorSetString(INDICATOR_SHORTNAME,"t1");
   
   SetIndexBuffer(0,OC,INDICATOR_DATA);
   SetIndexBuffer(1,OC_color,INDICATOR_COLOR_INDEX);
   
   SetIndexBuffer(2, MA1_buf,INDICATOR_DATA); 
   //PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,50);

     
//--- indicator buffers mapping

   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{

//--- Проверка количества доступных баров (1 - минимально, 4 - оптимально для большинства расчётов. Но всё "по месту"...)
   if(rates_total<4) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated; // 0 - пришел новый тик, новый бар формироваться не начал. 1 - пришел новый тик и начал формироваться новый бар.
   //if(limit>1) 
   
               // если вписать "limit>0", то на нулевом баре будет расчёт только нулевого бара, на каждом новом баре будет полный перерасчёт всей истории
               // если вписать "limit>1", то на нулевом баре будет расчёт только нулевого бара, на открытии нового бара - пересчёт первого и нулевого,
               // при подгрузке истории и на первом запуске - перерасчёт всей истории
     {
     limit=rates_total-1;
           // здесь должна быть инициализация всех используемых буферов индикатора необходимыми значениями (обычно EMPTY_VALUE и 0)
     }
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      // необходимые действия по расчёту индикатора
     
     OC[i]=fmax(open[i],close[i])-fmin(open[i],close[i]);
     if(OC[i]>0.001)
      {   OC_color[i]=1;
      }
      }  
   
 /*  for(int k=limit; k>=0 && !IsStopped(); k--)
     {
   
     MA1_buf[k]=iMAOnArray(OC,0,MA1,k,MODE_SMA,0);
     }
*/
      SimpleMAOnBuffer(rates_total,prev_calculated,0,MA1,OC,MA1_buf);

//--- return value of prev_calculated for next call
   return(rates_total);
  }




double iMAOnArray(double &array[],
                      int total,
                      int period,
                      int ma_shift,
                      int ma_method,
                      int shift)
  {
   double buf[],arr[];
   if(total==0) total=ArraySize(array);
   if(total>0 && total<=period) return(0);
   if(shift>total-period-ma_shift) return(0);
   switch(ma_method)
     {
      case MODE_SMA :
        {
         total=ArrayCopy(arr,array,0,shift+ma_shift,period);
         if(ArrayResize(buf,total)<0) return(0);
         double sum=0;
         int    i,pos=total-1;
         for(i=1;i<period;i++,pos--)
            sum+=arr[pos];
         while(pos>=0)
           {
            sum+=arr[pos];
            buf[pos]=sum/period;
            sum-=arr[pos+period-1];
            pos--;
           }
         return(buf[0]);
        }
      case MODE_EMA :
        {
         if(ArrayResize(buf,total)<0) return(0);
         double pr=2.0/(period+1);
         int    pos=total-2;
         while(pos>=0)
           {
            if(pos==total-2) buf[pos+1]=array[pos+1];
            buf[pos]=array[pos]*pr+buf[pos+1]*(1-pr);
            pos--;
           }
         return(buf[shift+ma_shift]);
        }
      case MODE_SMMA :
        {
         if(ArrayResize(buf,total)<0) return(0);
         double sum=0;
         int    i,k,pos;
         pos=total-period;
         while(pos>=0)
           {
            if(pos==total-period)
              {
               for(i=0,k=pos;i<period;i++,k++)
                 {
                  sum+=array[k];
                  buf[k]=0;
                 }
              }
            else sum=buf[pos+1]*(period-1)+array[pos];
            buf[pos]=sum/period;
            pos--;
           }
         return(buf[shift+ma_shift]);
        }
      case MODE_LWMA :
        {
         if(ArrayResize(buf,total)<0) return(0);
         double sum=0.0,lsum=0.0;
         double price;
         int    i,weight=0,pos=total-1;
         for(i=1;i<=period;i++,pos--)
           {
            price=array[pos];
            sum+=price*i;
            lsum+=price;
            weight+=i;
           }
         pos++;
         i=pos+period;
         while(pos>=0)
           {
            buf[pos]=sum/weight;
            if(pos==0) break;
            pos--;
            i--;
            price=array[pos];
            sum=sum-lsum+price*period;
            lsum-=array[i];
            lsum+=price;
           }
         return(buf[shift+ma_shift]);
        }
      default: return(0);
     }
   return(0);
  }
 
psyman:

I have a related question, I am still struggling with array averaging, although I am doing it in 5, but I don't know what subject to write it in, let it be here.

I have a feeling that in MQL5 the indicator buffers and time series are "unfolded" in the opposite way, by default the leftmost bar in MT5 is bar 0 and in MT4 the rightmost bar is bar 0 and the indicator buffers have the same numeration

ZS: alas, I don't want to get involved with MT5, MT4 is enough for me to check my ideas, I only look at preparations in MT5, and if I write something using MT5 I never show it to anybody )))

Reason: