//------------------------------------------------------------------
//                                                   ChandesDMI.mq4 
//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers   8
#property indicator_color1    DarkSlateGray
#property indicator_color2    DarkSlateGray
#property indicator_color3    DarkSlateGray
#property indicator_color4    Gray
#property indicator_color5    LimeGreen
#property indicator_color6    LimeGreen
#property indicator_color7    PaleVioletRed
#property indicator_color8    PaleVioletRed
#property indicator_width4    2 
#property indicator_width5    2 
#property indicator_width6    2 
#property indicator_width7    2 
#property indicator_width8    2 
#property indicator_style2    STYLE_DOT

//
extern int    Price           =  0; // Applied Price: 0-Close,1-Open,2-High,3-Low,4-Median,5-Typical,6-Weighted
extern int    StdDevPeriod    =  5; // Period of Standard Deviation
extern int    MAStdDevPeriod  = 10; // Period of smoothing
extern int    MAStdDevMode    =  0; // Mode of smoothing MA
extern int    DMIPeriod       =  5; // Dynamic Momentum Index Period
extern int    DmiLowerLimit   = 10; // Dynamic Periods Lower Bound
extern int    DmiUpperLimit   = 50; // Dynamic Periods Upper Bound
extern double LevelUp         = 70;
extern double LevelDown       = 30;
extern int    maPeriod        = 20;
extern int    maMethod        =  1;
extern int    maPrice         =  0;

//
//
//
//
//

double dmi[];
double dmiUa[];
double dmiUb[];
double dmiDa[];
double dmiDb[];
double levelUp[];
double levelMi[];
double levelDn[];
int    atrTimeFrame;


//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,levelUp);
   SetIndexBuffer(1,levelMi);
   SetIndexBuffer(2,levelDn);
   SetIndexBuffer(3,dmi);
   SetIndexBuffer(4,dmiUa);
   SetIndexBuffer(5,dmiUb);
   SetIndexBuffer(6,dmiDa);
   SetIndexBuffer(7,dmiDb);
   IndicatorShortName("TC Chandes DMI ("+Price+","+StdDevPeriod+","+MAStdDevPeriod+","+getAverageName(MAStdDevMode)+","+DMIPeriod+")");

   //
   //
   //
   //
   //
   
   atrTimeFrame=PERIOD_D1;
   if (Period() >= atrTimeFrame)
      switch (Period())
         {
            case PERIOD_D1: atrTimeFrame = PERIOD_W1; break;
            default:        atrTimeFrame = PERIOD_MN1;
         }
   return(0);
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double wrkBuffer[][14];
#define _state 13
int start()
{
   int i,r,counted_bars = IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars - counted_bars,Bars-1);
         if (ArrayRange(wrkBuffer,0) != Bars) ArrayResize(wrkBuffer,Bars);
  
   //
   //
   //
   //
   //
      
   if (wrkBuffer[Bars-limit-1][_state] == 1) CleanPoint(limit,dmiUa,dmiUb);
   if (wrkBuffer[Bars-limit-1][_state] ==-1) CleanPoint(limit,dmiDa,dmiDb);
   for(i=limit, r=Bars-i-1; i>=0; i--, r++)
   {
      double deviation = iStdDev(NULL,0,StdDevPeriod,0,MODE_SMA,Price,i);
      double mastd     = iCustomMa(MAStdDevMode,deviation,MAStdDevPeriod,i); 
      double td        = 0;
      double vi        = 0;
      if (mastd != 0) vi = deviation/mastd;
      if (vi != 0)    td = DMIPeriod/vi; 
      if (td > DmiUpperLimit ) td = DmiUpperLimit;
      if (td < DmiLowerLimit ) td = DmiLowerLimit;

      //
      //
      //
      //
      //
      
      wrkBuffer[r][12] = iMA(NULL,0,1,0,MODE_SMA,Price,i);
            double Kg  = (3.0)/(2.0+td);
            double Hg  = 1.0-Kg;
            double roc = wrkBuffer[r][12]-wrkBuffer[r-1][12];
            double roa = MathAbs(roc);
            for (int k=0; k<3; k++)
            {
               int kk = k*2;
                  wrkBuffer[r][kk+0] = Kg*roc                + Hg*wrkBuffer[r-1][kk+0];
                  wrkBuffer[r][kk+1] = Kg*wrkBuffer[r][kk+0] + Hg*wrkBuffer[r-1][kk+1]; roc = 1.5*wrkBuffer[r][kk+0] - 0.5 * wrkBuffer[r][kk+1];
                  wrkBuffer[r][kk+6] = Kg*roa                + Hg*wrkBuffer[r-1][kk+6];
                  wrkBuffer[r][kk+7] = Kg*wrkBuffer[r][kk+6] + Hg*wrkBuffer[r-1][kk+7]; roa = 1.5*wrkBuffer[r][kk+6] - 0.5 * wrkBuffer[r][kk+7];
            }
                     
         if (roa != 0)
              double dmires = MathMax(MathMin((roc/roa+1.0)*50.0,100.00),0.00); 
         else        dmires = 50.0;
         dmiUa[i] = EMPTY_VALUE;
         dmiUb[i] = EMPTY_VALUE;
         dmiDa[i] = EMPTY_VALUE;
         dmiDb[i] = EMPTY_VALUE;

      //
      //
      //
      //
      //
      //

      if (dmires<LevelDown)                    wrkBuffer[r][_state]  = -1;
      if (dmires>LevelUp)                      wrkBuffer[r][_state]  =  1;
      if (dmires>LevelDown && dmires<LevelUp)  wrkBuffer[r][_state]  =  0;
         int y = iBarShift(NULL,atrTimeFrame,Time[i]);
            double avgRange = iATR(NULL,atrTimeFrame,maPeriod,y);
            double maValue  = iMA(NULL,0,maPeriod,0,maMethod,maPrice,i);
            levelMi[i] = maValue;
            levelUp[i] = maValue+(avgRange*(LevelUp-50  )/100);
            levelDn[i] = maValue-(avgRange*(50-LevelDown)/100);
            dmi[i]     = maValue+(dmires-50)/100*avgRange;
      if (wrkBuffer[r][_state]  == 1) PlotPoint(i,dmiUa,dmiUb,dmi);
      if (wrkBuffer[r][_state]  ==-1) PlotPoint(i,dmiDa,dmiDb,dmi);
   }
   return(0);
}


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

string methodNames[] = {"SMA","EMA","Smoothed MA","Linear weighted MA"};
string getAverageName(int& method)
{
   int max = ArraySize(methodNames)-1;
      method=MathMax(MathMin(method,max),0); return(methodNames[method]);
}

//
//
//
//
//

#define _maWorkBufferx1 1
#define _maWorkBufferx2 2
#define _maWorkBufferx3 3

double iCustomMa(int mode, double price, double length, int i, int instanceNo=0)
{
   int r = Bars-i-1;
   switch (mode)
   {
      case 0  : return(iSma(price,length,r,instanceNo));
      case 1  : return(iEma(price,length,r,instanceNo));
      case 2  : return(iSmma(price,length,r,instanceNo));
      case 3  : return(iLwma(price,length,r,instanceNo));
      default : return(0);
   }
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double workSma[][_maWorkBufferx2];
double iSma(double price, int period, int r, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2;

   //
   //
   //
   //
   //
      
   workSma[r][instanceNo] = price;
   if (r>=period)
          workSma[r][instanceNo+1] = workSma[r-1][instanceNo+1]+(workSma[r][instanceNo]-workSma[r-period][instanceNo])/period;
   else { workSma[r][instanceNo+1] = 0; for(int k=0; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo];  
          workSma[r][instanceNo+1] /= k; }
   return(workSma[r][instanceNo+1]);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars);

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workDema[][_maWorkBufferx2];
double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= Bars) ArrayResize(workSmma,Bars);

   //
   //
   //
   //
   //

   if (r<period)
         workSmma[r][instanceNo] = price;
   else  workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= Bars) ArrayResize(workLwma,Bars);
   
   //
   //
   //
   //
   //
   
   workLwma[r][instanceNo] = price;
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}
  
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i]   = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]   = from[i];
         second[i]  = EMPTY_VALUE;
      }
}
  
//+------------------------------------------------------------------+
/*

Source Code For Metastock

========================
Dynamic Mom Index - jose
========================
---8<---------------------------

{ Jose's Dynamic Momentum Index v3.1, 0~100% }
{ ©Copyright 2003-2004 Jose Silva }
{ http://www.metastocktools.com }

pds:=Input("avg DyMoIdx periods",3,252,21);
Stpds:=
 Input("Standard Deviation periods",2,252,5);
x:=Input("use Open=1 High=2 Low=3 Close=4 Volume=5 P=6",1,6,4);
plot:=Input("[1]Dynamic Momentum Idx,  [2]dynamic periods used",1,2,1);

x:=If(x=1,O,If(x=2,H,If(x=3,L,If(x=5,V,
 If(x=6,P,C)))));
Vt:=Stdev(x,Stpds)/Mov(Stdev(x,Stpds),10,S);
pds:=pds/(Vt+.14142);
pds:=If(pds>Cum(IsDefined(x))-13,
 Cum(IsDefined(x))-13,pds);
pds:=If(pds<2,2,pds);

Up:=If(x>Ref(x,-1),x-Ref(x,-1),0);
Dw:=If(x<Ref(x,-1),Ref(x,-1)-x,0);
UpAvg:=Up*2/pds+PREV*(1-2/pds);
DwAvg:=Dw*2/pds+PREV*(1-2/pds);
DyMoIdx:=
 100-(100/(1+UpAvg/If(DwAvg>0,DwAvg,.000001)));

If(plot=1,DyMoIdx,pds)

---8<---------------------------

Source Code From VTS:

Vi:= Stdev(price,stdevPeriods) / Mov(Stdev(price,stdevPeriods),stdevmaper,stdevmat) ;
Td:= Int(DmiPeriods/Vi);
Td:= if(Td>DmiUpperLimit,DmiUpperLimit,if(Td<DmiLowerLi mit,DmiLowerLimit,Td));

rsi_r:= (price - ref(price,-1));
rsi_rs:= Wilders(if(rsi_r>0,rsi_r,0),Td) / Wilders(if(rsi_r<0,Abs(rsi_r),0),Td);
DMIndex:= 100-(100/(1+rsi_rs));

IndicatorPlot:= if(plot=0,DMIndex,Td);
*/

