//+------------------------------------------------------------------+
//|                                  Kaufman Adaptive Moving Average |
//|                                            Kaufman AMA basic.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      ""

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1  LimeGreen
#property indicator_color2  Orange
#property indicator_color3  Orange
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2

//
//
//
//
//

extern string TimeFrame       = "Current time frame"; 
extern int    AMAPeriod       = 10;
extern int    AMAPrice        = PRICE_CLOSE;
extern int    Nfast           = 2;
extern int    Nslow           = 30;
extern double GCoeff          = 2;
extern int    PriceFilter     = 5;
extern int    PriceFilterMode = MODE_EMA;
extern bool   LinesVisible    = true;
extern int    LinesNumber     = 5;
extern color  ColorUp         = Blue;
extern color  ColorDown       = Red;
extern string UniqueID        = "KaufmanLines1";

//
//
//
//
//

double kAMAbuffer[];
double kAMAbufferda[];
double kAMAbufferdb[];
double slope[];
string indicatorFileName;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(4);
   SetIndexBuffer(0,kAMAbuffer);
   SetIndexBuffer(1,kAMAbufferda);
   SetIndexBuffer(2,kAMAbufferdb);
   SetIndexBuffer(3,slope);
   
      //
      //
      //
      //
      //
         
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame == "returnBars";     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
   
      //
      //
      //
      //
      //
   
   
   IndicatorShortName(timeFrameToString(timeFrame)+" Kaufman AMA ("+AMAPeriod+")");
   return(0);
}
void deinit()
{
   deleteLines();
}
void deleteLines()
{
   int lookForLength = StringLen(UniqueID);
   for (int i= ObjectsTotal()-1; i>=0; i--)
   {
      string name = ObjectName(i);
      if (StringSubstr(name,0,lookForLength)==UniqueID) ObjectDelete(name);
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { kAMAbuffer[0] = limit+1; return(0); }
           if (timeFrame!=Period())
           {
               limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
               if (slope[limit]==-1) CleanPoint(limit,kAMAbufferda,kAMAbufferdb);
               for (int i=limit; i>=0; i--)
               {
                   int y = iBarShift(NULL,timeFrame,Time[i]);               
                     kAMAbuffer[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",AMAPeriod,AMAPrice,Nfast,Nslow,GCoeff,PriceFilter,PriceFilterMode,LinesVisible,LinesNumber,ColorUp,ColorDown,UniqueID,0,y);
                     kAMAbufferda[i] = EMPTY_VALUE;
                     kAMAbufferdb[i] = EMPTY_VALUE;
                     slope[i]        = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",AMAPeriod,AMAPrice,Nfast,Nslow,GCoeff,PriceFilter,PriceFilterMode,LinesVisible,LinesNumber,ColorUp,ColorDown,UniqueID,3,y);
                     if (slope[i]==-1) PlotPoint(i,kAMAbufferda,kAMAbufferdb,kAMAbuffer);
               }
               return(0);
           }

   //
   //
   //
   //
   //
   
   if (slope[limit]==-1) CleanPoint(limit,kAMAbufferda,kAMAbufferdb);
   for(i=limit; i>=0; i--)
   {
      kAMAbuffer[i]   = iKama(iMA(NULL,0,PriceFilter,0,PriceFilterMode,AMAPrice,i),AMAPeriod,Nfast,Nslow,GCoeff,i);
      kAMAbufferda[i] = EMPTY_VALUE;
      kAMAbufferdb[i] = EMPTY_VALUE;
      slope[i]        = slope[i+1];
         if (kAMAbuffer[i]>kAMAbuffer[i+1]) slope[i] =  1;
         if (kAMAbuffer[i]<kAMAbuffer[i+1]) slope[i] = -1;
         if (slope[i]==-1) PlotPoint(i,kAMAbufferda,kAMAbufferdb,kAMAbuffer);
   }      
   
   deleteLines();
         if (LinesVisible)
         {
            int k = 0;
            for (i=0; i<Bars && k<LinesNumber; i++)
            if (slope[i]!= slope[i+1])
               {
                  string name = UniqueID+(string)Time[i];
                  ObjectCreate(name,OBJ_TREND,0,Time[i],kAMAbuffer[i],Time[i]+Period()*60,kAMAbuffer[i]);
                     if (slope[i]==1)
                           ObjectSet(name,OBJPROP_COLOR,ColorUp);
                     else  ObjectSet(name,OBJPROP_COLOR,ColorDown);                   
                     k++;
               }
         }               
   return(0);
}
  
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

double work[][3];
#define _price 0
#define _ama   1
#define _diff  2

double iKama(double price, int period, double fast, double slow, double gCoeff, int i, int s=0)
{
   if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars); int r = Bars-i-1; s *= 3;
      work[r][s+_price] = price;
   
   //
   //
   //
   //
   //
   
   double smooth;
   double signal;
   double noise   = 0;
   double efratio = 1.00;
   double fastend          = (2.0 /(fast + 1.0));
   double slowend          = (2.0 /(slow + 1.0));
          signal           = MathAbs(work[r][s+_price]-work[r-period][s+_price]);
          work[r][s+_diff] = MathAbs(work[r][s+_price]-work[r-1][s+_price]);
          for (int k=0; k<period && (r-k)>=0;k++)
                     noise += work[r-k][s+_diff];

          //
          //
          //
          //
          //

          if (noise != 0) efratio = signal/noise;
                          smooth  = MathPow(efratio*(fastend-slowend)+slowend,gCoeff);
                          work[r][s+_ama] = work[r-1][s+_ama] + smooth*(work[r][s+_price]-work[r-1][s+_ama]);
   return(work[r][s+_ama]);          
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = 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;
      }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}