//------------------------------------------------------------------
//
//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

#property indicator_chart_window
#property indicator_buffers    4
#property indicator_color1     clrNONE
#property indicator_color2     clrNONE
#property indicator_color3     clrNONE
#property indicator_color4     clrNONE


//
//
//
//
//

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_tbiased2,   // Trend biased (extreme) price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased,  // Heiken ashi trend biased price
   pr_hatbiased2  // Heiken ashi trend biased (extreme) price
};
enum enMaTypes
{
   ma_sma,    // Simple moving average
   ma_ema,    // Exponential moving average
   ma_smma,   // Smoothed MA
   ma_lwma,   // Linear weighted MA
   ma_tema    // Triple exponential moving average - TEMA
};

//AHTF Timeframe template copy and paste start11
enum enTimeFrames
{
   tf_cu  = PERIOD_CURRENT, // Current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_d1  = PERIOD_D1,      // Daily
   tf_w1  = PERIOD_W1,      // Weekly
   tf_mn1 = PERIOD_MN1,     // Monthly
   tf_n1  = -1,             // First higher time frame
   tf_n2  = -2,             // Second higher time frame
   tf_n3  = -3              // Third higher time frame
};
//AHTF Timeframe template copy and paste end11

//AHTF Timeframe template copy and paste start12
extern enTimeFrames       TimeFrame                       = tf_cu;                // Time frame
//AHTF Timeframe template copy and paste end12

extern int                FastMaPeriod                    = 12;           // Fast moving average period
extern enMaTypes          FastMaMethod                    = ma_ema;       // Fast moving average method   
extern int                SlowMaPeriod                    = 26;           // Slow moving average period
extern enMaTypes          SlowMaMethod                    = ma_ema;       // Slow moving average method   
extern int                SignalMaPeriod                  = 9;            // Signal moving average period
extern enMaTypes          SignalMaMethod                  = ma_sma;       // Signal moving average method   
extern enPrices           Price                           = pr_close;     // Price to use 
extern int                Shift                           = 0;            // Shift

//Forex-Station Zone template copy and paste start 1
extern bool               ShowZones_OnTheMainChart        = true;                 // Display the background zones on the main chart
extern bool               ShowZones_InTheSeparatedWindow1 = true;                 // Display the background zones in the first separated window
extern int                WhatSeparatedWindow1            = 1;
extern bool               ShowZones_InTheSeparatedWindow2 = true;                 // Display the background zones in the second separated window
extern int                WhatSeparatedWindow2            = 2;
extern color              ZoneColorUp                     = clrHoneydew;          // Uptrend Zone color
extern color              ZoneColorDown                   = clrLavenderBlush;     // Downtrend Zone color
extern string             UniqueZoneID                    = "MACDzones1";  // Unique ID for the zones
//Forex-Station Zone template copy and paste end 1

//Forex-Station Zone template copy and paste start 2
double Dummy = -1;
//Forex-Station Zone template copy and paste end 2
//
//
//
//
//

double macd[], Up[], Dn[], signal[], trend[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_y) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,FastMaPeriod,FastMaMethod,SlowMaPeriod,SlowMaMethod,SignalMaPeriod,SignalMaMethod,Price,Shift,ShowZones_OnTheMainChart,ShowZones_InTheSeparatedWindow1,WhatSeparatedWindow1,ShowZones_InTheSeparatedWindow2,WhatSeparatedWindow2,ZoneColorUp,ZoneColorDown,UniqueZoneID,_buff,_y)

//+------------------------------------------------------------------------------------------------------------------+
int init()
{
  
  IndicatorBuffers(6);
   SetIndexBuffer(0,Up);    
   SetIndexBuffer(1,Dn);    
   SetIndexBuffer(2,macd);
   SetIndexBuffer(3,signal); 
   SetIndexBuffer(4,trend);
   SetIndexBuffer(5,count);
     
   for (int i=0; i<7; i++) SetIndexShift(i,Shift);
   indicatorFileName = WindowExpertName();

//AHTF Timeframe Timeframe template copy and paste start13
   TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
//AHTF Timeframe Timeframe template copy and paste end13
     
   IndicatorShortName(timeFrameToString(TimeFrame) + " MACD ("+(string)FastMaPeriod+","+(string)SlowMaPeriod+","+(string)SignalMaPeriod+")");
return(0);
}
//+------------------------------------------------------------------------------------------------------------------+
//AHTF Timeframe template copy and paste start14
int timeFrameValue(int _tf)
{
   int add  = (_tf>=0) ? 0 : MathAbs(_tf);
   if (add != 0) _tf = _Period;
   int size = ArraySize(iTfTable); 
      int i =0; for (;i<size; i++) if (iTfTable[i]==_tf) break;
                                   if (i==size) return(_Period);
                                                return(iTfTable[(int)MathMin(i+add,size-1)]);
}
//AHTF Timeframe template copy and paste end14
//+------------------------------------------------------------------------------------------------------------------+
//Forex-Station Zone template copy and paste start 3
//+------------------------------------------------------------------------------------------------------------------+
int deinit()
{
   string lookFor       = UniqueZoneID+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   GlobalVariableDel(ChartID()+":"+UniqueZoneID);
   return(0);
}
//+------------------------------------------------------------------------------------------------------------------+
//Forex-Station Zone template copy and paste end 3
//+------------------------------------------------------------------------------------------------------------------+
int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = fmin(Bars-counted_bars,Bars-1); count[0]=limit;

//Forex-Station Zone template copy and paste start 4
         datetime tDummy = GlobalVariableGet(ChartID()+":"+UniqueZoneID); if (tDummy==0) tDummy = Time[0];
//Forex-Station Zone template copy and paste end 4

            if (TimeFrame!=_Period)
            {
               limit = (int)fmax(limit,fmin(Bars-1,_mtfCall(5,0)*TimeFrame/_Period));
               for (i=limit;i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     Up[i]    = _mtfCall(0,y);
                     Dn[i]    = _mtfCall(1,y);
                     macd[i]  = _mtfCall(2,y);
                     signal[i]= _mtfCall(3,y);
                     trend[i] = _mtfCall(4,y);
               }
//Forex-Station Zone template copy and paste start 5
               GlobalVariableSet(ChartID()+":"+UniqueZoneID,Time[0]+_Period*60-1);
//Forex-Station Zone template copy and paste end 5

             return(0);
            } //if (TimeFrame!=_Period)
   //
   //
   //
   //
   //

   for(i=limit; i>=0; i--)
   { 
      double price = getPrice(Price,Open,Close,High,Low,i);
      macd[i]   = iCustomMa(FastMaMethod,price,FastMaPeriod,i,0)-iCustomMa(SlowMaMethod,price,SlowMaPeriod,i,1);  
      signal[i] = iCustomMa(SignalMaMethod,macd[i],SignalMaPeriod,i,2);   
      Dn[i] = EMPTY_VALUE;
      Up[i] = EMPTY_VALUE;
      trend[i] = (i<Bars-1) ? (macd[i]>0) ? 1 : (macd[i]<0) ? -1 : trend[i+1] : 0;
      if (trend[i] == 1) Up[i] = macd[i];  
      if (trend[i] ==-1) Dn[i] = macd[i]; 

//Forex-Station Zone template copy and paste start 6

               for (int index=i; index<Bars; index++) if (trend[index]!= trend[index+1]) break;
               if (ShowZones_OnTheMainChart)
                  {
                    string name = UniqueZoneID+":"+Time[index+1]; ObjectDelete(name); ObjectDelete(UniqueZoneID+":"+Time[1]);
                    datetime lastTime = Time[i-1]; if (i==0) { lastTime = tDummy; if (Time[index]==lastTime) lastTime = Time[0]+Period()*60;}
                    ObjectCreate(name,OBJ_RECTANGLE,0,Time[index],0,lastTime,WindowPriceMax()*3.0);
                    ObjectSet(name,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                          ObjectSet(name,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name,OBJPROP_COLOR,ZoneColorUp);
                  }
               if (ShowZones_InTheSeparatedWindow1)
                  {
                    string name2 = UniqueZoneID+":aboveZero1"+Time[index+1]; ObjectDelete(name2); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime2 = Time[i-1]; if (i==0) { lastTime2 = tDummy; if (Time[index]==lastTime2) lastTime2 = Time[0]+Period()*60;}
                    ObjectCreate(name2,OBJ_RECTANGLE,WhatSeparatedWindow1,Time[index],0,lastTime2,1000);
                    ObjectSet(name2,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name2,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name2,OBJPROP_COLOR,ZoneColorUp);

                    string name3 = UniqueZoneID+":belowZero1"+Time[index+1]; ObjectDelete(name3); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime3 = Time[i-1]; if (i==0) { lastTime3 = tDummy; if (Time[index]==lastTime3) lastTime3 = Time[0]+Period()*60;}
                    ObjectCreate(name3,OBJ_RECTANGLE,WhatSeparatedWindow1,Time[index],0,lastTime3,-1000);
                    ObjectSet(name3,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name3,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name3,OBJPROP_COLOR,ZoneColorUp);
                  }
               if (ShowZones_InTheSeparatedWindow2)
                  {
                    string name4 = UniqueZoneID+":aboveZero2"+Time[index+1]; ObjectDelete(name4); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime4 = Time[i-1]; if (i==0) { lastTime4 = tDummy; if (Time[index]==lastTime4) lastTime4 = Time[0]+Period()*60;}
                    ObjectCreate(name4,OBJ_RECTANGLE,WhatSeparatedWindow2,Time[index],0,lastTime4,1000);
                    ObjectSet(name4,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name4,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name4,OBJPROP_COLOR,ZoneColorUp);

                    string name5 = UniqueZoneID+":belowZero2"+Time[index+1]; ObjectDelete(name5); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime5 = Time[i-1]; if (i==0) { lastTime5 = tDummy; if (Time[index]==lastTime5) lastTime5 = Time[0]+Period()*60;}
                    ObjectCreate(name5,OBJ_RECTANGLE,WhatSeparatedWindow2,Time[index],0,lastTime5,-1000);
                    ObjectSet(name5,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name5,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name5,OBJPROP_COLOR,ZoneColorUp);
                  }
//Forex-Station Zone template copy and paste end 6
   }
return(0);
}
//+------------------------------------------------------------------------------------------------------------------+
#define _maInstances 3
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int r, int instanceNo=0)
{
   int bars = Bars; r = bars-r-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)length,r,bars,instanceNo));
      case ma_ema   : return(iEma(price,length,r,bars,instanceNo));
      case ma_smma  : return(iSmma(price,(int)length,r,bars,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)length,r,bars,instanceNo));
      case ma_tema  : return(iTema(price,(int)length,r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx2];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars); instanceNo *= 2; int k;

   workSma[r][instanceNo+0] = price;
   workSma[r][instanceNo+1] = price; for(k=1; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo+0];  
   workSma[r][instanceNo+1] /= 1.0*k;
   return(workSma[r][instanceNo+1]);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);

   workEma[r][instanceNo] = price;
   if (r>0 && period>1)
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+(2.0/(1.0+period))*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);

   workSmma[r][instanceNo] = price;
   if (r>1 && period>1)
          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 _bars, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
   
   workLwma[r][instanceNo] = price; if (period<=1) return(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);
}

//
//
//
//
//

double workTema[][_maWorkBufferx3];
#define _tema1 0
#define _tema2 1
#define _tema3 2

double iTema(double price, double period, int r, int bars, int instanceNo=0)
{
   if (period<=1) return(price);
   if (ArrayRange(workTema,0)!= bars) ArrayResize(workTema,bars); instanceNo*=3;

   //
   //
   //
   //
   //
      
   workTema[r][_tema1+instanceNo] = price;
   workTema[r][_tema2+instanceNo] = price;
   workTema[r][_tema3+instanceNo] = price;
   double alpha = 2.0 / (1.0+period);
   if (r>0)
   {
          workTema[r][_tema1+instanceNo] = workTema[r-1][_tema1+instanceNo]+alpha*(price                         -workTema[r-1][_tema1+instanceNo]);
          workTema[r][_tema2+instanceNo] = workTema[r-1][_tema2+instanceNo]+alpha*(workTema[r][_tema1+instanceNo]-workTema[r-1][_tema2+instanceNo]);
          workTema[r][_tema3+instanceNo] = workTema[r-1][_tema3+instanceNo]+alpha*(workTema[r][_tema2+instanceNo]-workTema[r-1][_tema3+instanceNo]); }
   return(workTema[r][_tema3+instanceNo]+3.0*(workTema[r][_tema1+instanceNo]-workTema[r][_tema2+instanceNo]));
}
//+------------------------------------------------------------------------------------------------------------------+
#define priceInstances 1
double workHa[][priceInstances*4];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=4;
         int r = Bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen;
         if (r>0)
                haOpen  = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
         else   haOpen  = (open[i]+close[i])/2;
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(haOpen,haClose));

         if(haOpen  <haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else                 { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                                workHa[r][instanceNo+2] = haOpen;
                                workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (tprice)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hamedianb:   return((haOpen+haClose)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}   
//+------------------------------------------------------------------------------------------------------------------+
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("");
}
//+------------------------------------------------------------------------------------------------------------------+
