//+------------------------------------------------------------------+
//|                       TriangularMA centered asymmetric bands.mq4 |
//|                                                           mladen |
//| arrows coded acording to idea presented by umesh                 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_chart_window
#property indicator_buffers 5


#property indicator_color1  clrDodgerBlue
#property indicator_color2  clrOrangeRed
#property indicator_color3  clrLimeGreen
#property indicator_color4  clrNONE
#property indicator_color5  clrNONE

#property indicator_style1  STYLE_DOT
#property indicator_style2  STYLE_DOT
#property indicator_style3  STYLE_DOT


//
//
//
//
//

extern string TimeFrame       = "0";
extern int    HalfLength      = 50;
extern ENUM_APPLIED_PRICE    Price           = PRICE_WEIGHTED;
extern double BandsDeviations = 2.618;
extern double koeff           = 0.0001;
extern bool   Interpolate     = true;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = false;
extern bool   alertsOnHighLow = false;
extern bool   alertsMessage   = false;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
//------
//Forex-Station button template start41; copy and paste
input string               ButtonID                         = "Current";          // Button ID for multiple instances 
input int                  ButtonSubWindow                  = 0;                  // Button Window
input int                  ButtonWidth                      = 99;                 // Button Width
input int                  ButtonHight                      = 36;                 // Button Hight
input int                  ButtonFontSize                   = 11;                 // Button Font Size
input color                ButtonOff_Bg_Color               = clrDarkSlateGray;   // OFF Background Color
input color                ButtonOff_Brdr_Color             = clrChocolate;       // OFF Border Color
input color                ButtonOn_Bg_Color                = clrLimeGreen;       // ON Background Color
input color                ButtonOn_Brdr_Color              = clrChocolate;       // ON Border Color
input color                ButtonOff_Txt_Color              = clrSnow;            // OFF Text Color
input color                ButtonOn_Txt_Color               = clrSnow;            // ON Text Color
input string               ButtonOff_Txt                    = "TMA OFF";          // OFF Text
input string               ButtonOn_Txt                     = "TMA ON";           // ON Text
input ENUM_BASE_CORNER     ButtonCorner                     = 3;                  // Button Corner
input int                  ButtonX                          = 198;                // Button X Distance
input int                  ButtonY                          = 135;                // Button Y Distance

string ONOFButtName="TMA_Button_"+ButtonID;
//Forex-Station button template end41; copy and paste

//
//
//
//
//

double tmBuffer[];
double upBuffer[];
double dnBuffer[];
double wuBuffer[];
double wdBuffer[];
double upArrow[];
double dnArrow[];

//
//
//
//
//

string IndicatorFileName;
bool   calculatingTma = false;
bool   returningBars  = false;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int init()
{
//Forex-Station button template start42; copy and paste
   EventSetMillisecondTimer(36); 
//Forex-Station button template end42; copy and paste
   
   timeFrame  = stringToTimeFrame(TimeFrame);
   HalfLength = MathMax(HalfLength,1);
   IndicatorBuffers(7);
         SetIndexBuffer(0,tmBuffer);  SetIndexDrawBegin(0,HalfLength); SetIndexStyle(0,DRAW_LINE); 
         SetIndexBuffer(1,upBuffer);  SetIndexDrawBegin(1,HalfLength); SetIndexStyle(1,DRAW_LINE);
         SetIndexBuffer(2,dnBuffer);  SetIndexDrawBegin(2,HalfLength); SetIndexStyle(2,DRAW_LINE);
         SetIndexBuffer(3,dnArrow);   SetIndexStyle(3,DRAW_ARROW); SetIndexArrow(3,233);
         SetIndexBuffer(4,upArrow);   SetIndexStyle(4,DRAW_ARROW); SetIndexArrow(4,234);
         SetIndexBuffer(5,wuBuffer);
         SetIndexBuffer(6,wdBuffer);

         if (TimeFrame=="calculateTma")  { calculatingTma=true; return(0); }
         if (TimeFrame=="returnBars")    { returningBars=true;  return(0); }

   
   IndicatorFileName = WindowExpertName();
   return(0);
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-1,Bars-counted_bars+HalfLength);

           if (returningBars)  { tmBuffer[0] = limit; return(0); }
           if (calculatingTma) { calculateTma(limit); return(0); }
           if (timeFrame > Period()) limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,IndicatorFileName,"returnBars",0,0)*timeFrame/Period()));

   //
   //
   //
   //
   //
   
 	for(i = limit; i >= 0; i--)
   {
      int      shift1 = iBarShift(NULL,timeFrame,Time[i]);
      datetime time1  = iTime    (NULL,timeFrame,shift1);

      //
      //
      //
      //
      //

         tmBuffer[i] = iCustom(NULL,timeFrame,IndicatorFileName,"calculateTma",HalfLength,Price,BandsDeviations,0,shift1);
         upBuffer[i] = iCustom(NULL,timeFrame,IndicatorFileName,"calculateTma",HalfLength,Price,BandsDeviations,1,shift1);
         dnBuffer[i] = iCustom(NULL,timeFrame,IndicatorFileName,"calculateTma",HalfLength,Price,BandsDeviations,2,shift1);

         upArrow[i] = EMPTY_VALUE;
         dnArrow[i] = EMPTY_VALUE;            
            if (High[i+1]>upBuffer[i+1] && Close[i+1]>Open[i+1] && Close[i]<Open[i]) upArrow[i] = High[i]+iATR(NULL,0,20,i)+koeff;
            if ( Low[i+1]<dnBuffer[i+1] && Close[i+1]<Open[i+1] && Close[i]>Open[i]) dnArrow[i] = Low[i]-iATR(NULL,0,20,i)-koeff;

         if (timeFrame <= Period() || shift1==iBarShift(NULL,timeFrame,Time[i-1])) continue;
         if (!Interpolate) continue;

      //
      //
      //
      //
      //

         for(int n = 1; i+n < Bars && Time[i+n] >= time1; n++) continue;
         double factor = 1.0 / n;
         for(int k = 1; k < n; k++)
            {
               tmBuffer[i+k] = k*factor*tmBuffer[i+n] + (1.0-k*factor)*tmBuffer[i];
               upBuffer[i+k] = k*factor*upBuffer[i+n] + (1.0-k*factor)*upBuffer[i];
               dnBuffer[i+k] = k*factor*dnBuffer[i+n] + (1.0-k*factor)*dnBuffer[i];
            }               
   }

   //
   //
   //
   //
   //
   
   if (alertsOn)
   {
      if (alertsOnCurrent)
            int forBar = 0;
      else      forBar = 1;
      if (alertsOnHighLow)       
      {
         if (High[forBar] > upBuffer[forBar] && High[forBar+1] < upBuffer[forBar+1]) doAlert("high penetrated upper bar");
         if (Low[forBar]  < dnBuffer[forBar] && Low[forBar+1]  > dnBuffer[forBar+1]) doAlert("low penetrated lower bar");
      }
      else
      {
         if (Close[forBar] > upBuffer[forBar] && Close[forBar+1] < upBuffer[forBar+1]) doAlert("close penetrated upper bar");
         if (Close[forBar] < dnBuffer[forBar] && Close[forBar+1] > dnBuffer[forBar+1]) doAlert("close penetrated lower bar");
      }
   } 

   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void calculateTma(int limit)
{
   int i,j,k;
   double FullLength = 2.0*HalfLength+1.0;
   
   //
   //
   //
   //
   //
   
   for (i=limit; i>=0; i--)
   {
      double sum  = (HalfLength+1)*iMA(NULL,0,1,0,MODE_SMA,Price,i);
      double sumw = (HalfLength+1);
      for(j=1, k=HalfLength; j<=HalfLength; j++, k--)
      {
         sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i+j);
         sumw += k;

         if (j<=i)
         {
            sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i-j);
            sumw += k;
         }
      }
      tmBuffer[i] = sum/sumw;

      //
      //
      //
      //
      //
            
         double diff = iMA(NULL,0,1,0,MODE_SMA,Price,i)-tmBuffer[i];
         if (i> (Bars-HalfLength-1)) continue;
         if (i==(Bars-HalfLength-1))
         {
            upBuffer[i] = tmBuffer[i];
            dnBuffer[i] = tmBuffer[i];
            if (diff>=0)
               {
                  wuBuffer[i] = MathPow(diff,2);
                  wdBuffer[i] = 0;
               }
            else
               {               
                  wdBuffer[i] = MathPow(diff,2);
                  wuBuffer[i] = 0;
               }                  
            continue;
         }
      
         //
         //
         //
         //
         //
         
         if(diff>=0)
            {
               wuBuffer[i] = (wuBuffer[i+1]*(FullLength-1)+MathPow(diff,2))/FullLength;
               wdBuffer[i] =  wdBuffer[i+1]*(FullLength-1)/FullLength;
            }
         else
            {
               wdBuffer[i] = (wdBuffer[i+1]*(FullLength-1)+MathPow(diff,2))/FullLength;
               wuBuffer[i] =  wuBuffer[i+1]*(FullLength-1)/FullLength;
            }
         upBuffer[i] = tmBuffer[i] + BandsDeviations*MathSqrt(wuBuffer[i]);
         dnBuffer[i] = tmBuffer[i] - BandsDeviations*MathSqrt(wdBuffer[i]);
   }
}
    


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="";
   static datetime previousTime;
   string message;

   //
   //
   //
   //
   //
   
   if (previousAlert!=doWhat || previousTime!=Time[0]) 
   {
      previousAlert = doWhat;
      previousTime  = Time[0];

      message= StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," THA : ",doWhat);
         if (alertsMessage) Alert(message);
         if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"TMA "),message);
         if (alertsSound)   PlaySound("alert2.wav");
    }
}

//
//
//
//
//

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------

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) {
   StringToUpper(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("");
}


//end
//+------------------------------------------------------------------+
//Forex-Station button template start43; copy and paste
void CreateButton(string name)
 {
                   if(ObjectFind(0,name)<0)
                   ObjectCreate(0,name,OBJ_BUTTON,ButtonSubWindow,0,0); 
                   ObjectSetInteger(0,name,OBJPROP_XSIZE,ButtonWidth);
                   ObjectSetInteger(0,name,OBJPROP_YSIZE,ButtonHight);
                   ObjectSetString(0,name,OBJPROP_TEXT,ButtonOff_Txt);
                   ObjectSetString(0,name,OBJPROP_FONT,"Tahoma");
                   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,ButtonFontSize);
                   ObjectSetInteger(0,name,OBJPROP_COLOR,ButtonOff_Txt_Color);
                   ObjectSetInteger(0,name,OBJPROP_BGCOLOR,ButtonOff_Bg_Color);
                   ObjectSetInteger(0,name,OBJPROP_BORDER_COLOR,ButtonOff_Brdr_Color);
                   ObjectSetInteger(0,name,OBJPROP_BACK,false);
                   ObjectSetInteger(0,name,OBJPROP_STATE,false);
                   ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
                   ObjectSetInteger(0,name,OBJPROP_SELECTED,false);
                   ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
                   ObjectSetInteger(0,name,OBJPROP_ZORDER,100);
                   ObjectSetInteger(0,name,OBJPROP_CORNER,ButtonCorner);
                   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,ButtonX);
                   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,ButtonY);
 }
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
 {
//---
   if(id==CHARTEVENT_OBJECT_CLICK)
     { 
     if(sparam==ONOFButtName&&ObjectGetString(0,ONOFButtName,OBJPROP_TEXT)==ButtonOff_Txt) 
      {
         SetIndexStyle(0,DRAW_LINE);
         SetIndexStyle(1,DRAW_LINE);
         SetIndexStyle(2,DRAW_LINE);
         SetIndexStyle(3,DRAW_ARROW);
         SetIndexStyle(4,DRAW_ARROW);
      ObjectSetString(0,sparam,OBJPROP_TEXT,ButtonOn_Txt);
      ObjectSetInteger(0,sparam,OBJPROP_FONTSIZE,ButtonFontSize);
      ObjectSetInteger(0,sparam,OBJPROP_COLOR,ButtonOn_Txt_Color);
      ObjectSetInteger(0,sparam,OBJPROP_BGCOLOR,ButtonOn_Bg_Color);
      ObjectSetInteger(0,sparam,OBJPROP_BORDER_COLOR,ButtonOn_Brdr_Color);
      ObjectSetInteger(0,sparam,OBJPROP_STATE,true);
      }
     else
     if(sparam==ONOFButtName&&ObjectGetString(0,ONOFButtName,OBJPROP_TEXT)==ButtonOn_Txt)
      {    
         SetIndexStyle(0,DRAW_NONE);
         SetIndexStyle(1,DRAW_NONE);
         SetIndexStyle(2,DRAW_NONE);
         SetIndexStyle(3,DRAW_NONE);
         SetIndexStyle(4,DRAW_NONE);
      ObjectSetString(0,sparam,OBJPROP_TEXT,ButtonOff_Txt); 
      ObjectSetInteger(0,sparam,OBJPROP_FONTSIZE,ButtonFontSize);
      ObjectSetInteger(0,sparam,OBJPROP_COLOR,ButtonOff_Txt_Color);
      ObjectSetInteger(0,sparam,OBJPROP_BGCOLOR,ButtonOff_Bg_Color);
      ObjectSetInteger(0,sparam,OBJPROP_BORDER_COLOR,ButtonOff_Brdr_Color);
      ObjectSetInteger(0,sparam,OBJPROP_STATE,false);
      }
     }

 }
//+------------------------------------------------------------------+
int deinit()  
 { 
   EventKillTimer();
   objectsDelete(ONOFButtName);  
   return(0); 
 }
//+------------------------------------------------------------------+
void OnTimer()
 {
                   if(ObjectFind(0,ONOFButtName)<0)
                   CreateButton(ONOFButtName);
                   ObjectSetInteger(0,ONOFButtName,OBJPROP_CORNER,ButtonCorner);
                   ObjectSetInteger(0,ONOFButtName,OBJPROP_XDISTANCE,ButtonX);
                   ObjectSetInteger(0,ONOFButtName,OBJPROP_YDISTANCE,ButtonY); 
                   
        if(ObjectGetString(0,ONOFButtName,OBJPROP_TEXT)==ButtonOff_Txt)
         {
         SetIndexStyle(0,DRAW_NONE);
         SetIndexStyle(1,DRAW_NONE);
         SetIndexStyle(2,DRAW_NONE);
         SetIndexStyle(3,DRAW_NONE);
         SetIndexStyle(4,DRAW_NONE);
         }
        if(ObjectGetString(0,ONOFButtName,OBJPROP_TEXT)==ButtonOn_Txt)
         {
         SetIndexStyle(0,DRAW_LINE);
         SetIndexStyle(1,DRAW_LINE);
         SetIndexStyle(2,DRAW_LINE);
         SetIndexStyle(3,DRAW_ARROW);
         SetIndexStyle(4,DRAW_ARROW);
         }
 }
//+------------------------------------------------------------------+
void objectsDelete(string name)
{
   int objTotal = ObjectsTotal();
   for(int i=objTotal-1; i>=0; i--)  
  {
      string objName = ObjectName(i);
      if(StringFind(objName,name,0) == 0)
       ObjectDelete(0,objName);
   }
}
//+------------------------------------------------------------------+
//Forex-Station button template end43; copy and paste
