百思不得解决,请求指教一个不是问题的简单问题(MODE_SMA 和 MODE_EMA)

 

我的问题是:当使用 MODE_EMA 时,指标正常显示,也就是说随K线与时俱进,而当使用 MODE_SMA 时 ,静止了,不与时俱进,不能正常显示。

请教如何才能修正这个问题。先谢。

程序剪贴如下:

#property copyright   "2019"
#property description "zbc"
#property strict

//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrLawnGreen

//--- input parameter
input int InpFivePeriod=5; //  Period

//--- buffers
double ExtFiveBuffer[];


void OnInit(void)
  {
   string short_name;
//--- 1 additional buffer used for counting.
   IndicatorBuffers(1);
   IndicatorDigits(Digits);
//--- indicator line
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,ExtFiveBuffer);
 

 
  
//--- name for DataWindow and indicator subwindow label
   short_name="CrossingRiver("+IntegerToString(InpFivePeriod)+")";
   IndicatorShortName(short_name);
   SetIndexLabel(0,short_name);
  }



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 limit=rates_total-prev_calculated;
//---
   if(rates_total<=InpFivePeriod)
      return(0);
//---
   if(prev_calculated>0)
      limit++;
   for(int i=0; i<limit; i++)
     {
    
      double MA5=iMA(NULL,0,InpFivePeriod,0,MODE_EMA,PRICE_CLOSE,i);
      ExtFiveBuffer[i]=(Close[i]/MA5-1)*Close[i]/5;
   
    
      }
   
 
   return(rates_total);
  }
//+------------------------------------------------------------------+
 

当你用SMA时,最后InpFivePeriod的几个K线时,MA5的值为0,程序出错了。

要明白SMA和EMA的算法。

修改下:

//+------------------------------------------------------------------+

for(int i=0; i<limit; i++)
  {
   if(i>=rates_total-1 - InpFivePeriod)break;
   double MA5=iMA(NULL,0,InpFivePeriod,0,MODE_EMA,PRICE_CLOSE,i);
   ExtFiveBuffer[i]=(Close[i]/MA5-1)*Close[i]/5;

  }
//+------------------------------------------------------------------+
原因: