//+------------------------------------------------------------------+
//|                                Jim Sloman's natural market combo |
//|                   with Standard Deviation and historical extreme |
//|                                                                  |
//|                                            ocn nmc & SD hist.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 6
#property indicator_color1  DimGray
#property indicator_color2  DeepSkyBlue
#property indicator_color3  PaleVioletRed
#property indicator_color4  SeaGreen
#property indicator_color5  DimGray
#property indicator_color6  DeepSkyBlue
#property indicator_style1  STYLE_DOT
#property indicator_style4  STYLE_DOT
#property indicator_style5  STYLE_DOT
#property indicator_width6  2

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuy(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
   double dzSell(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i );
#import

//
//
//
//
//

extern string TimeFrame              = "current time frame";
extern int    NMCPeriod              = 40;
extern int    NMCPrice               = PRICE_CLOSE;
extern int    TEMAPeriod             = 10;
extern bool   ShowStandardDeviation  = true;
extern int    SDPeriod               = 30;
extern double SDUp                   = 2.0;
extern double SDDown                 = 2.0;
extern bool   ShowHistoricalExtreme  = true;
extern int    HistoryLookBack        = 15;
extern int    DzLookBackBars         = 70;
extern double DzStartBuyProbability  = 0.10;
extern double DzStartSellProbability = 0.10;
extern bool   Interpolate            = true;

//
//
//
//
//

double nmc[];
double zeroLine[];
double bli[];
double sli[];
double sd[];
double hist[];
double tBuffer[][4];
double alpha;

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,zeroLine); SetIndexLabel(0,NULL);
   SetIndexBuffer(1,bli);      SetIndexLabel(1,NULL);
   SetIndexBuffer(2,sli);      SetIndexLabel(2,NULL);
   SetIndexBuffer(3,hist);     SetIndexDrawBegin(3,NMCPeriod+SDPeriod);
   SetIndexBuffer(4,sd);       SetIndexDrawBegin(4,NMCPeriod+SDPeriod);
   SetIndexBuffer(5,nmc);      SetIndexDrawBegin(5,NMCPeriod);
   
   //
   //
   //
   //
   //
   
   string PriceType;
      switch(NMCPrice)
      {
         case PRICE_CLOSE:    PriceType = "Close";    break;  // 0
         case PRICE_OPEN:     PriceType = "Open";     break;  // 1
         case PRICE_HIGH:     PriceType = "High";     break;  // 2
         case PRICE_LOW:      PriceType = "Low";      break;  // 3
         case PRICE_MEDIAN:   PriceType = "Median";   break;  // 4
         case PRICE_TYPICAL:  PriceType = "Typical";  break;  // 5
         case PRICE_WEIGHTED: PriceType = "Weighted"; break;  // 6
      }      
      TEMAPeriod = MathMax(TEMAPeriod,1);
      NMCPeriod  = MathMax(NMCPeriod ,1);
           alpha = 2.0 /(1.0 + TEMAPeriod);

      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
   
   //
   //
   //
   //
   //

   IndicatorShortName (timeFrameToString(timeFrame)+" nmc & SD hist ("+NMCPeriod+","+PriceType+","+TEMAPeriod+")");
   return(0);
}
int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define iPrc 3

//
//
//
//
//

int start()
{
   int    counted_bars=IndicatorCounted();
   int    i,k,r,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit=MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { zeroLine[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      if (ArrayRange(tBuffer,0) != Bars) ArrayResize(tBuffer,Bars);
      for(i=limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         double rawPrice  = iMA(NULL,0,1,0,MODE_SMA,NMCPrice,i);
         double currPrice = iTema(rawPrice,r);
         if (currPrice > 0)
               tBuffer[r][iPrc] = MathLog(currPrice);
         else  tBuffer[r][iPrc] = 0.00;
      
         //
         //
         //
         //
         //
         
         nmc[i]      = 0;
         zeroLine[i] = 0;
            double nmm = iNmmFunction(1,i);
            double nmr = iNmrFunction(1,i);
            double tmp = (MathAbs(nmm)*nmr+MathAbs(nmr)*nmm)/2.00;
               if (tmp > 0) nmc[i] =  MathSqrt( tmp);
               if (tmp < 0) nmc[i] = -MathSqrt(-tmp);
         
         //
         //
         //
         //
         //

         if (ShowStandardDeviation)
         {         
            sd[i] = 0;
            double avg = iSma(nmc,SDPeriod,i);
            double deviation = iDeviation(nmc,avg,SDPeriod,i);
               if (nmc[i] > 0) sd[i] = avg+deviation*SDUp;
               if (nmc[i] < 0) sd[i] = avg-deviation*SDDown;
         }
         
         //
         //
         //
         //
         //
         
         if (ShowHistoricalExtreme)
         {
            hist[i]  = hist[i+1];
               if (nmc[i] >  0) hist[i] = MathMax(0,nmc[ArrayMaximum(nmc,HistoryLookBack,i)]);
               if (nmc[i] <  0) hist[i] = MathMin(0,nmc[ArrayMinimum(nmc,HistoryLookBack,i)]);
               if (nmc[i] == 0) hist[i] = 0;
         }               

         //
         //
         //
         //
         //

         bli[i]      = dzBuy (nmc, DzStartBuyProbability,  DzLookBackBars, Bars, i);
         sli[i]      = dzSell(nmc, DzStartSellProbability, DzLookBackBars, Bars, i);
         zeroLine[i] = dzSell(nmc, 0.5,                    DzLookBackBars, Bars, i);
      }
      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]);
         zeroLine[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,0,y);
         bli[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,1,y);
         sli[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,2,y);
         hist[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,3,y);
         sd[i]       = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,4,y);
         nmc[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",NMCPeriod,NMCPrice,TEMAPeriod,ShowStandardDeviation,SDPeriod,SDUp,SDDown,ShowHistoricalExtreme,HistoryLookBack,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,5,y);

         //
         //
         //
         //
         //
      
         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(k = 1; k < n; k++)
               {
                  zeroLine[i+k] = zeroLine[i] + (zeroLine[i+n] - zeroLine[i])*k/n;
                  bli[i+k]  = bli[i]  + (bli[i+n]  - bli[i]) *k/n;
                  sli[i+k]  = sli[i]  + (sli[i+n]  - sli[i]) *k/n;
                  hist[i+k] = hist[i] + (hist[i+n] - hist[i])*k/n;
                  sd[i+k]   = sd[i]   + (sd[i+n]   - sd[i])  *k/n;
                  nmc[i+k]  = nmc[i]  + (nmc[i+n]  - nmc[i]) *k/n;
               }
   }
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//    natural market mirror
//
//
//

double iNmmFunction(int startPeriod, int tPos)
{
   int    endPeriod = startPeriod*NMCPeriod;
   int    pos       = Bars-tPos-1;
   double sum       = 0.00;
   double currPrice = tBuffer[pos][iPrc];
      
   for (int i= startPeriod; i <= endPeriod; i += startPeriod)
           sum += (currPrice-tBuffer[pos-i][iPrc])/MathSqrt(i);
   return((sum/NMCPeriod)*1000.00);
}

//
//
//
//    natural market river
//
//
//

double iNmrFunction(int startPeriod, int tPos)
{
   int    endPeriod = startPeriod*NMCPeriod;
   int    pos       = Bars-tPos-1;
   double sum       = 0.00;
      
   for (int i=startPeriod; i <= endPeriod; i+=startPeriod)
          sum += (tBuffer[pos-i+startPeriod][iPrc]-tBuffer[pos-i][iPrc])*(MathSqrt(i)-MathSqrt(i-startPeriod));
   return(sum*1000.00);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double iDeviation(double& array[],double dMA, int period, int pos)
{
   double dSum = 0;
         for(int i=0; i<period; i++,pos++) dSum += (array[pos]-dMA)*(array[pos]-dMA);
   return(MathSqrt(dSum/period));
}

//
//
//
//
//

double iSma(double& array[], int period, int pos)
{
   double sum = 0;
         for(int i=0; i<period; i++,pos++) sum += array[pos];
   return(sum/period);
}

//
//
//
//
//

double iTema(double price,int i)
{
   if (i < 1)
      {
         tBuffer[i][0] = price;
         tBuffer[i][1] = price;
         tBuffer[i][2] = price;
      }
   else
      {
         tBuffer[i][0] = tBuffer[i-1][0]+alpha*(price        -tBuffer[i-1][0]);
         tBuffer[i][1] = tBuffer[i-1][1]+alpha*(tBuffer[i][0]-tBuffer[i-1][1]);
         tBuffer[i][2] = tBuffer[i-1][2]+alpha*(tBuffer[i][1]-tBuffer[i-1][2]);
      }
   return(3*tBuffer[i][0] - 3*tBuffer[i][1] + tBuffer[i][2]);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}