Indicator drops calculations and puts constant value in buffer

 

Indicator tests fine with no issues but when put on live charts it periodically behaves different and values in buffer drop to some constant

//+------------------------------------------------------------------+
//|                                         VWAP_Dayly.mq5 |
//|                                           Michael & Robert Maher |
//+------------------------------------------------------------------+
#property copyright "Standing on the shoulders of giants"
#property version   "1.0"
#property description "The indicator calculates standard VWAP (Volume Weighted Average Price) line"
#property description "The start point at the beginning of the Day."
#property description " "
#property description "Purpose: Identify the average price from a certain point in time"
#property description " "
#property description "# IMPORTANT: Each line must have a unique ID #"
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
//--- plot vwap
#property indicator_label1  "Day"
#property indicator_type1   DRAW_SECTION
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2

#property indicator_label2  "MA"
#property indicator_type2   DRAW_SECTION
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2

#property indicator_label3  "Year"
#property indicator_type3   DRAW_SECTION
#property indicator_style3  STYLE_SOLID
#property indicator_width3  2



//---

enum PRICE_METHOD
  {
   Median,  // Median Price (HL/2)
   Typical, // Typical Price (HLC/3)
   Weighted // Weighted Close (HLCC/4)
  };
//--- input parameters
input PRICE_METHOD      Method    = Typical;    // Price Calculation Method
input color             Day = clrAqua;
input color             Average  = clrRed;
input color             Year = clrLime;    
//--- indicator buffers
double         iDay[];
double         MA[];
double         iYear[];
//--- global variables
int            start4;
int            start3;
int            start2;
int            start1;
int            yearstart;
string         Prefix;
string         indicator_name;
int            iRatesTotal;
datetime       iTime[];
double         iOpen[],iHigh[],iLow[],iClose[],iVolume[];
long           obj_time;
bool           first=true;
int            counter=0;
int i;


//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
// indicator buffers mapping
   SetIndexBuffer(0,iDay,INDICATOR_DATA);
   ArraySetAsSeries(iDay,true);
   SetIndexBuffer(1,MA,INDICATOR_DATA);
   ArraySetAsSeries(MA,true);
   SetIndexBuffer(2,iYear,INDICATOR_DATA);
   ArraySetAsSeries(iYear,true);
   
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,Day);
   PlotIndexSetInteger(1,PLOT_LINE_COLOR,Average);
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,Year);
   
  

Print("INIT");

   return(INIT_SUCCEEDED);
   
   
  }
//+------------------------------------------------------------------+
//| Custom indicator Deinitialization function                       |
//+------------------------------------------------------------------+     
void OnDeinit(const int reason)
  {
  Print("DEINIT");
   if(reason==REASON_INITFAILED)
     
      Print("ERROR");
      ChartIndicatorDelete(0,0,indicator_name);
     
  }
//+------------------------------------------------------------------+
//| Custom indicator Chart Event function                            |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(sparam==Prefix) EventSetMillisecondTimer(100);
   else EventKillTimer();
  }
//+------------------------------------------------------------------+
//| Custom indicator TIMER function                                  |
//+------------------------------------------------------------------+
void OnTimer()
  {
  
   
  }
//+------------------------------------------------------------------+
//| 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[])

{

   ArraySetAsSeries(time,true);
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(tick_volume,true);
// Initializes Buffers
  //if(first)
                 
      ArrayResize(iTime,  (int)(1.1 * rates_total),(int)(rates_total/5));
      ArrayResize(iOpen,  (int)(1.1 * rates_total),(int)(rates_total/5));
      ArrayResize(iHigh,  (int)(1.1 * rates_total),(int)(rates_total/5));
      ArrayResize(iLow,   (int)(1.1 * rates_total),(int)(rates_total/5));
      ArrayResize(iClose, (int)(1.1 * rates_total),(int)(rates_total/5));
      ArrayResize(iVolume,(int)(1.1 * rates_total),(int)(rates_total/5));
      ArraySetAsSeries(iTime,true);
      ArraySetAsSeries(iOpen,true);
      ArraySetAsSeries(iHigh,true);
      ArraySetAsSeries(iLow,true);
      ArraySetAsSeries(iClose,true);
      ArraySetAsSeries(iVolume,true);
 
  if(prev_calculated==0)
  {    
   ArrayInitialize(iDay,EMPTY_VALUE);
    ArrayInitialize(MA,EMPTY_VALUE);
     ArrayInitialize(iYear,EMPTY_VALUE);
     }
   
     
// load the price vectors
  if (NewBar())
  
  {

   for(i=rates_total-1;i>=0; i--)     
    
     {
      iRatesTotal=rates_total;
      iTime[i]=time[i];
      iOpen[i]=open[i];
      iHigh[i]=high[i];
      iLow[i]=low[i];
      iClose[i]=close[i];
      iVolume[i]=(double)tick_volume[i];
     }
     

  
    //get beginning of year bar number 
    datetime date = TimeCurrent();
     MqlDateTime now;
     TimeToStruct(date,now);
     
     datetime yeardate = date - (date % 86400) - ((now.day_of_year-1) * 86400);   
     //datetime month = iTime(Symbol(),PERIOD_MN1,0);
     yearstart = iBarShift(Symbol(),Period(),yeardate);
     YearVWAP();
 
     
     
     //get beginning of current and past Day's bar number
     datetime Day4 = iTime(NULL,PERIOD_D1, 3);
     datetime Day3 = iTime(NULL,PERIOD_D1, 2);     
     datetime Day2 = iTime(NULL,PERIOD_D1, 1);
     datetime Day1 = iTime(NULL,PERIOD_D1, 0);
     start4  = iBarShift(Symbol(),Period(),Day4);
     start3   = iBarShift(Symbol(),Period(),Day3);
     start2 = iBarShift(Symbol(),Period(),Day2);
     start1   = iBarShift(Symbol(),Period(),Day1);
    
  
     //Calulate current and past Day's VWAP lines
     if(prev_calculated==0)
     {
     PreviousVWAP();  
      } 
     CurrentVWAP();     
  
     //Calculate moving average of VWAP
  
   DailyAverage();
    Print("ma: ",MA[0]);
    Print("day: ",iDay[0]);
  
  // MA[0]  = iMAOnArrayMQL4(iDay,0,21,0,MODE_SMA,0);
   
  //DailyAverage();
       
                      
   }  
   
   
   return(rates_total);
}
//+------------------------------------------------------------------+
void CurrentVWAP()
  {
   
   double sumPrice=0,sumVol=0;
   for(i=start1-1; i>=0; i--)
     {
      sumPrice    += Price(iOpen,iHigh,iLow,iClose,i)*iVolume[i];
      sumVol      += iVolume[i];
      if (sumVol > 0) iDay[i]= sumPrice/sumVol;
     }
  }
//+------------------------------------------------------------------+
void PreviousVWAP()
  {
   
   double sumPrice=0,sumVol=0;
   for(i=start4-1; i>=start1; i--)
     {
     if(i == start3-1 || i == start2-1)
     {
     sumPrice=0;
     sumVol=0;
     }
      sumPrice    += Price(iOpen,iHigh,iLow,iClose,i)*iVolume[i];
      sumVol      += iVolume[i];
      if (sumVol > 0) iDay[i]= sumPrice/sumVol;
     }
  }
//+-------------------------------------------------------------------+
void YearVWAP()
  {
   
   double sumPrice=0,sumVol=0;  
   for(i=yearstart-1;i>=0; i--) 
     {
      sumPrice    += Price(iOpen,iHigh,iLow,iClose,i)*iVolume[i];
      sumVol      += iVolume[i];
      if (sumVol > 0) iYear[i]= sumPrice/sumVol;
     }
  }
//+--------------------------------------------------------------------------+
double Price(const double &open[],
             const double &high[],
             const double &low[],
             const double &close[],
             int          index)
  {
   double output;
   if(Method==Median)   output=(high[index]+low[index])/2;
   else if(Method==Typical)  output=(high[index]+low[index]+close[index])/3;
   else if(Method==Weighted) output=(high[index]+low[index]+close[index]+close[index])/4;
   else                      output=close[index];
   return(output);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+

bool NewBar()
   {
   static datetime   prevTime    =  0;
   datetime          currentTime =  iTime(Symbol(), Period(), 0);
   if(currentTime!=prevTime) 
      {
      prevTime = currentTime;
      return(true);
      }
   return(false);
   }
   
bool NewMin()

   {
   
   static datetime   prevTime    =  0;
   datetime          currentTime =  iTime(Symbol(), PERIOD_M1, 0);
   if(currentTime!=prevTime) 
      {
      prevTime = currentTime;
      return(true);
      }
   return(false);
   
   }
//+------------------------------------------------------------------+

double iMAOnArrayMQL4(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 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    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  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);
  }
  
void DailyAverage()
{
   int j;
   int w =20;
   for(j=10; j>=0;j--)
   {
   double sum = 0.0;
      for(i=20; i >= 0; i--)
      {
                  sum += iDay[i+j];
      }
    
   if(iDay[w+j] == EMPTY_VALUE)
      MA[j]=EMPTY_VALUE;
   else
      MA[j]= sum /= 21;
}
}   


Capture2.JPG everything fine all buffers showing correct values.



Capture.JPG Year buffer still ok, but Day and MA dropped value to low number.  Problem seems to be in Day buffer because MA calculates off of Day.

Files:
Capture.JPG  302 kb
Capture2.JPG  175 kb
Reason: