//+------------------------------------------------------------------+
//|                                           Plot External Data.mq4 |
//+------------------------------------------------------------------+

#property  indicator_separate_window

#include <hanover --- function header (np).mqh>

#property  indicator_buffers 1
#property  indicator_color1  Red
#property  indicator_width1  1

extern   string   FileName         = "data.csv";
extern   string   DateFormat       = "YYYY.MM.DD HH:II";
extern   string   DateDelimiters   = ". :";
extern   string   FieldDelimiter   = ",";
extern   color    LineColor        = Red;
extern   int      LineWidth        = 1;
extern   int      LineStyle        = STYLE_SOLID;
extern   double   ScalingFactor    = 1.0;

double     buffer0[];

datetime   dt[9999];
double     val[9999];
string     arr[4];    // added to accomplish format conversion


//+------------------------------------------------------------------+
int init()  {
//+------------------------------------------------------------------+
  SetIndexBuffer(0,buffer0);
  SetIndexStyle(0,DRAW_LINE,LineStyle,LineWidth,LineColor);
  SetIndexDrawBegin(0,0);
  IndicatorShortName("External: "+FileName);
  return(0);
}

//+------------------------------------------------------------------+
int start()  {
//+------------------------------------------------------------------+
  int h = FileOpen(FileName, FILE_CSV|FILE_READ,'~');
  if (h==0) {
    Comment("File "+FileName+" not found.");
    return(0);
  }  

  // First pass loads data from file into arrays dt, val   (i.e. date/time, and value)
  for (int c=0; !FileIsEnding(h) && c<9999; c++)  {
    string tmp = FileReadString(h);
    if (FileIsEnding(h))  break;
    if (StringLen(StringTrimRight(tmp)) < 1)   continue;    // ignore blank lines
    StrToStringArray(tmp,arr,FieldDelimiter);
    dt[c]  = StrToDate(arr[0],DateFormat,DateDelimiters);
    val[c] = StrToNumber(arr[1]);
//    if (c>0)  log(c,DateToStr(dt[c]),NumberToStr(val[c],"RT-3.5"));    // debugging only
  }
  FileClose(h);
  
  // Second pass re-synchs data from dt, val arrays onto chart timeframe, and plots them accordingly
  c--;
  for (int i=0; i<=Bars; i++)  {
    while(Time[i]<dt[c]) c--;
    if (c>=0) buffer0[i] = val[c]*ScalingFactor;
//    if (i<30) log(i,DateToStr(Time[i]),c,DateToStr(dt[c]),val[c],buffer0[i]);    // debugging only
  }
  
  return(0);
}

//+------------------------------------------------------------------+
#include <hanover --- extensible functions (np).mqh>

