//+------------------------------------------------------------------+
//|                                                         dema.mq4 | 
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1  Blue

//
//
//
//
//

extern int    DemaPeriod = 12;
extern int    Price      = PRICE_CLOSE;

//
//
//
//
//

double dema[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,dema);   
   IndicatorShortName(" dema ");
return(0);
}

int deinit()  {   return(0);  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);


   //
   //
   //
   //
   //
   
   for (i=limit; i>=0; i--)
   {
       double price = iMA(NULL,0,1,0,MODE_SMA,Price,i);
       dema[i]   = iDema(price,DemaPeriod,i);
         
    }
return(0);
}
     
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workDema[][2];
#define _ema1 0
#define _ema2 1

double iDema(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workDema,0)!= Bars) ArrayResize(workDema,Bars); instanceNo*=2; r = Bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workDema[r][_ema1+instanceNo] = workDema[r-1][_ema1+instanceNo]+alpha*(price                        -workDema[r-1][_ema1+instanceNo]);
          workDema[r][_ema2+instanceNo] = workDema[r-1][_ema2+instanceNo]+alpha*(workDema[r][_ema1+instanceNo]-workDema[r-1][_ema2+instanceNo]);
   return(workDema[r][_ema1+instanceNo]*2.0-workDema[r][_ema2+instanceNo]);
}

