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

 
Igor Makanu:

You didn't initialize them at the beginning or anywhere else, you just declared them

I wrote before using, i.e. if you have variables SredRazmax, SredRazmin, Sredn as sums of array values, then to correctly calculate the sum, you need to zero the variable and then add the array values and save them in this variable

i.e.

And the second, what you have a question, in the indicator every tick will callOnCalculate() and it means you will constantly count tops of ZigZag at every tick, i.e. about 40-60 times per second.

Thanks, but I've tried zeroing them and triedusingOnStart instead ofOnCalculate() , values are still jumping and it's not clear to me if ww=0 (array value is always displayed) , why are values jumping in the middle, how to make it not count each tick and only count values from array?

 
Dmitry Belov:

Thanks, but I have tried zeroing them and triedusingOnStart instead ofOnCalculate()

I think I can't explain why it happens that way. The matter is that OnStart() is used in scripts and OnCalculate() is used in indicators.

i am not quite clear what your task is? you want to output the values of what? in the code, you add up the prices at which the ZigZag peaks are located on the entire chart, in the output you write "Average spread" and print the value(SredRazmax-SredRazmin)/nn, and the calculation is performed for all the bars

why do you need the indicator if you don't use indicator buffers for drawing? in the indicator buffers are attached to the bars, and their values will shift as soon as a new bar appears

 
Igor Makanu:

I think I can't explain why it happens, the point is that OnStart() is used in scripts, and OnCalculate() in indicators, you need to understand how scripts differ from indicators in MQL

i am not quite clear what your task is? you want to output the values of what? in the code, you add up the prices at which the ZigZag peaks are located on the entire chart, in the output you write "Average spread" and print the value(SredRazmax-SredRazmin)/nn, and the calculation is performed for all the bars

Why do you need an indicator if you don't use indicator buffers for drawing? in the indicator buffers are attached to bars and their values will shift as soon as a new bar appears

To be honest, I simplified the problem (the original formula looks a bit different), I thought I would understand why the values of the average jump when the zero value in the array remains constant. I have two loops, one for filling the array, and the other for calculation of the average, there's a limit of nn, and I actually wanted to output a graph - it's a standard zig zag, but iCustom is drawing the hell out of it, and the average... From zero node, if it is larger than the previous one, subtract previous node and from the previous one subtract prerevious node (it will be minus sign, so it should be multiplied by minus 1) and all this should be summed up and divided by a given number of nn. We get average span of vertices. Further I wanted to get other averages for zigzag, but I got stuck with "jumping" values.

This is roughly how it was originally:

//+------------------------------------------------------------------+
//|                                                           01.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window

#property indicator_buffers 1
#property indicator_color1 Red
#property indicator_width1 1

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+

extern int ExtDepth=12;
extern int ExtDeviation=5;
extern int ExtBackstep=3;
extern int nn=30;

int shift, ww=0;
double zz, SredRazmax=0.0; 
double HZZ[];


int OnInit()
  {
//--- indicator buffers mapping
    SetIndexBuffer(0,HZZ);
  SetIndexStyle(0,DRAW_SECTION);
//---
   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[])
  {
//---
  for(shift = 0; shift <= Bars-1; shift++){
      zz = iCustom(NULL, 0, "ZigZag", ExtDepth, ExtDeviation, ExtBackstep, 0, shift);
           if(zz > 0.0)   {
           HZZ[ww]=zz;
            ww++;          }
           else {
           continue;
           }
    }
//---------------------------------------------+
//расчет среднего значения           
//---------------------------------------------+      
  for(ww=0;ww<=nn;ww++){
       if(HZZ[ww]>HZZ[ww+1]){
          SredRazmax += (HZZ[ww]- HZZ[ww+1]);      
         }     
        else if(HZZ[ww]<HZZ[ww+1]){
         SredRazmax += (HZZ[ww]- HZZ[ww+1])*(-1);
        }
        else{
        continue;
           }
     }  
        
  if(SredRazmax>0){    
   
      Comment("Средний размах = ", SredRazmax/nn,",",HZZ[0],",",HZZ[1],",",HZZ[2],",",HZZ[3],",",HZZ[4]);      
        }
   
       
//--- return value of prev_calculated for next call
 return(0);

  
 
  }
 
Dmitry Belov:

To be honest I just simplified the problem (originally the formula looks a bit different), I thought I could understand why the values of the average jump, if the zero value in the array remains constant. I have two loops, one for filling the array, and the other for calculating the average, there's a limit of nn, and I actually wanted to output a graph as well - it's a standard zig zag, but iCustom draws the hell out of it, and the average... From zero node, if it is larger than the previous one, subtract previous node and from the previous one subtract prerevious one (it will be minus sign, so it should be multiplied by minus 1) and all this should be summed up and divided by a given number of nn. We get average span of vertices. Further I wanted to get other averages for zigzag, but I got stuck with "jumping" values.

This is approximately how it was originally:

I don't really understand it, it's late, I'm sleepy, I tweaked it as I saw it, I have doubts how the indicator will behave on a zero bar (I didn't check), but it draws and displays comments according to your formula

//+------------------------------------------------------------------+
//|                                                           01.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window

#property indicator_buffers 1
#property indicator_color1 Red
#property indicator_width1 1

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+

extern int ExtDepth=12;
extern int ExtDeviation=5;
extern int ExtBackstep=3;
extern int nn=30;

int  ww=0;
double zz,SredRazmax;
double HZZ[];
bool up,dn;
double lastzz;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,HZZ);
   SetIndexStyle(0,DRAW_SECTION);
   SetIndexEmptyValue(0,0.0);
   up = false;
   dn = false;
   lastzz=0.0;
   SredRazmax=0.0;
//---
   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[])
  {
//---
   int shift,limit;
//--- Первый вызов индикатора или смена таймфрейма или подгрузка данных из истории
   if(prev_calculated==0)
     {
      limit=rates_total-1;
      up = false;
      dn = false;
      lastzz=0.0;
      SredRazmax=0.0;
      ArrayInitialize(HZZ,0.0);
     }
   else limit=rates_total-prev_calculated+1;
   for(shift=limit; shift>=0; shift--)
     {
      zz=iCustom(NULL,0,"ZigZag",ExtDepth,ExtDeviation,ExtBackstep,0,shift);
      if(zz>0.0)
        {
         HZZ[shift]=zz;
         if(lastzz>zz) {up=true;  dn=false;}
         if(lastzz<zz) {up=false; dn=true;}
         if(up) SredRazmax+=zz-lastzz;
         if(dn) SredRazmax+=(zz- lastzz)*(-1);
         lastzz=zz;
        }
      else HZZ[shift]=0.0;
     }
   Comment("Средний размах = ",SredRazmax/nn,",",HZZ[0],",",HZZ[1],",",HZZ[2],",",HZZ[3],",",HZZ[4]);
   return(rates_total);
  }
//+------------------------------------------------------------------+
 

Can you help me solve a problem like this? (If possible.)

The Expert Advisor will issue an Alert under certain conditions. Is it possible to make the window that triggered the Alert become active as well?

 
Vatal:

Can you help me solve a problem like this? (If possible.)

The Expert Advisor will issue an Alert under certain conditions. Is it possible to make the window that triggered the Alert become active as well?

There is an example in the documentation. Get the ID of the chart on which the EA is running and go...
Примеры работы с графиком - Константы графиков - Константы, перечисления и структуры - Справочник MQL4
Примеры работы с графиком - Константы графиков - Константы, перечисления и структуры - Справочник MQL4
  • docs.mql4.com
В этом разделе представлены примеры для работы со свойствами графика. Для каждого свойства приведены одна или две законченные функции, которые позволяют задавать/получать значение этого свойства. Эти функции можно использовать в своих MQL4 программах как есть. На рисунке показана графическая панель для наглядной демонстрации того, как изменение...
 
Igor Makanu:

I have some doubts how the indicator will behave on a zero bar (I didn't check), but it does draw and uses your formula to output the comment.

Yes, thank you for your time, it works, I must have done something wrong. But it's not outputting an array in the comment (there should only be vertices, right?) and counts wrong with minus and number..., the zigzag has a different spread between vertices. The idea is to subtract the previous smaller vertex from the last bigger one (which is just formed), and from the previous smaller one subtract even the one that is bigger and the number will be with minus sign, we multiply it by (-1) and so on, and all this is summed nn times and divided by nn, we get the average departure. Approximately on 4 watches this would be 1.69(from to) on USDJPY. Further I wanted to calculate the number of bars average between the tops. I will now try to understand your code, what I did wrong, why it didn't draw and why it doesn't calculate correctly...

 
Dmitry Belov:
Yes, thank you for your time, it really does work, I must have done something wrong. But it doesn't output the array in the comment (it should only have vertices, right?) and counts wrong with minus and number..., the zigzag does not have the same spread between vertices. The idea is to subtract the previous smaller vertex from the last bigger one (which is just formed), and from the previous smaller one subtract even the one that is bigger and the number will be with minus sign, we multiply it by (-1) and so on, and all this is summed nn times and divided by nn, we get the average departure. Approximately on 4 watches this would be 1.69(from to) on USDJPY. Further I wanted to calculate the number of bars average between the tops. I will now try to understand your code, what I did wrong, why it didn't draw me and why it doesn't calculate correctly...

The tops in the comment will not output, because indicator bufferHZZ[] contains copied values of indicator buffer ZigZag, otherwise we will not be able to draw, I deliberately split into 2 conditions of vertex detection up and down:

if(up) SredRazmax+=zz-lastzz;
if(dn) SredRazmax+=(zz- lastzz)*(-1);

If youneed to know several tops in ZZ, then you have to create another array to store this data. The new indicator buffer will complicate it, because all arrays connected to indicator buffers "slip" together with the chart

ZS: the code is my example, and I think that it needs to loop to the 1st bar, and not to 0, will recalculate constantly the values of SredRazmax, I can not check now, no terminal in the PC

 
Igor Makanu:

The tops in the comment will not output, because indicator bufferHZZ[] contains copied values of indicator buffer ZigZag, otherwise we will not be able to draw, I deliberately split into 2 conditions of vertex detection up and down:

If youneed to know several tops in ZZ, then you have to create another array to store this data. The new indicator buffer will complicate it, because all arrays connected to indicator buffers will "slide" together with the chart when a new bar appears.

SZY: the code is my example, and I think that it needs to loop to the 1st bar, and not to 0, will recalculate constantly the value of SredRazmax, I can not check now, no terminal in the PC

My indicator as soon as it is loaded shows the correct values, then every tick increases the value of the average, although in the output values of the zig zag array no change in the tops are holding. That's what I can't understand, why is it like this? I lack experience and knowledge of the language. I'll give up drawing - it's a normal zigzag taken by iCustum (I understand now that it can't overlay an array on the graph, so it draws the hell out of it.). The array will "crawl", but then the values will just recalculate, won't they? so I understand Thank you... I'll be trying... Learning...
 
How do you explain to an EA (standard ma) that you should only buy (sell) when the averages cross, and not in general, when ma_1>ma_2. But it constantly buys, it can't stop
Reason: