//------------------------------------------------------------------
//                                                NRTR_ATR_STOP.mq4 
//------------------------------------------------------------------
#property copyright ""
#property link      ""

#property indicator_chart_window
#property indicator_buffers  2
#property indicator_color1 LimeGreen
#property indicator_color2 DarkOrange
#property indicator_width1 2
#property indicator_width2 2

extern int    ATR        = 20;
extern double Coeficient = 2;

//
//
//
//
//

double Up[], Dn[], mode[];

//------------------------------------------------------------------
//
//------------------------------------------------------------------
int init()
  {
   IndicatorBuffers(3);
   SetIndexBuffer(0, Up); SetIndexLabel (0, "Up");
   SetIndexBuffer(1, Dn); SetIndexLabel (1, "Dn");
   SetIndexBuffer(2, mode);
return(0);
}
int deinit() 
{ 
return(0); 
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
           int limit=MathMin(Bars-counted_bars,Bars-1);

   //
   //
   //
   //
   //
   
      for(int i = limit - 1; i >= 0; i--)
      {
       Dn[i]   = EMPTY_VALUE; 
       Up[i]   = EMPTY_VALUE;
       mode[i] = mode[i+1];
       double REZ = Coeficient*iATR(NULL, 0, ATR, i);

       if((mode[i] == -1 || mode[i]==EMPTY_VALUE) &&  Low[i+1] > Dn[i+1]) 
       { 
           Up[i+1] = Low[i+1] - REZ; 
           mode[i] = 1; 
       }
       if((mode[i]==1 || mode[i]==EMPTY_VALUE) && High[i+1] < Up[i+1]) 
       { 
           Dn[i+1] = High[i+1] + REZ; 
           mode[i] = -1; 
       }
       
       //
       //
       //
       //
       //
       
       if(mode[i]==1)
         {
           if(Low[i+1] > Up[i+1] + REZ) 
             { 
               Up[i] = Low[i+1] - REZ; 
               Dn[i] = EMPTY_VALUE; 
             }
		         else 
		           { 
		             Up[i] = Up[i+1]; 
                   Dn[i] = EMPTY_VALUE; 
		           }
		       }
       if(mode[i]==-1)
         {
     	     if(High[i+1] < Dn[i+1] - REZ) 
     	       { 
     	         Dn[i] = High[i+1] + REZ; 
     	         Up[i] = EMPTY_VALUE; 
     	       }
	          else 
	            { 
	              Dn[i] = Dn[i+1]; 
	              Up[i] = EMPTY_VALUE; 
	            }
	        }
      }
      return(0);
   }
   
   