//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
//v1.3 Added text on corner of chart to indicate trend direction
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 14


#property strict

//
//
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
};


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
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) 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_slwma,   // Smoothed LWMA
   ma_dsema,   // Double Smoothed Exponential average
   ma_tema,    // Triple exponential moving average - TEMA
   ma_lsma     // Linear regression value (lsma)
};
//
//

extern enTimeFrames   TimeFrame   = tf_cu;  // Time frame

input int                MAPeriod1       = 50;               // Fast ma period
input enMaTypes          MAType1          = ma_ema;           // Ma Fast type
extern enPrices          MAPrice1         = pr_close;         // Ma Fast price to use
extern int               ShadowWidth1   =   3;                 // Shadow fast line width
extern int               LineWidth1     =   1;                // fast lines   width
extern color             Upcolor1       = clrMediumSeaGreen; // Bullish fast line  color
extern color             Dncolor1       = clrCrimson;       // Bearish fast line  color
extern color             Shcolor1       = clrGray;         // Shadow fast color

input int                MAPeriod2       = 200;               // Slow ma period

input enMaTypes          MAType2          = ma_ema;           // Slow Ma type
extern enPrices          MAPrice2         = pr_close;         // Slow Ma price to use

extern int               ShadowWidth2   =   3;                 // Shadow Slow line width
extern int               LineWidth2     =   1;                // Slow Lines width
extern color             Upcolor2       = clrMediumSeaGreen; // Bullish Slow line  color
extern color             Dncolor2       = clrCrimson;       // Bearish Slow line  color
extern color             Shcolor2       = clrGray;         // Shadow Slow line color

extern bool              ShowCandles = true;            // Candles are visible?
extern bool              ShowLines = true;            // Lines are visible?
extern bool              ShowArrows = true;            // Arrows are visible?


input int             WickWidth        = 1;                 // Candle wick width
input int             BodyWidth        = 2;                 // If auto width = false then use this
input bool            UseAutoWidth     = true;              // Auto adjust candle body width
extern color             Upcolor       = clrMediumSeaGreen; // Bullish candles  color
extern color             Dncolor       = clrCrimson;       // Bearish candles  color

input bool            alertsOn             = false;              // Alerts?
input bool            alertsOnCurrent      = false;             // Alerts open bar?
input bool            alertsMessage        = true;              // Alerts message?
input bool            alertsSound          = true;              // Alerts sound?
input bool            alertsNotify         = false;             // Alerts notification?
input bool            alertsEmail          = false;             // Alerts email?

input bool             ArrowOnFirst    = true;             // Arrow on first bars true/false
input int              UpArrowSize     = 2;                // Up Arrow size
input int              DnArrowSize     = 2;                // Down Arrow size
input int              UpArrowCode     = 159;              // Up Arrow code
input int              DnArrowCode     = 159;              // Down arrow code
input double           UpArrowGap      = 0.5;              // Up Arrow gap        
input double           DnArrowGap      = 0.5;              // Dn Arrow gap
input color            UpArrowColor    = clrLimeGreen;     // Up Arrow Color
input color            DnArrowColor    = clrOrange;        // Down Arrow Color

input ENUM_BASE_CORNER TextCorner = CORNER_RIGHT_UPPER;
input int TextX = 50;
input int TextY = 10;
input string UpText="Long";
input string DnText="Short";


input bool               Interpolate = true;            // Interpolate in multi time frame mode on/off?


extern string             button_note1          = "------------------------------";
extern int                btn_Subwindow = 0;
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER;
extern string             btn_text              = "2X MA";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 10;
extern color              btn_text_ON_color     = clrLime;
extern color              btn_text_OFF_color    = clrRed;
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 850;
extern int                button_y              = 40;
extern int                btn_Width             = 70;
extern int                btn_Height            = 20;
extern string             button_note2          = "------------------------------";
bool show_data = true;
bool recalc    = true;

string IndicatorName, IndicatorObjPrefix,buttonId;

double UpH[],UpH_bot[],DnH[],DnH_bot[];
int candlewidth=0;


double ma1[],ma1Ua[],ma1Ub[],ma2[],ma2Ua[],ma2Ub[],slope1[],shadow1[],upa[],dna[],shadow2[],slope2[],trend[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,MAPeriod1,MAType1,MAPrice1,ShadowWidth1,LineWidth1,Upcolor1,Dncolor1,Shcolor1,MAPeriod2,MAType2,MAPrice2,ShadowWidth2,LineWidth2,Upcolor2,Dncolor2,Shcolor2,ShowCandles,ShowLines,ShowArrows,WickWidth,BodyWidth,UseAutoWidth,Upcolor,Dncolor,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,ArrowOnFirst,UpArrowSize,DnArrowSize,UpArrowCode,DnArrowCode,UpArrowGap,DnArrowGap,UpArrowColor,DnArrowColor,Interpolate,button_note1,btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,button_note2,_buff,_ind)

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
string GenerateIndicatorName(const string target) 
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//
//
//

int OnInit()
{

IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(IndicatorName);
   IndicatorDigits(Digits);
   
   double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
      show_data = val != 0;
 
  if (UseAutoWidth)
   {
      int scale = int(ChartGetInteger(0,CHART_SCALE));
      switch(scale) 
	   {
	      case 0: candlewidth =  1; break;
	      case 1: candlewidth =  1; break;
		   case 2: candlewidth =  2; break;
		   case 3: candlewidth =  3; break;
		   case 4: candlewidth =  6; break;
		   case 5: candlewidth = 14; break;
	   }
	}
	else { candlewidth = BodyWidth; }
	
	     
   IndicatorBuffers(18);
     if (ShowCandles)
   { 
    SetIndexBuffer(0, UpH);    SetIndexStyle(0,DRAW_HISTOGRAM, 0, WickWidth, Upcolor);
    SetIndexBuffer(1, DnH);    SetIndexStyle(1,DRAW_HISTOGRAM, 0, WickWidth, Dncolor);
    SetIndexBuffer(2,UpH_bot); SetIndexStyle(2,DRAW_HISTOGRAM, 0, candlewidth, Upcolor);
    SetIndexBuffer(3,DnH_bot); SetIndexStyle(3,DRAW_HISTOGRAM, 0, candlewidth, Dncolor);
   }
                    else
   {
   SetIndexBuffer(0, UpH);    SetIndexStyle(0,DRAW_NONE);
   SetIndexBuffer(1, DnH);    SetIndexStyle(1,DRAW_NONE);
   SetIndexBuffer(2,UpH_bot);    SetIndexStyle(2,DRAW_NONE);
   SetIndexBuffer(3,DnH_bot);    SetIndexStyle(3,DRAW_NONE);
   } 
    if (ShowLines)
   { 
   SetIndexBuffer(4,shadow1);       SetIndexStyle(4,DRAW_LINE,EMPTY,ShadowWidth1,Shcolor1);
   SetIndexBuffer(5,ma1);           SetIndexStyle(5,DRAW_LINE,EMPTY,LineWidth1,Upcolor1);
   SetIndexBuffer(6,ma1Ua);         SetIndexStyle(6,DRAW_LINE,EMPTY,LineWidth1,Dncolor1);
   SetIndexBuffer(7,ma1Ub);         SetIndexStyle(7,DRAW_LINE,EMPTY,LineWidth1,Dncolor1);
   
   SetIndexBuffer(8,shadow2);       SetIndexStyle(8,DRAW_LINE,EMPTY,ShadowWidth2,Shcolor2);
   SetIndexBuffer(9,ma2);           SetIndexStyle(9,DRAW_LINE,EMPTY,LineWidth2,Upcolor2);
   SetIndexBuffer(10,ma2Ua);        SetIndexStyle(10,DRAW_LINE,EMPTY,LineWidth2,Dncolor2);
   SetIndexBuffer(11,ma2Ub);        SetIndexStyle(11,DRAW_LINE,EMPTY,LineWidth2,Dncolor2);
   }
                    else
   {
   SetIndexBuffer(4,shadow1);       SetIndexStyle(4,DRAW_NONE);
   SetIndexBuffer(5,ma1);           SetIndexStyle(5,DRAW_NONE);
   SetIndexBuffer(6,ma1Ua);         SetIndexStyle(6,DRAW_NONE);
   SetIndexBuffer(7,ma1Ub);         SetIndexStyle(7,DRAW_NONE);
   
   SetIndexBuffer(8,shadow2);       SetIndexStyle(8,DRAW_NONE);
   SetIndexBuffer(9,ma2);           SetIndexStyle(9,DRAW_NONE);
   SetIndexBuffer(10,ma2Ua);        SetIndexStyle(10,DRAW_NONE);
   SetIndexBuffer(11,ma2Ub);        SetIndexStyle(11,DRAW_NONE);
   
   }
   
                    if (ShowArrows)
   { 
    SetIndexBuffer(12, upa);   SetIndexStyle(12,DRAW_ARROW,EMPTY,UpArrowSize,UpArrowColor); SetIndexArrow(12,UpArrowCode);
    SetIndexBuffer(13, dna);   SetIndexStyle(13,DRAW_ARROW,EMPTY,DnArrowSize,DnArrowColor); SetIndexArrow(13,DnArrowCode);
   }
                    else
   { 
    SetIndexBuffer(12, upa);   SetIndexStyle(12,DRAW_NONE); SetIndexArrow(12,108);
    SetIndexBuffer(13, dna);   SetIndexStyle(13,DRAW_NONE); SetIndexArrow(14,108);
   }  
   
   
   SetIndexBuffer(14,slope1);
   SetIndexBuffer(15,slope2);
   
   SetIndexBuffer(16,trend);
   
   SetIndexBuffer(17,count);
   
   indicatorFileName = WindowExpertName();
    TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
   
   IndicatorSetString(INDICATOR_SHORTNAME,timeFrameToString(TimeFrame)+"  ("+(string)MAPeriod1+")");
   
   //
    ChartSetInteger(0, 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(0, buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE, button_x);
   
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){  
 ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);
 }

//
//
void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
  {
   ObjectDelete(0,buttonID);
      ObjectCreate (0,buttonID,OBJ_BUTTON,btn_Subwindow,0,0);
   ObjectSetInteger(0,buttonID,OBJPROP_COLOR,txtColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,bgColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BORDER_COLOR,borderColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BORDER_TYPE,BORDER_RAISED);
   ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,width);
   ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,height);
   ObjectSetString(0,buttonID,OBJPROP_FONT,font);
   ObjectSetString(0,buttonID,OBJPROP_TEXT,buttonText);
   ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,fontSize);
   ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);
   ObjectSetInteger(0,buttonID,OBJPROP_CORNER,btn_corner);
   ObjectSetInteger(0,buttonID,OBJPROP_HIDDEN,1);
   ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,9999);
   ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,9999);
  }
//+------------------------------------------------------------------+
void handleButtonClicks()
  {
   if(ObjectGetInteger(0, buttonId, OBJPROP_STATE))
     {
      ObjectSetInteger(0, 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();
   if(id==CHARTEVENT_OBJECT_CLICK && sparam==buttonId){

      if (ShowCandles)
   { 
     SetIndexStyle(0,DRAW_HISTOGRAM, 0, WickWidth, Upcolor);
     SetIndexStyle(1,DRAW_HISTOGRAM, 0, WickWidth, Dncolor);
     SetIndexStyle(2,DRAW_HISTOGRAM, 0, candlewidth, Upcolor);
     SetIndexStyle(3,DRAW_HISTOGRAM, 0, candlewidth, Dncolor);
   }
                    else
   {
     SetIndexStyle(0,DRAW_NONE);
     SetIndexStyle(1,DRAW_NONE);
     SetIndexStyle(2,DRAW_NONE);
     SetIndexStyle(3,DRAW_NONE);
   } 
   
     if (ShowLines)
   {  
     SetIndexStyle(4,DRAW_LINE);
     SetIndexStyle(5,DRAW_LINE);
     SetIndexStyle(6,DRAW_LINE);
     SetIndexStyle(7,DRAW_LINE);
     SetIndexStyle(8,DRAW_LINE);
     SetIndexStyle(9,DRAW_LINE);
     SetIndexStyle(10,DRAW_LINE);
     SetIndexStyle(11,DRAW_LINE);
   }
                    else
   {
     SetIndexStyle(4,DRAW_NONE);
     SetIndexStyle(5,DRAW_NONE);
     SetIndexStyle(6,DRAW_NONE);
     SetIndexStyle(7,DRAW_NONE);
     SetIndexStyle(8,DRAW_NONE);
     SetIndexStyle(9,DRAW_NONE);
     SetIndexStyle(10,DRAW_NONE);
     SetIndexStyle(11,DRAW_NONE);
   }
   
   if (ShowArrows)
   { 
         SetIndexStyle(12,DRAW_ARROW,EMPTY,UpArrowSize,UpArrowColor); SetIndexArrow(12,UpArrowCode);
       SetIndexStyle(13,DRAW_ARROW,EMPTY,DnArrowSize,DnArrowColor); SetIndexArrow(13,DnArrowCode);
   
   }
   else
   { 
       SetIndexStyle(12,DRAW_NONE); 
       SetIndexStyle(13,DRAW_NONE); 
   }    
   

   if(show_data)
     {
      handleButtonClicks();
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
      ObjectSetInteger(ChartID(),IndicatorObjPrefix+"MaText",OBJPROP_COLOR,clrYellow);  
        
     }
   else
     {
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
      ObjectSetInteger(ChartID(),IndicatorObjPrefix+"MaText",OBJPROP_COLOR,clrNONE);  
      SetIndexStyle(0,DRAW_NONE);
      SetIndexStyle(1,DRAW_NONE);
      SetIndexStyle(2,DRAW_NONE);
      SetIndexStyle(3,DRAW_NONE);
      SetIndexStyle(4,DRAW_NONE);
      SetIndexStyle(5,DRAW_NONE);
      SetIndexStyle(6,DRAW_NONE);
      SetIndexStyle(7,DRAW_NONE);
     SetIndexStyle(8,DRAW_NONE);
     SetIndexStyle(9,DRAW_NONE);
     SetIndexStyle(10,DRAW_NONE);
     SetIndexStyle(11,DRAW_NONE);
     SetIndexStyle(12,DRAW_NONE);
     SetIndexStyle(13,DRAW_NONE);
     }
   }
}
//

int OnCalculate (const int       rates_total,
                 const int       prev_calculated,
                 const datetime& time[],
                 const double&   open[],
                 const double&   high[],
                 const double&   low[],
                 const double&   close[],
                 const long&     tick_volume[],
                 const long&     volume[],
                 const int&      spread[])
{
   int i,limit=fmin(rates_total-prev_calculated+1,rates_total-1); count[0] = limit;
  if(ChartGetInteger(0,CHART_SCALE) != candlewidth) OnInit();
      if (TimeFrame!=_Period)
      {
         limit = (int)fmax(limit,fmin(rates_total-1,_mtfCall(17,0)*TimeFrame/_Period));
         if (slope1[limit]== -1) CleanPoint(limit,ma1Ua,ma1Ub);
         if (slope2[limit]==-1) CleanPoint(limit,ma2Ua,ma2Ub);
         for (i=limit;i>=0 && !_StopFlag; i--)
         {
            int y = iBarShift(NULL,TimeFrame,time[i]);
            int x = y;
                if (ArrowOnFirst)
                      {  if (i<Bars-1) x = iBarShift(NULL,TimeFrame,Time[i+1]);               }
                else  {  if (i>0)      x = iBarShift(NULL,TimeFrame,Time[i-1]); else x = -1;  }
                
               ma1[i]   = _mtfCall(5,y);
               shadow1[i] = ma1[i];
     
               ma2[i]   = _mtfCall(9,y);
               shadow2[i] = ma2[i];
                
               ma1Ua[i] = ma1Ub[i]  = EMPTY_VALUE;
               ma2Ua[i] = ma2Ub[i]  = EMPTY_VALUE;
               slope1[i] = _mtfCall(14,y);
               slope2[i] = _mtfCall(15,y);
               
               trend[i] = _mtfCall(16,y);
               
               UpH[i] = DnH[i]  = EMPTY_VALUE;
               UpH_bot[i] = DnH_bot[i]  = EMPTY_VALUE;
               
               upa[i] = dna[i]  = EMPTY_VALUE;
               
                if (x!=y)
                     {
                       upa[i] = _mtfCall(12,y);
                       dna[i] = _mtfCall(13,y);
                     }  
               //
               //
               //
                     
               if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,time[i-1]))) continue;
                  
               //
               //
               //
                  
               #define _interpolate(buff) buff[i+k] = buff[i]+(buff[i+n]-buff[i])*k/n
               int n,k; datetime dtime = iTime(NULL,TimeFrame,y);
                  for(n = 1; (i+n)<rates_total && time[i+n] >= dtime; n++) continue;	
                  for(k = 1; k<n && (i+n)<rates_total && (i+k)<rates_total; k++) 
                  {
                     _interpolate(ma1);
                     _interpolate(ma2); 
                     _interpolate(shadow1);
                     _interpolate(shadow2);
                       
                  }                    
         } 
         for(i=limit;i>=0; i--)
         {      
            if (slope1[i] == -1)  PlotPoint(i,ma1Ua,ma1Ub,ma1);
            if (slope2[i] == -1)  PlotPoint(i,ma2Ua,ma2Ub,ma2); 
            if (trend[i] ==  1) {   UpH[i] = High[i]; DnH[i] = Low[i];  UpH_bot[i] = fmax(Open[i],Close[i]); DnH_bot[i] = fmin(Open[i],Close[i]); }
            if (trend[i] == -1) {   UpH[i] =  Low[i]; DnH[i] = High[i]; UpH_bot[i] = fmin(Open[i],Close[i]); DnH_bot[i] = fmax(Open[i],Close[i]); } 
            
               
                  
               
         }
   return(rates_total);
   } 
   //
   //
   //
   
         if (slope1[limit]== -1) CleanPoint(limit,ma1Ua,ma1Ub);
         if (slope2[limit]== -1) CleanPoint(limit,ma2Ua,ma2Ub);
   for(i=limit;i>=0; i--)
   {  
      ma1[i]   = iCustomMa(MAType1,getPrice(MAPrice1,Open,Close,High,Low,i,Bars,0),   MAPeriod1,i,rates_total,0); 
      ma2[i]   = iCustomMa(MAType2,getPrice(MAPrice2,Open,Close,High,Low,i,Bars,1),   MAPeriod2,i,rates_total,1);  
      
      shadow1[i] = ma1[i];
      shadow2[i] = ma2[i];
       
   //+-   colored  ma based on slope
   //+-   slope1[i] = (i<rates_total-1) ? (ma1[i]>ma1[i+1]) ? 1 : (ma1[i]<ma1[i+1]) ? -1 :  slope1[i+1]  : 0;
   //+-   slope2[i] = (i<rates_total-1) ? (ma2[i]>ma2[i+1]) ? 1 : (ma2[i]<ma2[i+1]) ? -1 :  slope2[i+1]  : 0; 
   
   
   //+-   colored  ma based on ma cross   
      slope1[i] = (i<rates_total-1) ? (ma1[i]>ma2[i]) ? 1 : (ma1[i]<ma2[i]) ? -1 :  slope1[i+1]  : 0;
      slope2[i] = (i<rates_total-1) ? (ma2[i]<ma1[i]) ? 1 : (ma2[i]>ma1[i]) ? -1 :  slope2[i+1]  : 0; 
      
      trend[i] =  (i<Bars-1) ? (slope1[i]== 1 && slope2[i]== 1) ? 1 : (slope1[i]== -1 && slope2[i]== -1) ? -1 : trend[i+1]  : 0; 
      
            ma1Ua[i] = ma1Ub[i]  = EMPTY_VALUE;
            ma2Ua[i] = ma2Ub[i]  = EMPTY_VALUE;
            
            UpH[i] = DnH[i]  = EMPTY_VALUE;
            UpH_bot[i] = DnH_bot[i]  = EMPTY_VALUE;
            
      //      upa[i] = dna[i]  = EMPTY_VALUE;
      
            if (slope1[i] == -1)  PlotPoint(i,ma1Ua,ma1Ub,ma1);
            if (slope2[i] == -1)  PlotPoint(i,ma2Ua,ma2Ub,ma2); 
           
           if (trend[i] ==  1) {   UpH[i] = High[i]; DnH[i] = Low[i];  UpH_bot[i] = fmax(Open[i],Close[i]); DnH_bot[i] = fmin(Open[i],Close[i]); }
           if (trend[i] == -1) {   UpH[i] =  Low[i]; DnH[i] = High[i]; UpH_bot[i] = fmin(Open[i],Close[i]); DnH_bot[i] = fmax(Open[i],Close[i]); }
         if (i<Bars-1)
      {
         if (trend[i] ==  1) {
             SignalText(UpText);
             
             if(trend[i]!=trend[i+1])
                  upa[i] = fmin(ma2[i],Low[i] )-iATR(NULL,0,15,i)*UpArrowGap;  
         }
         if (trend[i] == -1){
            SignalText(DnText);
            
            if(trend[i]!=trend[i+1])
               dna[i] = fmax(ma2[i],High[i])+iATR(NULL,0,15,i)*DnArrowGap;
            
         }
      } 
            
            
   }
    
      int whichBar =(alertsOnCurrent) ? 0 : 1; 
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) {
            if (alertsOn)
               doAlert("  up  ");
               
            SignalText(UpText);
         }
         if (trend[whichBar] ==-1) {
            if (alertsOn)
               doAlert("  down  ");  
               
             SignalText(DnText);      
         }
   }         

return(rates_total);
}

void SignalText(string iText)
  {
      if(ObjectFind(0,IndicatorObjPrefix+"MaText")<0)
         ObjectCreate(0,IndicatorObjPrefix+"MaText",OBJ_LABEL,0,0,0);
         
      ObjectSetInteger(0,IndicatorObjPrefix+"MaText",OBJPROP_CORNER,TextCorner);
      ObjectSetInteger(0,IndicatorObjPrefix+"MaText",OBJPROP_XDISTANCE,TextX);
      ObjectSetInteger(0,IndicatorObjPrefix+"MaText",OBJPROP_YDISTANCE,TextY);
      
      ObjectSetString(0,IndicatorObjPrefix+"MaText",OBJPROP_TEXT, iText);
      
      if(iText==UpText && show_data)
         ObjectSetInteger(0,IndicatorObjPrefix+"MaText",OBJPROP_COLOR,Upcolor1);
      else if(iText==DnText && show_data)
         ObjectSetInteger(0,IndicatorObjPrefix+"MaText",OBJPROP_COLOR,Dncolor1);
      
  }   

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//



//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

#define _maInstances 2
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int r, int bars, int instanceNo=0)
{
   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_slwma : return(iSlwma(price,(int)length,r,bars,instanceNo));
      case ma_dsema : return(iDsema(price,length,r,bars,instanceNo));
      case ma_tema  : return(iTema(price,(int)length,r,bars,instanceNo));
      case ma_lsma  : return(iLinr(price,(int)length,r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx1];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars);

   workSma[r][instanceNo+0] = price;
   double avg = price; int k=1;  for(; k<period && (r-k)>=0; k++) avg += workSma[r-k][instanceNo+0];  
   return(avg/(double)k);
}

//
//
//
//
//

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 workSlwma[][_maWorkBufferx2];
double iSlwma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSlwma,0)!= _bars) ArrayResize(workSlwma,_bars); 

   //
   //
   //
   //
   //

      int SqrtPeriod = (int)MathFloor(MathSqrt(period)); instanceNo *= 2;
         workSlwma[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*workSlwma[r-k][instanceNo];  
         }             
         workSlwma[r][instanceNo+1] = (sum/sumw);

         //
         //
         //
         //
         //
         
         sumw = SqrtPeriod;
         sum  = SqrtPeriod*workSlwma[r][instanceNo+1];
            for(int k=1; k<SqrtPeriod && (r-k)>=0; k++)
            {
               double weight = SqrtPeriod-k;
                      sumw += weight;
                      sum  += weight*workSlwma[r-k][instanceNo+1];  
            }
   return(sum/sumw);
}

//
//
//
//
//

double workDsema[][_maWorkBufferx2];
#define _ema1 0
#define _ema2 1

double iDsema(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workDsema,0)!= _bars) ArrayResize(workDsema,_bars); instanceNo*=2;

   //
   //
   //
   //
   //
   
   workDsema[r][_ema1+instanceNo] = price;
   workDsema[r][_ema2+instanceNo] = price;
   if (r>0 && period>1)
   {
      double alpha = 2.0 /(1.0+MathSqrt(period));
          workDsema[r][_ema1+instanceNo] = workDsema[r-1][_ema1+instanceNo]+alpha*(price                         -workDsema[r-1][_ema1+instanceNo]);
          workDsema[r][_ema2+instanceNo] = workDsema[r-1][_ema2+instanceNo]+alpha*(workDsema[r][_ema1+instanceNo]-workDsema[r-1][_ema2+instanceNo]); }
   return(workDsema[r][_ema2+instanceNo]);
}

//
//
//
//
//

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 (ArrayRange(workTema,0)!= bars) ArrayResize(workTema,bars); instanceNo*=3;

   //
   //
   //
   //
   //
      
   workTema[r][_tema1+instanceNo] = price;
   workTema[r][_tema2+instanceNo] = price;
   workTema[r][_tema3+instanceNo] = price;
   if (r>0 && period>1)
   {
      double alpha = 2.0 / (1.0+period);
          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]));
}

//
//
//
//
//

double workLinr[][_maWorkBufferx1];
double iLinr(double price, int period, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(workLinr,0)!= bars) ArrayResize(workLinr,bars);

   //
   //
   //
   //
   //
   
      period = MathMax(period,1);
      workLinr[r][instanceNo] = price;
      if (r<period) return(price);
         double lwmw = period; double lwma = lwmw*price;
         double sma  = price;
         for(int k=1; k<period && (r-k)>=0; k++)
         {
            double weight = period-k;
                   lwmw  += weight;
                   lwma  += weight*workLinr[r-k][instanceNo];  
                   sma   +=        workLinr[r-k][instanceNo];
         }             
   
   return(3.0*lwma/lwmw-2.0*sma/period);
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

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("");
}
 
  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)]);
}


#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     2
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= bars) ArrayResize(workHa,bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*fabs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(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:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               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);
}

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 = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" 2xMA "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" 2xMA ",message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}
