Help - страница 2

 
Игорь:

"Ну и, если я правильно понимаю названия буферов (ExtMacdBuffer - буфер значений MACD, отображаемый в виде гистограммы, ExtSignalBuffer - буфер сигнальной линии, отображаемый в виде линии, ExtZigzagBuffer - буфер зигзага, отображаемый в виде соединяемых экстремумов)"

Вы правильно всё поняли.

Нумерацию подправил.  Я что то лишние убрал?

Собрал весь код (что касается макди и зигзаг).

//+------------------------------------------------------------------+
//|                                                            1.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                                          https:/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https:/"
#property version   "1.00"
#property strict

#include <MovingAverages.mqh>

//--- indicator settings
#property  indicator_separate_window
#property  indicator_buffers 5
#property  indicator_color1  Silver
#property  indicator_color2  Red
#property  indicator_color3 White
#property  indicator_width1  2
#property  indicator_width2  2
#property  indicator_width3  2
//--- indicator parameters
input int InpFastEMA=12;   // Fast EMA Period
input int InpSlowEMA=26;   // Slow EMA Period
input int InpSignalSMA=9;  // Signal SMA Period
//
input int InpDepth=12;     // Depth
input int InpDeviation=5;  // Deviation
input int InpBackstep=3;   // Backstep
//--- indicator buffers
double    ExtMacdBuffer[];
double    ExtSignalBuffer[];
double    ExtZigzagBuffer[];
double    ExtHighBuffer[];
double    ExtLowBuffer[];
//--- globals
int    ExtLevel=3; // recounting's depth of extremums
//--- right input parameters flag
bool      ExtParameters=false;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorDigits(Digits+1);
   if(InpBackstep>=InpDepth)
     {
      Print("Backstep cannot be greater or equal to Depth");
      return(INIT_FAILED);
     }
//--- 2 additional buffers
   IndicatorBuffers(3);
//---- drawing settings
   SetIndexStyle(0,DRAW_SECTION);
   SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexStyle(2,DRAW_LINE);
   SetIndexDrawBegin(1,InpSignalSMA);
   SetIndexEmptyValue(0,0.0);
//---- indicator buffers
//   SetIndexBuffer(0,ExtZigzagBuffer);
//   SetIndexBuffer(1,ExtHighBuffer);
//   SetIndexBuffer(2,ExtLowBuffer);
   
//---- indicator short name
   IndicatorShortName("ZigZag("+string(InpDepth)+","+string(InpDeviation)+","+string(InpBackstep)+")");
//--- indicator buffers mapping
   //SetIndexBuffer(0,ExtMacdBuffer);
   //SetIndexBuffer(1,ExtSignalBuffer);
  SetIndexBuffer(0,ExtMacdBuffer);
  SetIndexBuffer(1,ExtSignalBuffer); 
  SetIndexBuffer(2,ExtZigzagBuffer);
//--- name for DataWindow and indicator subwindow label
   IndicatorShortName("MACD("+IntegerToString(InpFastEMA)+","+IntegerToString(InpSlowEMA)+","+IntegerToString(InpSignalSMA)+")");
   SetIndexLabel(0,"MACD");
   SetIndexLabel(1,"Signal");
//--- check for input parameters
   if(InpFastEMA<=1 || InpSlowEMA<=1 || InpSignalSMA<=1 || InpFastEMA>=InpSlowEMA)
     {
      Print("Wrong input parameters");
      ExtParameters=false;
      return(INIT_FAILED);
     }
   else
      ExtParameters=true;
   return(INIT_SUCCEEDED);
  }
  //+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence                           |
//+------------------------------------------------------------------+

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 q,limit_;
//--- macd
   if(rates_total<=InpSignalSMA || !ExtParameters)
      return(0);
//--- last counted bar will be recounted
   limit_=rates_total-prev_calculated;
   if(prev_calculated>0)
      limit_++;
//--- macd counted in the 1-st buffer
   for(q=0; q<limit_; q++)
      ExtMacdBuffer[q]=iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,q)-
                    iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,q);
//--- signal line counted in the 2-nd buffer
   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- zigzag
   int    i,limit,counterZ,whatlookfor=0;
   int    back,pos,lasthighpos=0,lastlowpos=0;
   double extremum;
   double curlow=0.0,curhigh=0.0,lasthigh=0.0,lastlow=0.0;
//--- check for history and inputs
   if(rates_total<InpDepth || InpBackstep>=InpDepth)
      return(0);
//--- first calculations
   if(prev_calculated==0)
      limit=InitializeAll();
   else 
     {
      //--- find first extremum in the depth ExtLevel or 100 last bars
      i=counterZ=0;
      while(counterZ<ExtLevel && i<100)
        {
         if(ExtZigzagBuffer[i]!=0.0)
            counterZ++;
         i++;
        }
      //--- no extremum found - recounting all from begin
      if(counterZ==0)
         limit=InitializeAll();
      else
        {
         //--- set start position to found extremum position
         limit=i-1;
         //--- what kind of extremum?
         if(ExtLowBuffer[i]!=0.0) 
           {
            //--- low extremum
            curlow=ExtLowBuffer[i];
            //--- will look for the next high extremum
            whatlookfor=1;
           }
         else
           {
            //--- high extremum
            curhigh=ExtHighBuffer[i];
            //--- will look for the next low extremum
            whatlookfor=-1;
           }
         //--- clear the rest data
         for(i=limit-1; i>=0; i--)  
           {
            ExtZigzagBuffer[i]=0.0;  
            ExtLowBuffer[i]=0.0;
            ExtHighBuffer[i]=0.0;
           }
        }
     }
//--- main loop      
   for(i=limit; i>=0; i--)
     {
      //--- find lowest low in depth of bars
      extremum=low[iLowest(NULL,0,MODE_LOW,InpDepth,i)];
      //--- this lowest has been found previously
      if(extremum==lastlow)
         extremum=0.0;
      else 
        { 
         //--- new last low
         lastlow=extremum; 
         //--- discard extremum if current low is too high
         if(low[i]-extremum>InpDeviation*Point)
            extremum=0.0;
         else
           {
            //--- clear previous extremums in backstep bars
            for(back=1; back<=InpBackstep; back++)
              {
               pos=i+back;
               if(ExtLowBuffer[pos]!=0 && ExtLowBuffer[pos]>extremum)
                  ExtLowBuffer[pos]=0.0; 
              }
           }
        } 
      //--- found extremum is current low
      if(low[i]==extremum)
         ExtLowBuffer[i]=extremum;
      else
         ExtLowBuffer[i]=0.0;
      //--- find highest high in depth of bars
      extremum=high[iHighest(NULL,0,MODE_HIGH,InpDepth,i)];
      //--- this highest has been found previously
      if(extremum==lasthigh)
         extremum=0.0;
      else 
        {
         //--- new last high
         lasthigh=extremum;
         //--- discard extremum if current high is too low
         if(extremum-high[i]>InpDeviation*Point)
            extremum=0.0;
         else
           {
            //--- clear previous extremums in backstep bars
            for(back=1; back<=InpBackstep; back++)
              {
               pos=i+back;
               if(ExtHighBuffer[pos]!=0 && ExtHighBuffer[pos]<extremum)
                  ExtHighBuffer[pos]=0.0; 
              } 
           }
        }
      //--- found extremum is current high
      if(high[i]==extremum)
         ExtHighBuffer[i]=extremum;
      else
         ExtHighBuffer[i]=0.0;
     }
//--- final cutting 
   if(whatlookfor==0)
     {
      lastlow=0.0;
      lasthigh=0.0;  
     }
   else
     {
      lastlow=curlow;
      lasthigh=curhigh;
     }
   for(i=limit; i>=0; i--)
     {
      switch(whatlookfor)
        {
         case 0: // look for peak or lawn 
            if(lastlow==0.0 && lasthigh==0.0)
              {
               if(ExtHighBuffer[i]!=0.0)
                 {
                  lasthigh=High[i];
                  lasthighpos=i;
                  whatlookfor=-1;
                  ExtZigzagBuffer[i]=lasthigh;
                 }
               if(ExtLowBuffer[i]!=0.0)
                 {
                  lastlow=Low[i];
                  lastlowpos=i;
                  whatlookfor=1;
                  ExtZigzagBuffer[i]=lastlow;
                 }
              }
             break;  
         case 1: // look for peak
            if(ExtLowBuffer[i]!=0.0 && ExtLowBuffer[i]<lastlow && ExtHighBuffer[i]==0.0)
              {
               ExtZigzagBuffer[lastlowpos]=0.0;
               lastlowpos=i;
               lastlow=ExtLowBuffer[i];
               ExtZigzagBuffer[i]=lastlow;
              }
            if(ExtHighBuffer[i]!=0.0 && ExtLowBuffer[i]==0.0)
              {
               lasthigh=ExtHighBuffer[i];
               lasthighpos=i;
               ExtZigzagBuffer[i]=lasthigh;
               whatlookfor=-1;
              }   
            break;               
         case -1: // look for lawn
            if(ExtHighBuffer[i]!=0.0 && ExtHighBuffer[i]>lasthigh && ExtLowBuffer[i]==0.0)
              {
               ExtZigzagBuffer[lasthighpos]=0.0;
               lasthighpos=i;
               lasthigh=ExtHighBuffer[i];
               ExtZigzagBuffer[i]=lasthigh;
              }
            if(ExtLowBuffer[i]!=0.0 && ExtHighBuffer[i]==0.0)
              {
               lastlow=ExtLowBuffer[i];
               lastlowpos=i;
               ExtZigzagBuffer[i]=lastlow;
               whatlookfor=1;
              }   
            break;               
        }
     }
//--- done
   return(rates_total);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int InitializeAll()
  {
   ArrayInitialize(ExtZigzagBuffer,0.0);
   ArrayInitialize(ExtHighBuffer,0.0);
   ArrayInitialize(ExtLowBuffer,0.0);
//--- first counting position
   return(Bars-InpDepth);
  }
//+------------------------------------------------------------------+  

при компиляции ошибок и предупреждений нет.

При этом были выявлены не дочёты в логике индюка.


Два лишних буфера отражаются (я так предпологаю).


Зигзаг неправильно не отрисовывается.
 
Игорь:

Собрал весь код (что касается макди и зигзаг).

Опять 25 ))

Почему буфер с индексом 0 имеет тип отрисовки DRAW_SECTION, если ему соответствует массив для расчета значений MACD? MACD - гистограмма? Значит тип отрисовки должен быть DRAW_HISTOGRAM.

Дальше - аналогично: сигнальная линия  - это линия. Значит и тип отрисовки должен быть DRAW_LINE. Ну а зигзаг - это DRAW_SECTION.

при компиляции ошибок и предупреждений нет.

Это лишь небольшая победа, не более ))

При этом были выявлены не дочёты в логике индюка.


Два лишних буфера отражаются (я так предпологаю).

Они вообще не привязаны к буферам. В коде указано использование всего лишь 3-х буферов, а происходят попытки заполнения всех пяти. В итоге индикатор завершается с фатальной ошибкой - ошибкой выхода за пределы массива. В данном случае ошибка в строке 189. Чтобы ее не было, нужно:

  1. Изначально указать использование только 3-х буферов (indicator_buffers должен быть равен 3, а не 5).
  2. В OnInit() увеличить количество буферов до 5 (IndicatorBuffers() должен быть 5, а не 3).
  3. Связать буфера 3 и 4 с массивами ExtHighBuffer и ExtLowBuffer.

Зигзаг неправильно не отрисовывается.

До него дело попросту не доходит. Индикатор крешится.

P. S. Хотя я не понимаю, что Вы собираетесь дальше делать с зигзагом, если он основан на поиске экстремумов ценового графика. Приведенный код никакого отношения к поиску экстремумов MACD не имеет. Вы пытаетесь скрестить носорога с бульдозером.

Какие проверки должен пройти торговый робот перед публикацией в Маркете
Какие проверки должен пройти торговый робот перед публикацией в Маркете
  • www.mql5.com
Все продукты Маркета перед публикацией проходят обязательную предварительную проверку, так как небольшая ошибка в логике советника или индикатора может привести к убыткам на торговом счете. Именно поэтому нами разработана серия базовых проверок, призванных обеспечить необходимый уровень качества продуктов Маркета. Если в процессе проверки...
 
Ihor Herasko:

Опять 25 ))

Почему буфер с индексом 0 имеет тип отрисовки DRAW_SECTION, если ему соответствует массив для расчета значений MACD? MACD - гистограмма? Значит тип отрисовки должен быть DRAW_HISTOGRAM.

Дальше - аналогично: сигнальная линия  - это линия. Значит и тип отрисовки должен быть DRAW_LINE. Ну а зигзаг - это DRAW_SECTION.

Это лишь небольшая победа, не более ))

Они вообще не привязаны к буферам. В коде указано использование всего лишь 3-х буферов, а происходят попытки заполнения всех пяти. В итоге индикатор завершается с фатальной ошибкой - ошибкой выхода за пределы массива. В данном случае ошибка в строке 189. Чтобы ее не было, нужно:

  1. Изначально указать использование только 3-х буферов (indicator_buffers должен быть равен 3, а не 5).
  2. В OnInit() увеличить количество буферов до 5 (IndicatorBuffers() должен быть 5, а не 3).
  3. Связать буфера 3 и 4 с массивами ExtHighBuffer и ExtLowBuffer.

До него дело попросту не доходит. Индикатор крешится.

P. S. Хотя я не понимаю, что Вы собираетесь дальше делать с зигзагом, если он основан на поиске экстремумов ценового графика. Приведенный код никакого отношения к поиску экстремумов MACD не имеет. Вы пытаетесь скрестить носорога с бульдозером.

"Опять 25 ))" Я что не сохранил выходит)).

Сейчас буду править

"P. S. Хотя я не понимаю, что Вы собираетесь дальше делать с зигзагом, если он основан на поиске экстремумов ценового графика. Приведенный код никакого отношения к поиску экстремумов MACD не имеет. Вы пытаетесь скрестить носорога с бульдозером."

Как сказать)
 
Игорь:

"Опять 25 ))" Я что не сохранил выходит)).

Сейчас буду править

"P. S. Хотя я не понимаю, что Вы собираетесь дальше делать с зигзагом, если он основан на поиске экстремумов ценового графика. Приведенный код никакого отношения к поиску экстремумов MACD не имеет. Вы пытаетесь скрестить носорога с бульдозером."

Как сказать)

Вроде всё исправил

//+------------------------------------------------------------------+
//|                                                            1.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                                          https:/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https:/"
#property version   "1.00"
#property strict
#include <MovingAverages.mqh>
//--- indicator settings
#property  indicator_separate_window
#property  indicator_buffers 3
#property  indicator_color1  Silver
#property  indicator_color2  Red
#property  indicator_color3 White
#property  indicator_width1  2
#property  indicator_width2  2
#property  indicator_width3  2
//--- indicator parameters
input int InpFastEMA=12;   // Fast EMA Period
input int InpSlowEMA=26;   // Slow EMA Period
input int InpSignalSMA=9;  // Signal SMA Period
//
input int InpDepth=12;     // Depth
input int InpDeviation=5;  // Deviation
input int InpBackstep=3;   // Backstep
//--- indicator buffers
double    ExtMacdBuffer[];
double    ExtSignalBuffer[];
double    ExtZigzagBuffer[];
double    ExtHighBuffer[];
double    ExtLowBuffer[];
//--- globals
int    ExtLevel=3; // recounting's depth of extremums
//--- right input parameters flag
bool      ExtParameters=false;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorDigits(Digits+1);
   if(InpBackstep>=InpDepth)
     {
      Print("Backstep cannot be greater or equal to Depth");
      return(INIT_FAILED);
     }
//--- 2 additional buffers
   IndicatorBuffers(5);
//---- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexStyle(2,DRAW_SECTION);
   SetIndexDrawBegin(1,InpSignalSMA);
   SetIndexBuffer(3,ExtHighBuffer);
   SetIndexBuffer(4,ExtLowBuffer);
   SetIndexEmptyValue(0,0.0);

//---- indicator short name
   IndicatorShortName("ZigZag("+string(InpDepth)+","+string(InpDeviation)+","+string(InpBackstep)+")");
//--- indicator buffers mapping
   //SetIndexBuffer(0,ExtMacdBuffer);
   //SetIndexBuffer(1,ExtSignalBuffer);
  SetIndexBuffer(0,ExtMacdBuffer);
  SetIndexBuffer(1,ExtSignalBuffer); 
  SetIndexBuffer(2,ExtZigzagBuffer);
//--- name for DataWindow and indicator subwindow label
   IndicatorShortName("MACD("+IntegerToString(InpFastEMA)+","+IntegerToString(InpSlowEMA)+","+IntegerToString(InpSignalSMA)+")");
   SetIndexLabel(0,"MACD");
   SetIndexLabel(1,"Signal");
//--- check for input parameters
   if(InpFastEMA<=1 || InpSlowEMA<=1 || InpSignalSMA<=1 || InpFastEMA>=InpSlowEMA)
     {
      Print("Wrong input parameters");
      ExtParameters=false;
      return(INIT_FAILED);
     }
   else
      ExtParameters=true;
   return(INIT_SUCCEEDED);
  }
  //+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence                           |
//+------------------------------------------------------------------+

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 q,limit_;
//--- macd
   if(rates_total<=InpSignalSMA || !ExtParameters)
      return(0);
//--- last counted bar will be recounted
   limit_=rates_total-prev_calculated;
   if(prev_calculated>0)
      limit_++;
//--- macd counted in the 1-st buffer
   for(q=0; q<limit_; q++)
      ExtMacdBuffer[q]=iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,q)-
                    iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,q);
//--- signal line counted in the 2-nd buffer
   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- zigzag
   int    i,limit,counterZ,whatlookfor=0;
   int    back,pos,lasthighpos=0,lastlowpos=0;
   double extremum;
   double curlow=0.0,curhigh=0.0,lasthigh=0.0,lastlow=0.0;
//--- check for history and inputs
   if(rates_total<InpDepth || InpBackstep>=InpDepth)
      return(0);
//--- first calculations
   if(prev_calculated==0)
      limit=InitializeAll();
   else 
     {
      //--- find first extremum in the depth ExtLevel or 100 last bars
      i=counterZ=0;
      while(counterZ<ExtLevel && i<100)
        {
         if(ExtZigzagBuffer[i]!=0.0)
            counterZ++;
         i++;
        }
      //--- no extremum found - recounting all from begin
      if(counterZ==0)
         limit=InitializeAll();
      else
        {
         //--- set start position to found extremum position
         limit=i-1;
         //--- what kind of extremum?
         if(ExtLowBuffer[i]!=0.0) 
           {
            //--- low extremum
            curlow=ExtLowBuffer[i];
            //--- will look for the next high extremum
            whatlookfor=1;
           }
         else
           {
            //--- high extremum
            curhigh=ExtHighBuffer[i];
            //--- will look for the next low extremum
            whatlookfor=-1;
           }
         //--- clear the rest data
         for(i=limit-1; i>=0; i--)  
           {
            ExtZigzagBuffer[i]=0.0;  
            ExtLowBuffer[i]=0.0;
            ExtHighBuffer[i]=0.0;
           }
        }
     }
//--- main loop      
   for(i=limit; i>=0; i--)
     {
      //--- find lowest low in depth of bars
      extremum=low[iLowest(NULL,0,MODE_LOW,InpDepth,i)];
      //--- this lowest has been found previously
      if(extremum==lastlow)
         extremum=0.0;
      else 
        { 
         //--- new last low
         lastlow=extremum; 
         //--- discard extremum if current low is too high
         if(low[i]-extremum>InpDeviation*Point)
            extremum=0.0;
         else
           {
            //--- clear previous extremums in backstep bars
            for(back=1; back<=InpBackstep; back++)
              {
               pos=i+back;
               if(ExtLowBuffer[pos]!=0 && ExtLowBuffer[pos]>extremum)
                  ExtLowBuffer[pos]=0.0; 
              }
           }
        } 
      //--- found extremum is current low
      if(low[i]==extremum)
         ExtLowBuffer[i]=extremum;
      else
         ExtLowBuffer[i]=0.0;
      //--- find highest high in depth of bars
      extremum=high[iHighest(NULL,0,MODE_HIGH,InpDepth,i)];
      //--- this highest has been found previously
      if(extremum==lasthigh)
         extremum=0.0;
      else 
        {
         //--- new last high
         lasthigh=extremum;
         //--- discard extremum if current high is too low
         if(extremum-high[i]>InpDeviation*Point)
            extremum=0.0;
         else
           {
            //--- clear previous extremums in backstep bars
            for(back=1; back<=InpBackstep; back++)
              {
               pos=i+back;
               if(ExtHighBuffer[pos]!=0 && ExtHighBuffer[pos]<extremum)
                  ExtHighBuffer[pos]=0.0; 
              } 
           }
        }
      //--- found extremum is current high
      if(high[i]==extremum)
         ExtHighBuffer[i]=extremum;
      else
         ExtHighBuffer[i]=0.0;
     }
//--- final cutting 
   if(whatlookfor==0)
     {
      lastlow=0.0;
      lasthigh=0.0;  
     }
   else
     {
      lastlow=curlow;
      lasthigh=curhigh;
     }
   for(i=limit; i>=0; i--)
     {
      switch(whatlookfor)
        {
         case 0: // look for peak or lawn 
            if(lastlow==0.0 && lasthigh==0.0)
              {
               if(ExtHighBuffer[i]!=0.0)
                 {
                  lasthigh=High[i];
                  lasthighpos=i;
                  whatlookfor=-1;
                  ExtZigzagBuffer[i]=lasthigh;
                 }
               if(ExtLowBuffer[i]!=0.0)
                 {
                  lastlow=Low[i];
                  lastlowpos=i;
                  whatlookfor=1;
                  ExtZigzagBuffer[i]=lastlow;
                 }
              }
             break;  
         case 1: // look for peak
            if(ExtLowBuffer[i]!=0.0 && ExtLowBuffer[i]<lastlow && ExtHighBuffer[i]==0.0)
              {
               ExtZigzagBuffer[lastlowpos]=0.0;
               lastlowpos=i;
               lastlow=ExtLowBuffer[i];
               ExtZigzagBuffer[i]=lastlow;
              }
            if(ExtHighBuffer[i]!=0.0 && ExtLowBuffer[i]==0.0)
              {
               lasthigh=ExtHighBuffer[i];
               lasthighpos=i;
               ExtZigzagBuffer[i]=lasthigh;
               whatlookfor=-1;
              }   
            break;               
         case -1: // look for lawn
            if(ExtHighBuffer[i]!=0.0 && ExtHighBuffer[i]>lasthigh && ExtLowBuffer[i]==0.0)
              {
               ExtZigzagBuffer[lasthighpos]=0.0;
               lasthighpos=i;
               lasthigh=ExtHighBuffer[i];
               ExtZigzagBuffer[i]=lasthigh;
              }
            if(ExtLowBuffer[i]!=0.0 && ExtHighBuffer[i]==0.0)
              {
               lastlow=ExtLowBuffer[i];
               lastlowpos=i;
               ExtZigzagBuffer[i]=lastlow;
               whatlookfor=1;
              }   
            break;               
        }
     }
//--- done
   return(rates_total);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int InitializeAll()
  {
   ArrayInitialize(ExtZigzagBuffer,0.0);
   ArrayInitialize(ExtHighBuffer,0.0);
   ArrayInitialize(ExtLowBuffer,0.0);
//--- first counting position
   return(Bars-InpDepth);
  }
//+------------------------------------------------------------------+  

итог


 
Игорь:

Вроде всё исправил

итог


Касательно MACD и сигнальной линии, а также с объявлением буферов теперь все верно. Теперь нужно решить вопрос с зигзагом. Он рассчитывается по ценовому графику. В итоге имеет значения более 1. В то же время MACD имеет значения в 300 раз меньше. Поэтому MACD и сигнальной линии в окне индикатора не видно. Они лишь иногда проскакивают в показаниях в виде прямой линии. Именно про это я говорил в контексте носорога и бульдозера: подход для стандартного зигзага здесь неуместен, делается совершенно по-другому.

Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Линии индикаторов
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Линии индикаторов
  • www.mql5.com
Некоторые технические индикаторы имеют несколько отрисовываемых на графике буферов. Нумерация индикаторных буферов начинается с 0. При копировании значений индикатора функцией CopyBuffer() в массив типа double для некоторых индикаторов можно указывать не номер копируемого буфера, а идентификатор этого буфера.
 
Ihor Herasko:

Касательно MACD и сигнальной линии, а также с объявлением буферов теперь все верно. Теперь нужно решить вопрос с зигзагом. Он рассчитывается по ценовому графику. В итоге имеет значения более 1. В то же время MACD имеет значения в 300 раз меньше. Поэтому MACD и сигнальной линии в окне индикатора не видно. Они лишь иногда проскакивают в показаниях в виде прямой линии. Именно про это я говорил в контексте носорога и бульдозера: подход для стандартного зигзага здесь неуместен, делается совершенно по-другому.

"подход для стандартного зигзага здесь неуместен, делается совершенно по-другому." Выходит, что в мт 4 это сделать нельзя?

 
Игорь:

"подход для стандартного зигзага здесь неуместен, делается совершенно по-другому." Выходит, что в мт 4 это сделать нельзя?

Очень даже можно. Но выбранное Вами решение не подходит.

 
Ihor Herasko:

Очень даже можно. Но выбранное Вами решение не подходит.

"Вами решение не подходит." Вы можете что нибудь посоветовать?

Причина обращения: