Помогите разобраться с цыклами

 

Доброго времени суток. Помогите разобраться с кодом... Хочу написать индикатор на основе MACD. Индикатор должен считать количество пересечений двух машек за предыдущие 70 баров. Тоесть в каждом значение индикатора должно быть записано количество пересечений за предыдущие 70 баров.

Но чтото не выходит.

//+------------------------------------------------------------------+
//|                                                  Custom MACD.mq4 |
//|                   Copyright 2005-2014, MetaQuotes Software Corp. |
//|                                              https://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "2005-2014, MetaQuotes Software Corp."
#property link        "https://www.mql4.com"
#property description "Moving Averages Convergence/Divergence"
#property strict

#include <MovingAverages.mqh>

//--- indicator settings
#property  indicator_separate_window
#property  indicator_buffers 2
#property  indicator_color1  Silver
#property  indicator_color2  Red
#property  indicator_width1  2
//--- indicator parameters
input int InpFastEMA=12;   // Fast EMA Period
input int InpSlowEMA=26;   // Slow EMA Period
input int InpSignalSMA=9;  // Signal SMA Period
//--- indicator buffers
double    ExtMacdBuffer[];
double    ExtSignalBuffer[];
//--- right input parameters flag
bool      ExtParameters=false;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   IndicatorDigits(Digits+1);
//--- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexDrawBegin(1,InpSignalSMA);
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtMacdBuffer);
   SetIndexBuffer(1,ExtSignalBuffer);
//--- 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;
//--- initialization done
   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 i,limit,j,zz=0;
//---
   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(i=0; i<limit; i++)
      for(j=0;j<70;j++){
         if ((iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,i+j)<iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,i+j) && iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,i+j+1)>iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,i+j+1)) || (iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,i+j)>iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,i+j) && iMA(NULL,0,InpSlowEMA,0,MODE_EMA,PRICE_CLOSE,i+j+1)<iMA(NULL,0,InpFastEMA,0,MODE_EMA,PRICE_CLOSE,i+j+1))){
            zz++;
            } 
         }
      ExtMacdBuffer[i]=zz;
//--- signal line counted in the 2-nd buffer
      SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- done
     
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
С цыклами? Может, с цыками или циклами? 
 
А что именно не работает? И как быть с ложными пересечениями на 0 баре, которых может быть и по десятку в час, а то и больше?
 
Простите за правописание... Ну предполагаю что он будет перерисовываться на 0 баре. Не работает вообще(
 
Ну так я ж и прошу помощи, подскажите как правильно
 
Фигурные скобки для первого цикла где?
 
Фигурные скобки для первого цикла проблему не решают. Да и в стандартном MACD в данном месте нету фигурных скобок
 

В стандартном они и не нужны, там только один оператор, а тут их два. Разве выход за пределы массива ни о чём не говорит?


А так да, это не единственная ошибка в коде.

 

Пробуй так:

//+------------------------------------------------------------------+
//|                                                  Custom MACD.mq4 |
//|                   Copyright 2005-2014, MetaQuotes Software Corp. |
//|                                              https://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright   "2005-2014, MetaQuotes Software Corp."
#property link        "https://www.mql4.com"
#property description "Moving Averages Convergence/Divergence"
#property strict

#include <MovingAverages.mqh>

//--- indicator settings
#property  indicator_separate_window
#property  indicator_buffers 2
#property  indicator_color1  Silver
#property  indicator_color2  Red
#property  indicator_width1  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 CalculateBar  = 70;
 //--- indicator buffers
double    ExtMacdBuffer[];
double    ExtSignalBuffer[];
//--- right input parameters flag
bool      ExtParameters=false;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   IndicatorDigits (0);
//--- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexDrawBegin (0, CalculateBar);
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtMacdBuffer);
   SetIndexBuffer(1,ExtSignalBuffer);
//--- 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;
//--- initialization done
   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 i, limit, j, zz;
//---
    if(rates_total <= InpSignalSMA || !ExtParameters) return (0);
//--- last counted bar will be recounted
    limit = rates_total - prev_calculated;
    if (prev_calculated > 0) limit++;
    else if (prev_calculated == 0) limit -= (CalculateBar + 1);
 //--- macd counted in the 1-st buffer
    for (i = limit - 1; i >= 0; i--)
    {
        zz = 0;
        for (j = 0; j < CalculateBar; j++)
        {if (CrossingMA (i + j)) zz++;} 
        ExtMacdBuffer[i] = zz;
    }
//--- signal line counted in the 2-nd buffer
      SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- done
     
    return (rates_total);
  }
//+------------------------------------------------------------------+
bool CrossingMA (int fi_Bar)
{
    if ((NormalizeDouble (iMA (NULL, 0, InpSlowEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar) - iMA (NULL, 0, InpFastEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar), Digits) < 0.
      && NormalizeDouble (iMA (NULL, 0, InpSlowEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar + 1) - iMA (NULL, 0, InpFastEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar + 1), Digits) > 0.)
      || (NormalizeDouble (iMA (NULL, 0, InpSlowEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar) - iMA (NULL, 0, InpFastEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar), Digits) > 0.
      && NormalizeDouble (iMA (NULL, 0, InpSlowEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar + 1) - iMA (NULL, 0, InpFastEMA, 0, MODE_EMA, PRICE_CLOSE, fi_Bar + 1), Digits) < 0.))
    return (true);
    return (false);
}
//+------------------------------------------------------------------+

Поправил вычисление limit.

 
TarasBY, спасибо большое, работает
 
Хотя просматривается смещение показаний на сам период вычислений, TarasBY
Причина обращения: