//+------------------------------------------------------------------+
//|                                              Spread_Recorder.mq4 |
//|                                                         Zen_Leow |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Zen_Leow"
#property link      ""
#property indicator_chart_window

#include <stdlib.mqh>
#include <stderror.mqh>


string msg = "";
double CustomSpread = 0;
double LastKnownSpread = 0;
int PipFactor = 1;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
   // Cater for fractional pips
   if (Digits == 3 || Digits == 5)
   {
      PipFactor = 10;
   }
   GetSpread();

   msg = "";
   WriteToLogFile(msg);
   
   LastKnownSpread = CustomSpread;
   WriteMessage();
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }

void WriteMessage()
{
   msg = "Ask: "+DoubleToStr(Ask,Digits)+" | Bid: "+DoubleToStr(Bid,Digits)+" | Spread: "+DoubleToStr(CustomSpread,2)+" pips";
   WriteToLogFile(msg);
}

void GetSpread()
{
   CustomSpread = (MarketInfo(Symbol(),MODE_SPREAD)) / PipFactor;
}

void WriteToLogFile(string Iinput)
{
   string filename = "Spread_Recording/"+Symbol()+"-Spread_Recorder-"+Day()+"-"+Month()+"-"+Year()+".log";
   Iinput = TimeHour(TimeCurrent())+":"+TimeMinute(TimeCurrent())+":"+TimeSeconds(TimeCurrent())+" - "+Iinput;
   int handle = FileOpen(filename,FILE_READ|FILE_WRITE);
   if (handle>1)
   {
      FileSeek(handle, 0, SEEK_END); // go to end of file
      FileWrite(handle, Iinput);
      FileClose(handle);
   }
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
//----
   GetSpread();
   if (CustomSpread != LastKnownSpread)
   {
      WriteMessage();
   }
   LastKnownSpread = CustomSpread;
//----
   return(0);
}
//+------------------------------------------------------------------+