//+------------------------------------------------------------------+
//|                MA_Touch.mq4                                      |
//+------------------------------------------------------------------+
#property copyright "FxFisherman.com"
#property link      "http://www.fxfisherman.com"

extern int Crossed_Pips = 1;
extern int MA_Period = 35;
extern int MA_Type = MODE_SMA;
extern string File_Name="MA_Touch.csv";

int curr_already_touched = 0 ;
int just_started = 1 ;
datetime start_time ;
int Handle = 0 ;

int init()
{
  Handle=FileOpen(File_Name, FILE_CSV|FILE_WRITE, " ");// File opening
   if ( Handle > 0 ) {
     Print("File opened");
   } else {
     Print("Cannot open file!");
   }
   return(0);
}

void deinit()
{
   string StrL ;
   
   if ( Handle > 0 ) {
      FileClose(Handle);
      Handle = 0 ;
   }
}

int start()
 {
  double ma, ma_prev, ma_prev_prev, ma_curr;
  datetime curr_start = Time[0];
  string StrL ;

  if ( just_started == 1 ) { // this is the first execution
    just_started = 0 ;
    start_time = Time[0];
  } else { // not the first execution
    if ( curr_start == start_time ) { // bar not changed
       if ( curr_already_touched > 0 ) return(0) ; // a touch already occured on curr bar
    } else { // bar changed
       start_time = curr_start ;
       curr_already_touched = 0 ;
    }
  }

  ma_prev = iMA(Symbol(), Period(), MA_Period, 0, MA_Type, PRICE_CLOSE, 1);
  ma_prev_prev = iMA(Symbol(), Period(), MA_Period, 0, MA_Type, PRICE_CLOSE, 2);
  // Extrapolating to current bar:
  ma_curr = ma_prev + ma_prev - ma_prev_prev ;
  //---------- Ask
  //---------- Bid
  if ( Open[0] > ma_prev ) { // looking for touch from above, by Bid
     if ( Bid <= (ma_curr + (Crossed_Pips * Point)) ) { 
        curr_already_touched = 1 ;
        if ( Handle > 0 ) {
           StrL = "" ;
           StrL = StringConcatenate(StrL, "Touch from above, Time: ", TimeToStr(TimeCurrent()), 
                                        ", Bid:", Bid);
           FileWrite(Handle, StrL);
        }
     }
  }
  if ( Open[0] < ma_prev ) { // looking for touch from below, by Ask
     if ( Ask >= (ma_curr - (Crossed_Pips * Point)) ) { 
        curr_already_touched = 1 ;
        if ( Handle > 0 ) {
           StrL = "" ;
           StrL = StringConcatenate(StrL, "Touch from below, Time: ", TimeToStr(TimeCurrent()), 
                                        ", Ask:", Ask);
           FileWrite(Handle, StrL);
        }
     }
  }

   return(0);
 }
 
//+------------------------------------------------------------------+