//+------------------------------------------------------------------+
//|                                               StochMACD.mq4 |
//+------------------------------------------------------------------+

#property copyright "Squalou"
#property link      ""

#property  indicator_separate_window
#property indicator_minimum  0
#property indicator_maximum  100
#property  indicator_buffers 2
#property  indicator_color2  Orange
#property  indicator_color1  Black

//---- input parameters
extern int FastEMA   =12;
extern int SlowEMA   =26;
extern int SignalSMA =9;
extern int StochasticPeriod =120; //4 weeks of H4 bars = 4*5*24/4 = 120

//----------------------------------


double macdSignal[], StochMACD[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {

   IndicatorShortName("StochMACDsq");
   
   SetIndexBuffer(0,macdSignal);

   SetIndexStyle(1,DRAW_LINE);
   SetIndexLabel(1,"StochMACD");
   SetIndexBuffer(1,StochMACD);
   SetIndexDrawBegin(1,StochasticPeriod);


   return(0);
  }
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {

   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
  int limit;
  int i,j;
  int counted_bars=IndicatorCounted();

//---- last counted bar will be recounted
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;

  //---- macd signal line, start from oldest bar
  for(i=limit; i>=0; i--)
  {
     StochMACD[i] = StochMACD(FastEMA,SlowEMA,SignalSMA, StochasticPeriod,i);
	}

  return(0);
}
//+------------------------------------------------------------------+

double StochMACD(int fast_ema_period, int slow_ema_period, int signal_period, int StochasticPeriod, int shift)
{
  // get macd signal line
  double macdSignal;
  int j;
  // get highest/lowest of macdSignal over StochasticPeriod
  double ll = 100000, hh = -100000, dif;
  for(j=shift; j<shift+StochasticPeriod; j++)
  {
    macdSignal = iMACD(NULL,0,fast_ema_period, slow_ema_period, signal_period, PRICE_CLOSE,MODE_SIGNAL,j);
    hh = MathMax(hh,macdSignal);
    ll = MathMin(ll,macdSignal);
  }

  // normalize to 0..100

  dif = hh-ll;
  if (dif==0) return (0);
  else return (100 * (iMACD(NULL,0,fast_ema_period, slow_ema_period, signal_period, PRICE_CLOSE,MODE_SIGNAL,shift)-ll)/dif); 
}

