//+------------------------------------------------------------------+
//|                                                          ASI.mq4 |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  PaleVioletRed
#property indicator_color2  DeepSkyBlue
#property indicator_color3  DimGray
#property indicator_color4  LimeGreen
#property indicator_style3  STYLE_DOT
#property indicator_width4  2

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i,double precision);
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i,double precision);
#import

//
//
//
//
//

extern string TimeFrame                = "current time frame";
extern string ForSymbol                = "";
extern double T                        = 300.0;
extern int    SmoothLength             = 9;
extern double SmoothPhase              = -100;
extern int    DzLookBackBars           = 70;
extern double DzStartBuyProbability    = 0.15;
extern double DzStartSellProbability   = 0.15;
extern bool   arrowsVisible            = false;
extern bool   arrowsUpLevelVisible     = false;
extern bool   arrowsMiddleLevelVisible = true;
extern bool   arrowsDownLevelVisible   = false;
extern bool   arrowsShowBreakOut       = true;
extern bool   arrowsShowRetrace        = true;
extern string arrowsIdentifier         = "dz - asi arrows ID 1";
extern color  arrowsUpColor            = DeepSkyBlue;
extern color  arrowsDnColor            = Red;
extern bool   alertsOn                 = false;
extern bool   alertsOnCurrent          = true;
extern bool   alertsOnUpLevelCross     = false;
extern bool   alertsOnMiddleLevelCross = true;
extern bool   alertsOnDownLevelCross   = false;
extern bool   alertsMessage            = true;
extern bool   alertsSound              = false;
extern bool   alertsEmail              = false;
extern bool   Interpolate              = true;

double ASIBuffer[];
double SIBuffer[];
double sli[];
double bli[];
double zli[];
double trend1[];
double trend2[];
double trend3[];
   
//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

   
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,bli);
   SetIndexBuffer(1,sli);
   SetIndexBuffer(2,zli);
   SetIndexBuffer(3,ASIBuffer); SetIndexEmptyValue(3, 0.0); SetIndexLabel(3, "Accumulation Swing Index");
   SetIndexBuffer(4,SIBuffer);  SetIndexEmptyValue(4, 0.0);
   SetIndexBuffer(5,trend1);
   SetIndexBuffer(6,trend2);
   SetIndexBuffer(7,trend3);
   

   //
   //
   //
   //
   //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
   if (ForSymbol=="") ForSymbol=Symbol();

   IndicatorShortName(timeFrameToString(timeFrame)+" "+ForSymbol+" Accumulation Swing Index ("+DoubleToStr(T,2)+")");
   return(0);
}

//
//
//
//
//

int deinit()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int i, limit, counted_bars = IndicatorCounted();

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { bli[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || (ForSymbol == Symbol() && timeFrame == Period()))
   {
      double R, K, TR, ER, SH;
      
      //
      //
      //
      //
      //
      
      for(i = limit; i >= 0; i--)
      {
         TR = iATR(NULL, 0, 1, i);
         
         if(Close[i+1] >= Low[i] && Close[i+1] <= High[i]) 
            ER = 0; 
         else 
            {
               if(Close[i+1] > High[i]) ER = MathAbs(High[i] - Close[i+1]);
               if(Close[i+1] < Low[i])  ER = MathAbs(Low[i] - Close[i+1]);
            }
         K  = MathMax(MathAbs(High[i] - Close[i+1]), MathAbs(Low[i] - Close[i+1]));
         SH = MathAbs(Close[i+1] - Open[i+1]);
         R  = TR - 0.5*ER + 0.25*SH;
         if (R == 0) 
               SIBuffer[i] = iSmooth(0,SmoothLength,SmoothPhase,i,0); 
         else  SIBuffer[i] = iSmooth(50*(Close[i] - Close[i+1] + 0.5*(Close[i] - Open[i]) +  0.25*(Close[i+1] - Open[i+1]))*(K / T) / R,SmoothLength,SmoothPhase,i,0); 
         
              ASIBuffer[i] = iSmooth(ASIBuffer[i+1] + SIBuffer[i],SmoothLength,SmoothPhase,i,10);
              bli[i]     = dzBuyP (ASIBuffer, DzStartBuyProbability,  DzLookBackBars, Bars, i,0.0001);
              sli[i]     = dzSellP(ASIBuffer, DzStartSellProbability, DzLookBackBars, Bars, i,0.0001);
              zli[i]     = dzSellP(ASIBuffer, 0.5,                    DzLookBackBars, Bars, i,0.0001);

         //
         //
         //
         //
         //
         
         trend1[i] = trend1[i+1];
         trend2[i] = trend2[i+1];
         trend3[i] = trend3[i+1];
            if (ASIBuffer[i]>bli[i]) trend1[i] =  1;
            if (ASIBuffer[i]<bli[i]) trend1[i] = -1;
            if (ASIBuffer[i]>sli[i]) trend2[i] =  1;
            if (ASIBuffer[i]<sli[i]) trend2[i] = -1;
            if (ASIBuffer[i]>zli[i]) trend3[i] =  1;
            if (ASIBuffer[i]<zli[i]) trend3[i] = -1;
            manageArrow(i);
      }
      manageAlerts();
      return(0);
   }

   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(ForSymbol,timeFrame,indicatorFileName,"returnBars",0,0)));
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(ForSymbol,timeFrame,Time[i]);
         bli[i]       = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,0,y);
         sli[i]       = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,1,y);
         zli[i]       = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,2,y);
         ASIBuffer[i] = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,3,y);
         trend1[i]    = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,5,y);
         trend2[i]    = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,6,y);
         trend3[i]    = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",T,SmoothLength,SmoothPhase,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,7,y);
            manageArrow(i);

         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
            {
               bli[i+k]       = bli[i]  + (bli[i+n] -bli[i])*k/n;
               sli[i+k]       = sli[i]  + (sli[i+n] -sli[i])*k/n;
               zli[i+k]       = zli[i]  + (zli[i+n] -zli[i])*k/n;
               ASIBuffer[i+k] = ASIBuffer[i]  + (ASIBuffer[i+n] -ASIBuffer[i])*k/n;
            }               
   }
   manageAlerts();
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i)
{
   if (!calculateValue && arrowsVisible && ForSymbol==Symbol())
   {
         deleteArrow(Time[i]);
         if (arrowsDownLevelVisible && trend1[i]!=trend1[i+1])
         {
            if (trend1[i] == 1) drawArrow(i,arrowsUpColor,241,false);
            if (trend1[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
         }
         if (arrowsUpLevelVisible && trend2[i]!=trend2[i+1])
         {
            if (trend2[i] == 1) drawArrow(i,arrowsUpColor,241,false);
            if (trend2[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
         }
         if (arrowsMiddleLevelVisible && trend3[i]!=trend3[i+1])
         {
            if (trend3[i] == 1) drawArrow(i,arrowsUpColor,241,false);
            if (trend3[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
         }
   }
}

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = 3.0*iATR(NULL,0,20,i)/4.0;   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap);
}

//
//
//
//
//

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));

      //
      //
      //
      //
      //

         static datetime time1 = 0;
         static string   mess1 = "";
         if (alertsOnDownLevelCross && trend1[whichBar] != trend1[whichBar+1])
         {
            if (trend1[whichBar] == 1) doAlert(time1,mess1,whichBar,"down level "+DoubleToStr(sli[whichBar],Digits)+" up");
            if (trend1[whichBar] ==-1) doAlert(time1,mess1,whichBar,"down level "+DoubleToStr(sli[whichBar],Digits)+" don");
         }

         static datetime time2 = 0;
         static string   mess2 = "";
         if (alertsOnUpLevelCross && trend2[whichBar] != trend2[whichBar+1])
         {
            if (trend2[whichBar] == 1) doAlert(time2,mess2,whichBar,"up level "+DoubleToStr(bli[whichBar],Digits)+" up");
            if (trend2[whichBar] ==-1) doAlert(time2,mess2,whichBar,"up level "+DoubleToStr(bli[whichBar],Digits)+" don");
         }

         static datetime time3 = 0;
         static string   mess3 = "";
         if (alertsOnMiddleLevelCross && trend3[whichBar] != trend3[whichBar+1])
         {
            if (trend3[whichBar] == 1) doAlert(time3,mess3,whichBar,"middle line "+DoubleToStr(sli[whichBar],Digits)+" up");
            if (trend3[whichBar] ==-1) doAlert(time3,mess3,whichBar,"middle line "+DoubleToStr(sli[whichBar],Digits)+" don");
         }
   }
}   

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
      if (previousAlert != doWhat || previousTime != Time[forBar]) {
          previousAlert  = doWhat;
          previousTime   = Time[forBar];

          //
          //
          //
          //
          //

          message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," ",ForSymbol," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Dynamic zone ASI crossed ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Dynamic zone ASI "),message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}


//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

double wrk[][20];
#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[0][k+s]=price; for(; k<10; k++) wrk[0][k+s]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrk[r][4+s]);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}