//+------------------------------------------------------------------+
//|                                                       adxvma.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  DeepSkyBlue 
#property indicator_color2  OrangeRed
#property indicator_color3  DimGray  
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_minimum 0
#property indicator_maximum 1

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern double AdxVmaPeriod     = 15;
extern int    AdxVmaPrice      = PRICE_WEIGHTED;//PRICE_MEDIAN;
extern bool   TrendMode        = true;
extern bool   alertsOn         = false;
extern bool   alertsOnCurrent  = true;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsNotify     = true;//false;
extern bool   alertsEmail      = false;
extern string soundFile        = "alert2.wav";
extern bool   ShowArrows       = false;
extern string arrowsIdentifier = "adxvma Arrows1";
extern double arrowsUpperGap   = 1.0;
extern double arrowsLowerGap   = 1.0;
extern color  arrowsUpColor    = LimeGreen;
extern color  arrowsDnColor    = Red;
extern int    arrowsUpCode     = 241;
extern int    arrowsDnCode     = 242;

//
//
//
//
//

double adxvma[];
double adxvmua[];
double adxvmda[];
double adxvmna[];
double trend[];

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

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

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,adxvmua);SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,adxvmda);SetIndexStyle(1,DRAW_HISTOGRAM);  
   SetIndexBuffer(2,adxvmna);SetIndexStyle(2,DRAW_HISTOGRAM);  
   SetIndexBuffer(3,adxvma); 
   SetIndexBuffer(4,trend);
   
   //
   //
   //
   //
   //
   
      AdxVmaPeriod      = MathMax(AdxVmaPeriod,1);
      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="CalculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
      
   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" AdxVma ("+DoubleToStr(AdxVmaPeriod,2)+")");
   return(0);
}
int deinit() 
{  
   deleteArrows(); 
return(0); 
}

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

double  work[][6];
#define prc 0
#define pdm 1
#define mdm 2
#define pdi 3
#define mdi 4
#define out 5

int start()
{
   int counted_bars = IndicatorCounted();
   int i,r,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { adxvmua[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      for(i = limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         work[r][prc] = NormalizeDouble(iMA(NULL,0,1,0,MODE_SMA,AdxVmaPrice,i),4);

         //
         //
         //
         //
         //
            
         double diff = work[r][prc]-work[r-1][prc];
         double tpdm = work[r-1][pdm];
         double tmdm = work[r-1][mdm];
               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 diDiff = MathAbs(work[r][pdi]-work[r][mdi]);
         double diSumm =         work[r][pdi]+work[r][mdi];
         double tout   = 0;
               if (diSumm>0) tout = diDiff/diSumm;
         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 = 1; j<AdxVmaPeriod-1; j++)
            {
               thi = MathMax(work[r-j-1][out],thi);
               tlo = MathMin(work[r-j-1][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;
         adxvmda[i] = EMPTY_VALUE;
         adxvmna[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) adxvmua[i] = 1;
            if (trend[i]==-1) adxvmda[i] = 1;
            if (trend[i]== 0) adxvmna[i] = 1;
            
            //
            //
            //
            //
            //
     
            if (ShowArrows)
            {
              deleteArrow(Time[i]);
              if (trend[i] != trend[i+1])
              {
                 if (trend[i] == 1)  drawArrow(i,arrowsUpColor,arrowsUpCode,false);
                 if (trend[i] ==-1)  drawArrow(i,arrowsDnColor,arrowsDnCode, true);
              }
            }
         
            
      }
      
      //
      //
      //
      //
      //
      
      if (alertsOn)
      {
        if (alertsOnCurrent)
             int whichBar = 0;
        else     whichBar = 1;
        if (trend[whichBar] != trend[whichBar+1])
        if (trend[whichBar] == 1)
              doAlert("sloping up"  +"  "+ "("+ (AdxVmaPeriod)+")");
        else  doAlert("sloping down"+"  "+ "("+ (AdxVmaPeriod)+")");       
      }        
      return(0);
   }

   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         trend[i]   = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",AdxVmaPeriod,AdxVmaPrice,TrendMode,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,4,y);
         adxvmua[i] = EMPTY_VALUE;
         adxvmda[i] = EMPTY_VALUE;
            if (trend[i]== 1) adxvmua[i] = 1;
            if (trend[i]==-1) adxvmda[i] = 1;
            if (trend[i]== 0) adxvmna[i] = 1;
   }
   return(0);
         
}

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

string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,10,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);
}

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

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

         message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," adxvma ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," adxvma "),message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//
//
//
//
//

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] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsLowerGap * 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);
}




