//+------------------------------------------------------------------+
//|                                  TriangularMA centered bands.mq4 |
//|                                                           mladen |
//| forex-tsd elite section only                                     |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_chart_window
#property indicator_buffers    8
#property indicator_color1     CLR_NONE
#property indicator_color2     White
#property indicator_color3     White
#property indicator_color4     Lime 
#property indicator_color5     Red
#property indicator_color6     White
#property indicator_color7     Red
#property indicator_color8     Lime
#property indicator_style2     STYLE_DOT
#property indicator_style3     STYLE_DOT
#property  indicator_width1 1
#property  indicator_width2 1
#property  indicator_width3 1
#property  indicator_width4 2
#property  indicator_width5 2
#property  indicator_width6 2

//
//
//
//
//

extern string TimeFrame       = "current time frame";
extern int    HalfLength      = 56;
extern int    Price           = PRICE_CLOSE;
extern double ATRMultiplier   = 2.0;
extern int    ATRPeriod       = 100;
extern bool   Interpolate     = true;
extern double TrendThreshold = 0.5;
extern bool Normalize = false;
extern bool ShowDivergenceArrows = false;

extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = false;
extern bool   alertsOnHighLow = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;


//
//
//
//
//

double buffer1[];
double buffer2[];
double buffer3[];
double bull[];
double bear[];
double neutral[];
double trend[];
double peak[];
double trough[];

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

double TICK;
bool AdditionalDigit;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int init()
{
   AdditionalDigit = MarketInfo(Symbol(), MODE_MARGINCALCMODE) == 0 && MarketInfo(Symbol(), MODE_PROFITCALCMODE) == 0 && Digits % 2 == 1;
   
    TICK = MarketInfo(Symbol(), MODE_TICKSIZE);
    if (AdditionalDigit) {
        TICK *= 10;
    }     
    
   IndicatorBuffers(8);
   HalfLength=MathMax(HalfLength,1);
      SetIndexBuffer(0,buffer1); SetIndexDrawBegin(0,HalfLength);
      SetIndexBuffer(1,buffer2); SetIndexDrawBegin(1,HalfLength);
      SetIndexBuffer(2,buffer3); SetIndexDrawBegin(2,HalfLength);
      SetIndexBuffer(3,bull); SetIndexDrawBegin(3,HalfLength);
      SetIndexBuffer(4,bear); SetIndexDrawBegin(4,HalfLength);
      SetIndexBuffer(5,neutral); SetIndexDrawBegin(5,HalfLength);
      SetIndexBuffer(6,peak); SetIndexDrawBegin(6,HalfLength);
      SetIndexBuffer(7,trough); SetIndexDrawBegin(7,HalfLength);
      if (ShowDivergenceArrows)
      {
         SetIndexStyle( 6, DRAW_ARROW ); SetIndexArrow(6,234);
         SetIndexStyle( 7, DRAW_ARROW ); SetIndexArrow(7,233);  
      }
      else
      {
         SetIndexStyle( 6, DRAW_NONE,0,0,CLR_NONE );
         SetIndexStyle( 7, DRAW_NONE,0,0,CLR_NONE );
      }
      //SetIndexBuffer(6,trend);

      //
      //
      //
      //
      //
   
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame=="returnBars";     if (returnBars)     return(0);
      calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
      
   IndicatorShortName(timeFrameToString(timeFrame)+" TMA bands )"+HalfLength+")");
   return(0);
}
int deinit() { return(0); }




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,j,k,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-1,Bars-counted_bars+HalfLength);
            if (returnBars)  { buffer1[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
      for (i=225; i>=0; i--)//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;
            }
         }

         //
         //
         //
         //
         //
      
         double range = iATR(NULL,0,ATRPeriod,i+10)*ATRMultiplier;
         if(range == 0) continue;
         
         buffer1[i] = sum/sumw;
         buffer2[i] = buffer1[i]+range;
         buffer3[i] = buffer1[i]-range;

         bull[i] = EMPTY_VALUE;
         bear[i] = EMPTY_VALUE;          
         neutral[i] = EMPTY_VALUE;
         peak[i] = EMPTY_VALUE;
         trough[i] = EMPTY_VALUE;     
         double slope = (buffer1[i]-buffer1[i+1]);
         double slope2 = (buffer1[i+1]-buffer1[i+2]);
         double slope3 = (buffer1[i+2]-buffer1[i+3]);
         double normalizer = 0;
         if(Normalize)
         {
            normalizer = range*0.1;
         }
         else
         {
            normalizer = TICK;
         }
         
         if(slope/(normalizer) > TrendThreshold)
         {
            bull[i] = buffer1[i];
         }
         else if(slope/(normalizer) < -1 * TrendThreshold)
         {
            bear[i] = buffer1[i];
         }
         else
         {
            neutral[i] = buffer1[i];
         }
          
          if (slope < 0 && slope > slope2 && slope2 < slope3)
          {
            if (Open[i] > Close[i])
            {
               trough[i] = Low[i];
            }
          }
          if (slope > 0 && slope < slope2 && slope2 > slope3)
          {
            if (Open[i] < Close[i])
            {
            //Print("here ", i);
               peak[i] = High[i];
            }
          }
          
          //if (i < 100) Print (" slope ", slope," slope2 ", slope2," slope3 ", slope3);
         
      }
      if (!calculateValue) manageAlerts();
      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]);
      buffer1[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateTma",HalfLength,Price,ATRMultiplier,ATRPeriod,0,y);
      buffer2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateTma",HalfLength,Price,ATRMultiplier,ATRPeriod,1,y);
      buffer3[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateTma",HalfLength,Price,ATRMultiplier,ATRPeriod,2,y);
      trend[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateTma",HalfLength,Price,ATRMultiplier,ATRPeriod,3,y);

      //
      //
      //
      //
      //
       
      if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
      if (!Interpolate) continue;

      //
      //
      //
      //
      //

      datetime time = iTime(NULL,timeFrame,y);
         for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
         for(k = 1; k < n; k++)
         {
            buffer1[i+k] = buffer1[i]  +(buffer1[i+n]-buffer1[i])*k/n;
            buffer2[i+k] = buffer2[i]  +(buffer2[i+n]-buffer2[i])*k/n;
            buffer3[i+k] = buffer3[i]  +(buffer3[i+n]-buffer3[i])*k/n;
         }               
   }

   //
   //
   //
   //
   //
      
   manageAlerts();
   return(0);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      int trend;                
      int lastTrend;
      if (alertsOnHighLow)       
      {
         if (High[whichBar] > buffer2[whichBar]) trend =  1;
         if (Low[whichBar]  < buffer3[whichBar]) trend = -1;
         if (High[whichBar+1] > buffer2[whichBar+1]) lastTrend =  1;
         if (Low[whichBar+1]  < buffer3[whichBar+1]) lastTrend = -1;
      }
      else
      {
         if (Close[whichBar] > buffer2[whichBar]) trend =  1;
         if (Close[whichBar] < buffer3[whichBar]) trend = -1;
         if (Close[whichBar+1] > buffer2[whichBar+1]) lastTrend =  1;
         if (Close[whichBar+1] < buffer3[whichBar+1]) lastTrend = -1;
      } 
            
      
      if (trend != lastTrend)
      {
         if (trend == 1) doAlert(whichBar,"up");
         if (trend ==-1) doAlert(whichBar,"down");
      }         
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," "+timeFrameToString(timeFrame)+" TMA bands price penetrated ",doWhat," band");
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"TMA bands "),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)
{
   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 chars = StringGetChar(s, length);
         if((chars > 96 && chars < 123) || (chars > 223 && chars < 256))
                     s = StringSetChar(s, length, chars - 32);
         else if(chars > -33 && chars < 0)
                     s = StringSetChar(s, length, chars + 224);
   }
   return(s);
}