//+------------------------------------------------------------------+
//|                                        Wilders_Trailing_Stop.mq4 |
//|                               Copyright © 2013, Gehtsoft USA LLC |
//|                                            http://fxcodebase.com |
//+------------------------------------------------------------------+

#property copyright "Copyright © 2013, Gehtsoft USA LLC"
#property link      "http://fxcodebase.com"

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Orange
#property indicator_color2 LimeGreen
#property indicator_color3 LimeGreen
#property indicator_color4 Orange
#property indicator_width3 1
#property indicator_width4 1

extern int Length=5;
extern double Coeff=3.5;

double WTS[], WTSDn[], arrUp[], arrDn[];

int init()
{

    IndicatorShortName("Wilders trailing stop");
    IndicatorDigits(Digits);
    SetIndexBuffer(0,WTS);
    SetIndexBuffer(1,WTSDn);
    SetIndexBuffer(2,arrUp); SetIndexStyle(2,DRAW_ARROW); SetIndexArrow(2,SYMBOL_ARROWUP);
    SetIndexBuffer(3,arrDn); SetIndexStyle(3,DRAW_ARROW); SetIndexArrow(3,SYMBOL_ARROWDOWN);
 

 return(0);
}

int deinit()
{

 return(0);
}

int start()
{
 if(Bars<=Length) return(0);
 int ExtCountedBars=IndicatorCounted();
 if (ExtCountedBars<0) return(-1);
 int limit=Bars-2;
 if(ExtCountedBars>2) limit=Bars-ExtCountedBars-1;
 int pos;
 double loss;
 pos=limit;
 while(pos>=0)
 {
   arrUp[pos]=EMPTY_VALUE;
   arrDn[pos]=EMPTY_VALUE;
   WTSDn[pos]=EMPTY_VALUE;
  loss=iATR(NULL, 0, Length, pos)*Coeff;
  if (Close[pos]>WTS[pos+1] && Close[pos+1]>WTS[pos+1])
  {
   WTS[pos]=MathMax(WTS[pos+1], Close[pos]-loss);
   WTSDn[pos]=WTS[pos];
   WTSDn[pos+1]=WTS[pos+1];
  }
  else
  {
   if (Close[pos]<WTS[pos+1] && Close[pos+1]<WTS[pos+1])
   {
    WTS[pos]=MathMin(WTS[pos+1], Close[pos]+loss);
   }
   else
   {
    if (Close[pos]>WTS[pos+1])
    {
     WTS[pos]=Close[pos]-loss;
     WTSDn[pos]=WTS[pos];
     WTSDn[pos+1]=WTS[pos+1];
    }
    else
    {
     WTS[pos]=Close[pos]+loss;
    }
   }
  }
  if (WTSDn[pos]!=EMPTY_VALUE && WTSDn[pos+2]==EMPTY_VALUE) arrUp[pos] = WTS[pos]-iATR(NULL, 0, 10, pos)/2;
  if (WTSDn[pos]==EMPTY_VALUE && WTSDn[pos+1]!=EMPTY_VALUE) arrDn[pos] = WTS[pos]+iATR(NULL, 0, 10, pos)/2;
  pos--;
 } 
 return(0);
}

