//------------------------------------------------------------------
#property copyright "mladen - forex-station.com"
#property copyright "forex-station.com"
#property link      "https://www.forex-station.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  clrRed
#property indicator_color2  clrBrown

//
//
//
//
//

extern string            TimeFrame       = "Current time frame";
extern int               TSIPeriod1      = 25;
extern int               TSIPeriod2      = 13;
extern int               SignalPeriod    =  7;
input int                TsiLineWidth    = 2;
input int                SigLineWidth    = 12;
input ENUM_APPLIED_PRICE Price           = PRICE_CLOSE;
input bool               alertsOn        = true;             // Turn alerts on?
input bool               alertsOnCurrent = false;            // Alerts on still open bar?
input bool               alertsMessage   = true;             // Alerts should show popup message?
input bool               alertsSound     = false;            // Alerts should play a sound?
input bool               alertsEmail     = false;            // Alerts should send email?
input bool               alertsPushNotif = false;            // Alerts should send notification?

double TSIBuffer[];
double SignalBuffer[];
double trend[];
string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(3);
   SetIndexBuffer(0,TSIBuffer);    SetIndexStyle(0,DRAW_LINE,EMPTY,TsiLineWidth); SetIndexLabel(0,"TSI");
   SetIndexBuffer(1,SignalBuffer); SetIndexStyle(1,DRAW_LINE,EMPTY,SigLineWidth); SetIndexLabel(1,"TSI Signal");
   SetIndexBuffer(2,trend);
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //

   IndicatorShortName(timeFrameToString(timeFrame)+" TSI ("+TSIPeriod1+","+TSIPeriod2+","+SignalPeriod+")");
   return(0);
}

//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { TSIBuffer[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      for (int i=limit; i>=0; i--)
      {
         double priceDiff = iMA(NULL,0,1,0,MODE_SMA,Price,i)-iMA(NULL,0,1,0,MODE_SMA,Price,i+1);
         double avg = iEma(iEma(        priceDiff ,TSIPeriod1,i,0),TSIPeriod2,i,1);
         double ava = iEma(iEma(MathAbs(priceDiff),TSIPeriod1,i,2),TSIPeriod2,i,3);
            if (ava != 0)
                  TSIBuffer[i] = 100.0*avg/ava;
            else  TSIBuffer[i] = 0.00;
            SignalBuffer[i] = iEma(TSIBuffer[i],SignalPeriod,i,4);
            trend[i] = (i<Bars-1) ? (TSIBuffer[i]>0) ? 1 : (TSIBuffer[i]<0) ? -1 :  trend[i+1] : 0;
      }
      
      //
      //
      //
      //
      //
      
      if (alertsOn)
      {
         int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
         if (trend[whichBar] != trend[whichBar+1])
         if (trend[whichBar] == 1)
               doAlert("crossing zero up");
         else  doAlert("crossing zero down");       
      }  
      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]);
         TSIBuffer[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",TSIPeriod1,TSIPeriod2,SignalPeriod,TsiLineWidth,SigLineWidth,Price,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsPushNotif,0,y);
         SignalBuffer[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",TSIPeriod1,TSIPeriod2,SignalPeriod,TsiLineWidth,SigLineWidth,Price,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsPushNotif,1,y);
   }
   return(0);         
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workEma[][5];
double iEma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars); r = Bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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 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 = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" TSI "+doWhat;
             if (alertsMessage)   Alert(message);
             if (alertsPushNotif) SendNotification(message);
             if (alertsEmail)     SendMail(_Symbol+" TSI ",message);
             if (alertsSound)     PlaySound("alert2.wav");
      }
}