Add a Moving Average to MACD

To add comments, please log in or register
danizani95
142
danizani95  

Hi guys I'm trying to add a moving average to an adaptive macd code but I'm having some troubles. In particular the MA is showing but not like if I add it with navigator function (I need to implement a moving average in the MACD code to do another edit). I post a pic to show you the difference between what I want and what I actually have, the original macd adaptive mq4 and its code edited by me. I hope somebody could help me saying where I'm wrong. Thank you.

 

Mladen Rakic
110305
Mladen Rakic  
danizani95:

Hi guys I'm trying to add a moving average to an adaptive macd code but I'm having some troubles. In particular the MA is showing but not like if I add it with navigator function (I need to implement a moving average in the MACD code to do another edit). I post a pic to show you the difference between what I want and what I actually have, the original macd adaptive mq4 and its code edited by me. I hope somebody could help me saying where I'm wrong. Thank you.

 

At your example that histogram is osma (not macd)

You should use osma as a buffer for iMAOnaArray() not macd if you want it to be the same but then you have to add one more value displayed (since you have to have signal buffer or else you are not going to have data to calculate the osma)

danizani95
142
danizani95  

Actually I edited it as follow.. What's wrong o what miss ? Thank you mladen 

//+------------------------------------------------------------------+
//|                                         adaptivemacd 4 color mtf |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property description "edited by eevviill"
#property description "buf 3 to 1"
//
//
//
//
//

#property indicator_separate_window
#property indicator_buffers    6
#property indicator_color2     LimeGreen
#property indicator_color3     Red
#property indicator_color1     DimGray
#property indicator_color4     DeepSkyBlue
#property indicator_color5     PaleVioletRed
#property indicator_color6     Yellow
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_width4     2
#property indicator_width5     2
#property indicator_width6     1
#property indicator_level1     0
#property indicator_levelcolor Gold
#property indicator_levelstyle STYLE_DOT
#property indicator_style6     STYLE_DOT

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame        = PERIOD_CURRENT;
extern int                FastMa           = 12;
extern int                FastMaMethod     = 0;
extern ENUM_APPLIED_PRICE FastMaPrice      = 0;
extern int                AmaPeriod        = 26;
extern ENUM_APPLIED_PRICE AmaPrice         = PRICE_CLOSE;
extern int                Nfast            = 5;
extern int                Nslow            = 20;
extern double             GCoeff           = 2.0;
extern int                SignalMa         = 9;
extern ENUM_MA_METHOD     SignalMaMode     = 0;
extern int                SignalSMA        = 3;

extern bool   alertsOn         = true;
extern bool   alertsOnCurrent  = true;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;

extern string  __              = "arrows settings";
extern bool   ShowArrows       = true;
extern string arrowsIdentifier = "rsima arrows";
extern color  arrowsUpColor    = Lime;
extern color  arrowsDnColor    = Orange;
extern bool               Interpolate      = true;

//
//
//
//
//

double osma[];
double green_buffer[];
double red_buffer[];
double macd[];
double sig[];
double kAMAbuffer[];
double diff[];
double trend[];
double sma[];

//
//
//
//
//

double fastend;
double slowend;
string indicatorFileName;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
 IndicatorBuffers(9);
   SetIndexBuffer(1,green_buffer); SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(2,red_buffer);   SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(0,osma);
   SetIndexBuffer(3,macd);
   SetIndexBuffer(4,sig);
   SetIndexBuffer(5,kAMAbuffer);
   SetIndexBuffer(6,diff);
   SetIndexBuffer(7,trend);
   SetIndexBuffer(8,sma);          SetIndexDrawBegin(8,SignalSMA);
                                   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+1);
   
      fastend   = (2.0 /(Nfast + 1));
      slowend   = (2.0 /(Nslow + 1));
   //
   //
   //
   //
   //
      
     indicatorFileName = WindowExpertName();
     returnBars        = TimeFrame==-99;
     TimeFrame         = MathMax(TimeFrame,_Period);
      
   IndicatorShortName(timeFrameToString(TimeFrame)+"  adaptive macd  ("+FastMa+")"+getAverageName(FastMaMethod)+" ("+AmaPeriod+") "+(SignalSMA)+"");
   return(0);
}

//
//
//
//
//

int deinit(){  if (ShowArrows) deleteArrows();  return(0); }

//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
  {
   
   int counted_bars=IndicatorCounted();
   int i,n,k,x,limit;
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         limit=MathMin(Bars-counted_bars,Bars-1);
         if (returnBars)  { green_buffer[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //
   
   if (TimeFrame == Period())
   {
   
   for(i=limit; i>=0; i--)
   {
      double price = iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i);

         if (i > Bars-AmaPeriod) { kAMAbuffer[i] = price; continue; }
   
         //
         //
         //
         //
         //
   
         double efratio = 1.00;
         double noise   = 0.00;
         double smooth;
         double signal;
             signal  = MathAbs(price-iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i+AmaPeriod));
             diff[i] = MathAbs(price-iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i+1));
                for (k=0;k<AmaPeriod;k++)
                        noise += diff[i+k];

          //
          //
          //
          //
          //

                  if (noise != 0) efratio = signal/noise;
                            smooth        = MathPow(efratio*(fastend-slowend)+slowend,GCoeff);
                            kAMAbuffer[i] = kAMAbuffer[i+1] + smooth*(price-kAMAbuffer[i+1]);
                            macd[i]       = iCustomMA(iMA(NULL,0,1,0,MODE_SMA,FastMaPrice,i),FastMa,FastMaMethod,i) - kAMAbuffer[i];
          }
          
         for (i=limit; i>=0; i--) sig[i]  = iMAOnArray(macd,Bars,SignalMa,0,SignalMaMode,i);
   
   //
   //
   //
   //
   //
   //
   
   for(i=limit; i>=0; i--)
   sma[i]=iMAOnArray(osma,Bars,SignalSMA,0,MODE_SMA,i);
   
   //
   //
   //
   //
   //
   
   for (i=limit; i>=0; i--)
   {
   
      osma[i] = macd[i]- sig[i];
      green_buffer[i]  = 0;
      red_buffer[i]    = 0;
        
      if(osma[i] > 0) 
     
           green_buffer[i]   = osma[i];
      else red_buffer[i]     = osma[i]; 
      
      trend[i] = trend[i+1]; 
         
  if (macd[i] > sig[i] && macd[i+1] <= sig[i+1]) trend[i]= 1; 
  if (macd[i] < sig[i] && macd[i+1] >= sig[i+1]) trend[i]=-1;
  
  manageArrow(i);
      
      //
      //
      //
      //
      //
      
      }
      
      manageAlerts();
      return(0);
      }
  
      //
      //
      //
      //
      //
   
      limit = MathMax(limit,MathMin(Bars,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   
      for (i=limit; i>=0; i--)
      {
   
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         osma[i]        = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,2,y);
         green_buffer[i]= iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,0,y);
         red_buffer[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,1,y);
         macd[i]        = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,3,y);
         sig[i]         = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,4,y);
         trend[i]       = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,7,y);
         sma[i]         = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,8,y);
         if (!Interpolate || y==iBarShift(NULL,TimeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,TimeFrame,y);
         for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;
         for(x = 1; x < n; x++)
         {
          osma[i+x]         = osma[i]         + (osma[i+n]         - osma[i])         * x/n;
          green_buffer[i+x] = green_buffer[i] + (green_buffer[i+n] - green_buffer[i]) * x/n;
          red_buffer[i+x]   = red_buffer[i]   + (red_buffer[i+n]   - red_buffer[i])   * x/n;
          macd[i+x]         = macd[i]         + (macd[i+n]         - macd[i])         * x/n;
          sig[i+x]          = sig[i]          + (sig[i+n]          - sig[i])          * x/n;
          sma[i+x]          = sig[i]          + (sig[i+n]          - sig[i])          * x/n;
        }              
   }
   return(0);
}
      
//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"down");
      }
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," adaptive macd changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," adaptive macd "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double workPrices[];
double workResult[];
int    r;

double iCustomMA(double price, int period, int method, int i)
{
   if (ArraySize(workPrices)!= Bars) ArrayResize(workPrices,Bars);
            r = Bars-i-1;
   workPrices[r] = price;

   //
   //
   //
   //
   //
   
      switch(method)
      {
         case  0: return(iSma(price,period,i));
         case  1: return(iEma(price,period,i));
         case  2: return(iSmma(price,period,i));
         case  3: return(iLwma(price,period,i));
         case  4: return(iLsma(price,period,i));
         case  5: return(iTma(price,period,i));
         case  6: return(iSineWMA(price,period,i));
         case  7: return(iVolumeWMA(price,period,i));
         case  8: return(iHma(price,period,i));
         case  9: return(iNonLagMa(price,period,i));
         case 10: return(iLwmp(price,period,i));
      }
   return(EMPTY_VALUE);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double iSma(double price, double period, int i)
{
   double sum = 0;
   for(int k=0; k<period && (r-k)>=0; k++) sum += workPrices[r-k];  
   if (k!=0)
         return(sum/k);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iEma(double price, double period, int i)
{
   if (ArraySize(workResult)!= Bars) ArrayResize(workResult,Bars);
   double alpha = 2.0 / (1.0+period);
          workResult[r] = workResult[r-1]+alpha*(price-workResult[r-1]);
   return(workResult[r]);
}
//
//
//
//
//

double iSmma(double price, double period, int i)
{
   if (ArraySize(workResult)!= Bars) ArrayResize(workResult,Bars);
   if (i>=(Bars-period))
   {
      double sum = 0; 
         for(int k=0; k<period && (r-k)>=0; k++) sum += workPrices[r-k];  
         if (k!=0)
               workResult[i] = sum/k;
         else  workResult[i] = EMPTY_VALUE;
   }      
   else   workResult[r] = (workResult[r-1]*(period-1)+price)/period;
   return(workResult[r]);
}

//
//
//
//
//

double iLwma_prices[][3];
double iLwma(double price, double period, int i,int forValue=0)
{
   if (ArrayRange(iLwma_prices,0)!= Bars) ArrayResize(iLwma_prices,Bars);
   
   //
   //
   //
   //
   //
   
   iLwma_prices[r][forValue] = price;
      double sum  = 0;
      double sumw = 0;

      for(int k=0; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*iLwma_prices[r-k][forValue];  
      }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iLwmp_prices[][3];
double iLwmp(double price, double period, int i,int forValue=0)
{
   if (ArrayRange(iLwmp_prices,0)!= Bars) ArrayResize(iLwmp_prices,Bars);
   
   //
   //
   //
   //
   //
   
   iLwmp_prices[r][forValue] = price;
      double sum  = 0;
      double sumw = 0;

      for(int k=0; k<period && (r-k)>=0; k++)
      {
         double weight = (period-k)*(period-k);
                sumw  += weight;
                sum   += weight*iLwmp_prices[r-k][forValue];  
      }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iLsma(double price, double period, int i)
{
   return(3.0*iLwma(price,period,i)-2.0*iSma(price,period,i));
}

//
//
//
//
//

double iHma(double price, double period, int i)
{
   int HalfPeriod = MathFloor(period/2);
   int HullPeriod = MathFloor(MathSqrt(period));
            double price1 = 2.0*iLwma(price,HalfPeriod,i,0)-iLwma(price,period,i,1);
   return (iLwma(price1,HullPeriod,i,2));
}

//
//
//
//
//

double iTma(double price, double period, int i)
{
   double half = (period+1.0)/2.0;
   double sum  = 0;
   double sumw = 0;

   for(int k=0; k<period && (r-k)>=0; k++)
   {
      double weight = k+1; if (weight > half) weight = period-k;
             sumw  += weight;
             sum   += weight*workPrices[r-k];  
   }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

#define Pi 3.14159265358979323846
double iSineWMA(double price, int period, int i)
{
   double sum  = 0;
   double sumw = 0;
  
   for(int k=0; k<period && (r-k)>=0; k++)
   { 
      double weight = MathSin(Pi*(k+1)/(period+1));
             sumw  += weight;
             sum   += weight*workPrices[r-k]; 
   }
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iVolumeWMA(double price, int period, int i)
{
   double sum  = 0;
   double sumw = 0;
  
   for(int k=0; k<period && (r-k)>=0; k++)
   { 
      double weight = Volume[i+k];
             sumw  += weight;
             sum   += weight*workPrices[r-k]; 
   }
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}


//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

#define _length  0
#define _len     1
#define _weight  2

#define numOfSeparateCalculations 1
double  nlm_values[3][numOfSeparateCalculations];
double  nlm_prices[ ][numOfSeparateCalculations];
double  nlm_alphas[ ][numOfSeparateCalculations];

//
//
//
//
//

double iNonLagMa(double price, int length, int i, int forValue=0)
{
   if (ArrayRange(nlm_prices,0) != Bars) ArrayResize(nlm_prices,Bars);
                               nlm_prices[r][forValue]=price;
   if (length<3 || r<3) return(nlm_prices[r][forValue]);
   
   //
   //
   //
   //
   //
   
   if (nlm_values[_length][forValue] != length)
   {
      double Cycle = 4.0;
      double Coeff = 3.0*Pi;
      int    Phase = length-1;
      
         nlm_values[_length][forValue] = length;
         nlm_values[_len   ][forValue] = length*4 + Phase;  
         nlm_values[_weight][forValue] = 0;

         if (ArrayRange(nlm_alphas,0) < nlm_values[_len][forValue]) ArrayResize(nlm_alphas,nlm_values[_len][forValue]);
         for (int k=0; k<nlm_values[_len][forValue]; k++)
         {
            if (k<=Phase-1) 
                 double t = 1.0 * k/(Phase-1);
            else        t = 1.0 + (k-Phase+1)*(2.0*Cycle-1.0)/(Cycle*length-1.0); 
            double beta = MathCos(Pi*t);
            double g = 1.0/(Coeff*t+1); if (t <= 0.5 ) g = 1;
      
            nlm_alphas[k][forValue]        = g * beta;
            nlm_values[_weight][forValue] += nlm_alphas[k][forValue];
         }
   }
   
   //
   //
   //
   //
   //
   
   if (nlm_values[_weight][forValue]>0)
   {
      double sum = 0;
           for (k=0; k < nlm_values[_len][forValue]; k++) sum += nlm_alphas[k][forValue]*nlm_prices[r-k][forValue];
           return( sum / nlm_values[_weight][forValue]);
   }
   else return(0);           
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

string methodNames[] = {"SMA","EMA","SMMA","LWMA","LSMA","TriMA","SWMA","VWMA","HullMA","NonLagMA","LWM parabolic"};
string getAverageName(int& method)
{
   method=MathMax(MathMin(method,10),0); return(methodNames[method]);
}

//
//
//
//
//

void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] == 1) drawArrow(i,arrowsUpColor,221,false);
         if (trend[i] ==-1) drawArrow(i,arrowsDnColor,222,true);
      }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
  
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}
Mladen Rakic
110305
Mladen Rakic  
danizani95:

Actually I edited it as follow.. What's wrong o what miss ? Thank you mladen 

//+------------------------------------------------------------------+
//|                                         adaptivemacd 4 color mtf |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property description "edited by eevviill"
#property description "buf 3 to 1"
//
//
//
//
//

#property indicator_separate_window
#property indicator_buffers    6
#property indicator_color2     LimeGreen
#property indicator_color3     Red
#property indicator_color1     DimGray
#property indicator_color4     DeepSkyBlue
#property indicator_color5     PaleVioletRed
#property indicator_color6     Yellow
#property indicator_width1     2
#property indicator_width2     2
#property indicator_width3     2
#property indicator_width4     2
#property indicator_width5     2
#property indicator_width6     1
#property indicator_level1     0
#property indicator_levelcolor Gold
#property indicator_levelstyle STYLE_DOT
#property indicator_style6     STYLE_DOT

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame        = PERIOD_CURRENT;
extern int                FastMa           = 12;
extern int                FastMaMethod     = 0;
extern ENUM_APPLIED_PRICE FastMaPrice      = 0;
extern int                AmaPeriod        = 26;
extern ENUM_APPLIED_PRICE AmaPrice         = PRICE_CLOSE;
extern int                Nfast            = 5;
extern int                Nslow            = 20;
extern double             GCoeff           = 2.0;
extern int                SignalMa         = 9;
extern ENUM_MA_METHOD     SignalMaMode     = 0;
extern int                SignalSMA        = 3;

extern bool   alertsOn         = true;
extern bool   alertsOnCurrent  = true;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;

extern string  __              = "arrows settings";
extern bool   ShowArrows       = true;
extern string arrowsIdentifier = "rsima arrows";
extern color  arrowsUpColor    = Lime;
extern color  arrowsDnColor    = Orange;
extern bool               Interpolate      = true;

//
//
//
//
//

double osma[];
double green_buffer[];
double red_buffer[];
double macd[];
double sig[];
double kAMAbuffer[];
double diff[];
double trend[];
double sma[];

//
//
//
//
//

double fastend;
double slowend;
string indicatorFileName;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
 IndicatorBuffers(9);
   SetIndexBuffer(1,green_buffer); SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(2,red_buffer);   SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID);
   SetIndexBuffer(0,osma);
   SetIndexBuffer(3,macd);
   SetIndexBuffer(4,sig);
   SetIndexBuffer(5,kAMAbuffer);
   SetIndexBuffer(6,diff);
   SetIndexBuffer(7,trend);
   SetIndexBuffer(8,sma);          SetIndexDrawBegin(8,SignalSMA);
                                   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+1);
   
      fastend   = (2.0 /(Nfast + 1));
      slowend   = (2.0 /(Nslow + 1));
   //
   //
   //
   //
   //
      
     indicatorFileName = WindowExpertName();
     returnBars        = TimeFrame==-99;
     TimeFrame         = MathMax(TimeFrame,_Period);
      
   IndicatorShortName(timeFrameToString(TimeFrame)+"  adaptive macd  ("+FastMa+")"+getAverageName(FastMaMethod)+" ("+AmaPeriod+") "+(SignalSMA)+"");
   return(0);
}

//
//
//
//
//

int deinit(){  if (ShowArrows) deleteArrows();  return(0); }

//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
  {
   
   int counted_bars=IndicatorCounted();
   int i,n,k,x,limit;
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         limit=MathMin(Bars-counted_bars,Bars-1);
         if (returnBars)  { green_buffer[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //
   
   if (TimeFrame == Period())
   {
   
   for(i=limit; i>=0; i--)
   {
      double price = iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i);

         if (i > Bars-AmaPeriod) { kAMAbuffer[i] = price; continue; }
   
         //
         //
         //
         //
         //
   
         double efratio = 1.00;
         double noise   = 0.00;
         double smooth;
         double signal;
             signal  = MathAbs(price-iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i+AmaPeriod));
             diff[i] = MathAbs(price-iMA(NULL,0,1,0,MODE_SMA,AmaPrice,i+1));
                for (k=0;k<AmaPeriod;k++)
                        noise += diff[i+k];

          //
          //
          //
          //
          //

                  if (noise != 0) efratio = signal/noise;
                            smooth        = MathPow(efratio*(fastend-slowend)+slowend,GCoeff);
                            kAMAbuffer[i] = kAMAbuffer[i+1] + smooth*(price-kAMAbuffer[i+1]);
                            macd[i]       = iCustomMA(iMA(NULL,0,1,0,MODE_SMA,FastMaPrice,i),FastMa,FastMaMethod,i) - kAMAbuffer[i];
          }
          
         for (i=limit; i>=0; i--) sig[i]  = iMAOnArray(macd,Bars,SignalMa,0,SignalMaMode,i);
   
   //
   //
   //
   //
   //
   //
   
   for(i=limit; i>=0; i--)
   sma[i]=iMAOnArray(osma,Bars,SignalSMA,0,MODE_SMA,i);
   
   //
   //
   //
   //
   //
   
   for (i=limit; i>=0; i--)
   {
   
      osma[i] = macd[i]- sig[i];
      green_buffer[i]  = 0;
      red_buffer[i]    = 0;
        
      if(osma[i] > 0) 
     
           green_buffer[i]   = osma[i];
      else red_buffer[i]     = osma[i]; 
      
      trend[i] = trend[i+1]; 
         
  if (macd[i] > sig[i] && macd[i+1] <= sig[i+1]) trend[i]= 1; 
  if (macd[i] < sig[i] && macd[i+1] >= sig[i+1]) trend[i]=-1;
  
  manageArrow(i);
      
      //
      //
      //
      //
      //
      
      }
      
      manageAlerts();
      return(0);
      }
  
      //
      //
      //
      //
      //
   
      limit = MathMax(limit,MathMin(Bars,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   
      for (i=limit; i>=0; i--)
      {
   
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         osma[i]        = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,2,y);
         green_buffer[i]= iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,0,y);
         red_buffer[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,1,y);
         macd[i]        = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,3,y);
         sig[i]         = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,4,y);
         trend[i]       = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,7,y);
         sma[i]         = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMa,FastMaMethod,FastMaPrice,AmaPeriod,AmaPrice,Nfast,Nslow,GCoeff,SignalMa,SignalMaMode,SignalSMA,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,"",ShowArrows,arrowsIdentifier,arrowsUpColor,arrowsDnColor,8,y);
         if (!Interpolate || y==iBarShift(NULL,TimeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,TimeFrame,y);
         for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;
         for(x = 1; x < n; x++)
         {
          osma[i+x]         = osma[i]         + (osma[i+n]         - osma[i])         * x/n;
          green_buffer[i+x] = green_buffer[i] + (green_buffer[i+n] - green_buffer[i]) * x/n;
          red_buffer[i+x]   = red_buffer[i]   + (red_buffer[i+n]   - red_buffer[i])   * x/n;
          macd[i+x]         = macd[i]         + (macd[i+n]         - macd[i])         * x/n;
          sig[i+x]          = sig[i]          + (sig[i+n]          - sig[i])          * x/n;
          sma[i+x]          = sig[i]          + (sig[i+n]          - sig[i])          * x/n;
        }              
   }
   return(0);
}
      
//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"down");
      }
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," adaptive macd changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," adaptive macd "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double workPrices[];
double workResult[];
int    r;

double iCustomMA(double price, int period, int method, int i)
{
   if (ArraySize(workPrices)!= Bars) ArrayResize(workPrices,Bars);
            r = Bars-i-1;
   workPrices[r] = price;

   //
   //
   //
   //
   //
   
      switch(method)
      {
         case  0: return(iSma(price,period,i));
         case  1: return(iEma(price,period,i));
         case  2: return(iSmma(price,period,i));
         case  3: return(iLwma(price,period,i));
         case  4: return(iLsma(price,period,i));
         case  5: return(iTma(price,period,i));
         case  6: return(iSineWMA(price,period,i));
         case  7: return(iVolumeWMA(price,period,i));
         case  8: return(iHma(price,period,i));
         case  9: return(iNonLagMa(price,period,i));
         case 10: return(iLwmp(price,period,i));
      }
   return(EMPTY_VALUE);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double iSma(double price, double period, int i)
{
   double sum = 0;
   for(int k=0; k<period && (r-k)>=0; k++) sum += workPrices[r-k];  
   if (k!=0)
         return(sum/k);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iEma(double price, double period, int i)
{
   if (ArraySize(workResult)!= Bars) ArrayResize(workResult,Bars);
   double alpha = 2.0 / (1.0+period);
          workResult[r] = workResult[r-1]+alpha*(price-workResult[r-1]);
   return(workResult[r]);
}
//
//
//
//
//

double iSmma(double price, double period, int i)
{
   if (ArraySize(workResult)!= Bars) ArrayResize(workResult,Bars);
   if (i>=(Bars-period))
   {
      double sum = 0; 
         for(int k=0; k<period && (r-k)>=0; k++) sum += workPrices[r-k];  
         if (k!=0)
               workResult[i] = sum/k;
         else  workResult[i] = EMPTY_VALUE;
   }      
   else   workResult[r] = (workResult[r-1]*(period-1)+price)/period;
   return(workResult[r]);
}

//
//
//
//
//

double iLwma_prices[][3];
double iLwma(double price, double period, int i,int forValue=0)
{
   if (ArrayRange(iLwma_prices,0)!= Bars) ArrayResize(iLwma_prices,Bars);
   
   //
   //
   //
   //
   //
   
   iLwma_prices[r][forValue] = price;
      double sum  = 0;
      double sumw = 0;

      for(int k=0; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*iLwma_prices[r-k][forValue];  
      }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iLwmp_prices[][3];
double iLwmp(double price, double period, int i,int forValue=0)
{
   if (ArrayRange(iLwmp_prices,0)!= Bars) ArrayResize(iLwmp_prices,Bars);
   
   //
   //
   //
   //
   //
   
   iLwmp_prices[r][forValue] = price;
      double sum  = 0;
      double sumw = 0;

      for(int k=0; k<period && (r-k)>=0; k++)
      {
         double weight = (period-k)*(period-k);
                sumw  += weight;
                sum   += weight*iLwmp_prices[r-k][forValue];  
      }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iLsma(double price, double period, int i)
{
   return(3.0*iLwma(price,period,i)-2.0*iSma(price,period,i));
}

//
//
//
//
//

double iHma(double price, double period, int i)
{
   int HalfPeriod = MathFloor(period/2);
   int HullPeriod = MathFloor(MathSqrt(period));
            double price1 = 2.0*iLwma(price,HalfPeriod,i,0)-iLwma(price,period,i,1);
   return (iLwma(price1,HullPeriod,i,2));
}

//
//
//
//
//

double iTma(double price, double period, int i)
{
   double half = (period+1.0)/2.0;
   double sum  = 0;
   double sumw = 0;

   for(int k=0; k<period && (r-k)>=0; k++)
   {
      double weight = k+1; if (weight > half) weight = period-k;
             sumw  += weight;
             sum   += weight*workPrices[r-k];  
   }             
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

#define Pi 3.14159265358979323846
double iSineWMA(double price, int period, int i)
{
   double sum  = 0;
   double sumw = 0;
  
   for(int k=0; k<period && (r-k)>=0; k++)
   { 
      double weight = MathSin(Pi*(k+1)/(period+1));
             sumw  += weight;
             sum   += weight*workPrices[r-k]; 
   }
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}

//
//
//
//
//

double iVolumeWMA(double price, int period, int i)
{
   double sum  = 0;
   double sumw = 0;
  
   for(int k=0; k<period && (r-k)>=0; k++)
   { 
      double weight = Volume[i+k];
             sumw  += weight;
             sum   += weight*workPrices[r-k]; 
   }
   if (sumw!=0)
         return(sum/sumw);
   else  return(EMPTY_VALUE);
}


//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

#define _length  0
#define _len     1
#define _weight  2

#define numOfSeparateCalculations 1
double  nlm_values[3][numOfSeparateCalculations];
double  nlm_prices[ ][numOfSeparateCalculations];
double  nlm_alphas[ ][numOfSeparateCalculations];

//
//
//
//
//

double iNonLagMa(double price, int length, int i, int forValue=0)
{
   if (ArrayRange(nlm_prices,0) != Bars) ArrayResize(nlm_prices,Bars);
                               nlm_prices[r][forValue]=price;
   if (length<3 || r<3) return(nlm_prices[r][forValue]);
   
   //
   //
   //
   //
   //
   
   if (nlm_values[_length][forValue] != length)
   {
      double Cycle = 4.0;
      double Coeff = 3.0*Pi;
      int    Phase = length-1;
      
         nlm_values[_length][forValue] = length;
         nlm_values[_len   ][forValue] = length*4 + Phase;  
         nlm_values[_weight][forValue] = 0;

         if (ArrayRange(nlm_alphas,0) < nlm_values[_len][forValue]) ArrayResize(nlm_alphas,nlm_values[_len][forValue]);
         for (int k=0; k<nlm_values[_len][forValue]; k++)
         {
            if (k<=Phase-1) 
                 double t = 1.0 * k/(Phase-1);
            else        t = 1.0 + (k-Phase+1)*(2.0*Cycle-1.0)/(Cycle*length-1.0); 
            double beta = MathCos(Pi*t);
            double g = 1.0/(Coeff*t+1); if (t <= 0.5 ) g = 1;
      
            nlm_alphas[k][forValue]        = g * beta;
            nlm_values[_weight][forValue] += nlm_alphas[k][forValue];
         }
   }
   
   //
   //
   //
   //
   //
   
   if (nlm_values[_weight][forValue]>0)
   {
      double sum = 0;
           for (k=0; k < nlm_values[_len][forValue]; k++) sum += nlm_alphas[k][forValue]*nlm_prices[r-k][forValue];
           return( sum / nlm_values[_weight][forValue]);
   }
   else return(0);           
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

string methodNames[] = {"SMA","EMA","SMMA","LWMA","LSMA","TriMA","SWMA","VWMA","HullMA","NonLagMA","LWM parabolic"};
string getAverageName(int& method)
{
   method=MathMax(MathMin(method,10),0); return(methodNames[method]);
}

//
//
//
//
//

void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] == 1) drawArrow(i,arrowsUpColor,221,false);
         if (trend[i] ==-1) drawArrow(i,arrowsDnColor,222,true);
      }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
  
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}

Your indicator can display 6 buffers

Your sma buffer is buffer number 9 (8 in the MQL numbering). Change the buffer numbers for buffer 5 and buffer 8 in the init (make the buffer 5 to be buffer 8 and make the buffer 8 to be buffer 5)

danizani95
142
danizani95  
mladen:

Your indicator can display 6 buffers

Your sma buffer is buffer number 9 (8 in the MQL numbering). Change the buffer numbers for buffer 5 and buffer 8 in the init (make the buffer 5 to be buffer 8 and make the buffer 8 to be buffer 5)

Mmm I tried to what you say but the sma is not showing... Any other suggestions ?
Mladen Rakic
110305
Mladen Rakic  
danizani95:
Mmm I tried to what you say but the sma is not showing... Any other suggestions ?

Use this

PS: please do not paste the code as you do. Simply attach the file (if the code is long) or, if the code is short, paste it using the source tool. This way nobody can read those posts

danizani95
142
danizani95  
mladen:

Use this

PS: please do not paste the code as you do. Simply attach the file (if the code is long) or, if the code is short, paste it using the source tool. This way nobody can read those posts

ok thank you very much mladen :) !
myname
3232
myname  
Why adding average to OSMA? isn't that just adding lag?
Intrest1
202
Intrest1  
Hello. For some reason when the parameter value Nslow - 1 and for large periods of the indicator signals is inverted. Where the price goes in the top of the indicator down signals and Vice versa. This is evident by the pink and blue lines, they are below zero when the price is rising and higher when decreases.
is this normal or can I do differently?
To add comments, please log in or register