//+------------------------------------------------------------------+
//|                                                    OHLC - HA.mq4 |
//+------------------------------------------------------------------+

#property indicator_chart_window

#property indicator_buffers 4
#property indicator_color1 Red
#property indicator_color2 Green
#property indicator_color3 Red
#property indicator_color4 Green
#property indicator_width1 1
#property indicator_width2 1
#property indicator_width3 5
#property indicator_width4 5

double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];

int ExtCountedBars=0;

//|------------------------------------------------------------------|
int init()  {
//|------------------------------------------------------------------|

  SetIndexStyle(0,DRAW_HISTOGRAM, 0, 1, Red);
  SetIndexBuffer(0, ExtMapBuffer1);
  SetIndexStyle(1,DRAW_HISTOGRAM, 0, 1, Green);
  SetIndexBuffer(1, ExtMapBuffer2);
  SetIndexStyle(2,DRAW_HISTOGRAM, 0, 5, Red);
  SetIndexBuffer(2, ExtMapBuffer3);
  SetIndexStyle(3,DRAW_HISTOGRAM, 0, 5, Green);
  SetIndexBuffer(3, ExtMapBuffer4);

  SetIndexDrawBegin(0,10);
  SetIndexDrawBegin(1,10);
  SetIndexDrawBegin(2,10);
  SetIndexDrawBegin(3,10);

  SetIndexBuffer(0,ExtMapBuffer1);
  SetIndexBuffer(1,ExtMapBuffer2);
  SetIndexBuffer(2,ExtMapBuffer3);
  SetIndexBuffer(3,ExtMapBuffer4);

  return(0);
}

//+------------------------------------------------------------------+
int deinit()  {
//+------------------------------------------------------------------+
  return(0);
}

//+------------------------------------------------------------------+
int start()  {
//+------------------------------------------------------------------+
  double haOpen, haHigh, haLow, haClose;
  if(Bars<=10) return(0);
  ExtCountedBars=IndicatorCounted();
  if (ExtCountedBars<0) return(-1);
  if (ExtCountedBars>0) ExtCountedBars--;
  int pos=Bars-ExtCountedBars-1;

  while(pos>=0)  {
    haOpen=(haOpen+haClose)/2;
    haClose=(Open[pos]+High[pos]+Low[pos]+Close[pos])/4;
    haHigh=MathMax(High[pos], MathMax(haOpen, haClose));
    haLow=MathMin(Low[pos], MathMin(haOpen, haClose));
    double top = MathMax(Open[pos],Close[pos]);
    double bot = MathMin(Open[pos],Close[pos]);
    if (haOpen<haClose)  {                                // green candle
      ExtMapBuffer1[pos]=Low[pos];
      ExtMapBuffer2[pos]=High[pos];
      ExtMapBuffer3[pos]=bot;
      ExtMapBuffer4[pos]=top;
    } else {                                              // red candle
      ExtMapBuffer1[pos]=High[pos];
      ExtMapBuffer2[pos]=Low[pos];
      ExtMapBuffer3[pos]=top;
      ExtMapBuffer4[pos]=bot;
    } 
    pos--;
  }
  return(0);
}
//+------------------------------------------------------------------+