//+------------------------------------------------------------------+
//|                                                       adxvma.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link "www.forex-station.com"
//----
#property indicator_chart_window
#property indicator_buffers 5
//----
#property indicator_color1 DimGray 
#property indicator_color2 Lime
#property indicator_color3 Lime
#property indicator_color4 Red
#property indicator_color5 Red
//----
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2
#property indicator_width4 2
#property indicator_width5 2
//----
#property strict
//----
extern ENUM_TIMEFRAMES TimeFrame = PERIOD_CURRENT; // Time frame to use
extern double AdxVmaPeriod = 10; // Adxvma period
extern ENUM_APPLIED_PRICE AdxVmaPrice = PRICE_MEDIAN; // Price to use
extern bool TrendMode = true; // Trend mode?
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; 
extern string             btn_text              = "adxvma.";
extern string             btn_Font              = "Arial";      //"Arial Black"
extern int                btn_FontSize          = 8;                            
extern color              btn_text_ON_color     = clrWhite;
extern color              btn_text_OFF_color    = clrRed;
extern string             btn_pressed           = "adxvma off";            
extern string             btn_unpressed         = "adxvma on";
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrDarkGray;
extern int                button_x              = 900;                                 
extern int                button_y              = 0;                                   
extern int                btn_Width             = 60;                                 
extern int                btn_Height            = 20;     
extern bool Interpolate = true; // Interpolate in multi time frame mode?
//----
double adxvma[];
double adxvmua[];
double adxvmub[];
double adxvmda[];
double adxvmdb[];
double trend[];
//----
string indicatorFileName;
bool returnBars;
//
bool                      show_data             = true;
string IndicatorName, IndicatorObjPrefix ,buttonId ;
string GenerateIndicatorName(const string target)
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int init()
{
   IndicatorBuffers(6);
   SetIndexBuffer(0,adxvma);
   SetIndexBuffer(1,adxvmua);
   SetIndexBuffer(2,adxvmub);
   SetIndexBuffer(3,adxvmda);
   SetIndexBuffer(4,adxvmdb);
   SetIndexBuffer(5,trend);

   //
   //
   //
   //
   //

      AdxVmaPeriod      = MathMax(AdxVmaPeriod,1);
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame==-99;
      TimeFrame         = MathMax(TimeFrame,_Period);

   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" AdxVma ("+DoubleToStr(AdxVmaPeriod,2)+")");
   
    IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(WindowExpertName());
   IndicatorDigits(Digits);
   
   double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
   show_data = val != 0;

   ChartSetInteger(ChartID(), CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix+btn_text;
   createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_XDISTANCE, button_x); 
   
   return(0);
}
 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//

void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
      ObjectDelete    (ChartID(),buttonID);
      ObjectCreate    (ChartID(),buttonID,OBJ_BUTTON,0,0,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_COLOR,txtColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BGCOLOR,bgColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BORDER_COLOR,borderColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XSIZE,width);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YSIZE,height);
      ObjectSetString (ChartID(),buttonID,OBJPROP_FONT,font);
      ObjectSetString (ChartID(),buttonID,OBJPROP_TEXT,buttonText);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_FONTSIZE,fontSize);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_SELECTABLE,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_CORNER,btn_corner);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_HIDDEN,1);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XDISTANCE,9999);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YDISTANCE,9999);
}

int deinit()
{
   ObjectsDeleteAll(0,"adxvma.");
   ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);
   
return(0);
}

//
//
bool recalc = true;

void handleButtonClicks()
{
   if (ObjectGetInteger(ChartID(), buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(ChartID(), buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(IndicatorName + "_visibility", show_data ? 1.0 : 0.0);
      recalc = true;
      start();
   }
}
void OnChartEvent(const int id, 
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   handleButtonClicks();
  
}

//
//
//

int start()
{
//template code 
   handleButtonClicks();
   recalc = false;
   
   start2();
   
      SetIndexStyle( 0,   DRAW_LINE );
      SetIndexStyle( 1,  DRAW_LINE );
      SetIndexStyle( 2,   DRAW_LINE );
      SetIndexStyle( 3,  DRAW_LINE );
      
   
   if (show_data)
   {
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
      ObjectSetString(ChartID(),buttonId,OBJPROP_TEXT,btn_unpressed);
   }
   else
   {
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
      ObjectSetString(ChartID(),buttonId,OBJPROP_TEXT,btn_pressed);
         SetIndexStyle(0,DRAW_NONE);
         SetIndexStyle(1,DRAW_NONE);
         SetIndexStyle(2,DRAW_NONE);
         SetIndexStyle(3,DRAW_NONE);
         
           
   }
   return(0);
}
//
//
//
//

double  work[][6];
#define prc 0
#define pdm 1
#define mdm 2
#define pdi 3
#define mdi 4
#define out 5

//
//
//
//
//

int start2()
{
   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) { adxvma[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (TimeFrame == _Period)
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      if (trend[limit]== 1) CleanPoint(limit,adxvmua,adxvmub);
      if (trend[limit]==-1) CleanPoint(limit,adxvmda,adxvmdb);
      
      //
      //
      //
      //
      //
      
      for(int i = limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         work[r][prc] = NormalizeDouble(iMA(NULL,0,1,0,MODE_SMA,AdxVmaPrice,i),4);

         //
         //
         //
         //
         //
            
         if (r<1) continue;            
         double diff = work[r][prc]-work[r-1][prc];
//         double tpdm = work[r-1][pdm];
//         double tmdm = work[r-1][mdm];
         
         double tpdm = 0;
         double tmdm = 0;
               if (diff>0)
                     tpdm =  diff;
               else  tmdm = -diff;          
         work[r][pdm] = ((AdxVmaPeriod-1.0)*work[r-1][pdm]+tpdm)/AdxVmaPeriod;
         work[r][mdm] = ((AdxVmaPeriod-1.0)*work[r-1][mdm]+tmdm)/AdxVmaPeriod;

         //
         //
         //
         //
         //

         double trueRange = work[r][pdm]+work[r][mdm];
         double tpdi      = 0;
         double tmdi      = 0;
               if (trueRange>0)
               {
                  tpdi = work[r][pdm]/trueRange;
                  tmdi = work[r][mdm]/trueRange;
               }            
         work[r][pdi] = ((AdxVmaPeriod-1.0)*work[r-1][pdi]+tpdi)/AdxVmaPeriod;
         work[r][mdi] = ((AdxVmaPeriod-1.0)*work[r-1][mdi]+tmdi)/AdxVmaPeriod;
   
         //
         //
         //
         //
         //
                  
         double tout  = 0; if ((work[r][pdi]+work[r][mdi])>0) tout = MathAbs(work[r][pdi]-work[r][mdi])/(work[r][pdi]+work[r][mdi]);
         work[r][out] = ((AdxVmaPeriod-1.0)*work[r-1][out]+tout)/AdxVmaPeriod;

         //
         //
         //
         //
         //
                 
         double thi = MathMax(work[r][out],work[r-1][out]);
         double tlo = MathMin(work[r][out],work[r-1][out]);
            for (int j = 2; j<AdxVmaPeriod && r-j>=0; j++)
            {
               thi = MathMax(work[r-j][out],thi);
               tlo = MathMin(work[r-j][out],tlo);
            }            
         double vi = 0; if ((thi-tlo)>0) vi = (work[r][out]-tlo)/(thi-tlo);

      //
      //
      //
      //
      //
         
         adxvma[i]  = ((AdxVmaPeriod-vi)*adxvma[i+1]+vi*work[r][prc])/AdxVmaPeriod;
         adxvmua[i] = EMPTY_VALUE;
         adxvmub[i] = EMPTY_VALUE;
         adxvmda[i] = EMPTY_VALUE;
         adxvmdb[i] = EMPTY_VALUE;

            if (TrendMode)
                  trend[i] = trend[i+1];
            else  trend[i] = 0;
            if (adxvma[i]>adxvma[i+1]) trend[i] =  1;
            if (adxvma[i]<adxvma[i+1]) trend[i] = -1;
            if (trend[i]== 1) PlotPoint(i,adxvmua,adxvmub,adxvma);
            if (trend[i]==-1) PlotPoint(i,adxvmda,adxvmdb,adxvma);
      }
      return(0);
   }
   
   
   //
   //
   //
   //
   //
   
   limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/_Period));
   if (trend[limit]== 1) CleanPoint(limit,adxvmua,adxvmub);
   if (trend[limit]==-1) CleanPoint(limit,adxvmda,adxvmdb);
   for (int i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         adxvma[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AdxVmaPeriod,AdxVmaPrice,TrendMode,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_pressed,btn_unpressed,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,0,y);
         trend[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,AdxVmaPeriod,AdxVmaPrice,TrendMode,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_pressed,btn_unpressed,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,5,y);
         adxvmua[i] = EMPTY_VALUE;
         adxvmub[i] = EMPTY_VALUE;
         adxvmda[i] = EMPTY_VALUE;
         adxvmdb[i] = EMPTY_VALUE;

         //
         //
         //
         //
         //
      
            if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;

         //
         //
         //
         //
         //

         int n,k; datetime time = iTime(NULL,TimeFrame,y);
            for(n = 1; i+n<Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; i+n<Bars && i+k<Bars && k<n; k++)
               adxvma[i+k] = adxvma[i] + (adxvma[i+n]-adxvma[i])*k/n;
   }
   for (int i=limit;i>=0;i--)
   {
      if (trend[i]== 1) PlotPoint(i,adxvmua,adxvmub,adxvma);
      if (trend[i]==-1) PlotPoint(i,adxvmda,adxvmdb,adxvma);
   }
   return(0);
}



//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) return;
   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 (i>=Bars-2) return;
   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};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}