//+------------------------------------------------------------------+
//|                                               TestGoldenFile.mq5 |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Includes                                                         |
//+------------------------------------------------------------------+
#include <GoldenFile\DecisionRecorder.mqh>
#include <GoldenFile\GoldenCompare.mqh>
//+------------------------------------------------------------------+
//| Constants                                                        |
//+------------------------------------------------------------------+
#define DIR      "GoldenFile\\test\\"  // test files, in MQL5\Files of the terminal
#define SYM      "EURUSD"              // symbol of the test rows, must exist in Market Watch
#define T0_MSC   1770026400000         // 2026.02.02 10:00:00 in milliseconds, time of the first test tick
//+------------------------------------------------------------------+
//| One test decision                                                |
//+------------------------------------------------------------------+
struct STestRow
  {
   string            t;     // time as text
   string            kind;  // decision kind
   double            vol;   // volume
   double            px;    // price
   double            sl;    // stop loss
   double            tp;    // take profit
   long              ret;   // retcode
   string            note;  // note
  };
//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
int g_pass=0;  // checks that passed
int g_fail=0;  // checks that failed
//+------------------------------------------------------------------+
//| Check                                                            |
//| Prints one PASS or FAIL line and counts it.                      |
//+------------------------------------------------------------------+
void Check(const bool ok,const string name,const string detail="")
  {
   if(ok)
      g_pass++;
   else
      g_fail++;
   PrintFormat("%s %s%s",ok ? "PASS" : "FAIL",name,(!ok && detail!="") ? " | "+detail : "");
  }
//+------------------------------------------------------------------+
//| Base                                                             |
//| The ten decisions of the golden test file. Rows 3 and 4 share a  |
//| second: a close and a reversal on the same bar.                  |
//+------------------------------------------------------------------+
void Base(STestRow &r[])
  {
   ArrayResize(r,10);
   string t[10]   ={"2026.02.02 10:00:00","2026.02.02 13:00:00","2026.02.03 09:00:00","2026.02.03 09:00:00",
                    "2026.02.03 15:00:00","2026.02.04 11:00:00","2026.02.04 11:00:00","2026.02.05 08:00:00",
                    "2026.02.05 12:00:00","2026.02.06 16:00:00"};
   string k[10]   ={"BUY","MODIFY","CLOSE","SELL","MODIFY","CLOSE","BUY","MODIFY","CLOSE","SELL"};
   double v[10]   ={0.66,0.66,0.66,0.71,0.71,0.71,0.58,0.58,0.58,0.62};
   double px[10]  ={1.04123,1.04301,1.04211,1.04209,1.03980,1.03812,1.03814,1.04002,1.04120,1.04377};
   double sl[10]  ={1.03900,1.04123,0,1.04420,1.04209,0,1.03550,1.03814,0,1.04600};
   double tp[10]  ={1.04500,1.04500,0,1.03860,1.03860,0,1.04254,1.04254,0,1.04001};
   for(int i=0; i<10; i++)
     {
      r[i].t=t[i];
      r[i].kind=k[i];
      r[i].vol=v[i];
      r[i].px=px[i];
      r[i].sl=sl[i];
      r[i].tp=tp[i];
      r[i].ret=10009;
      r[i].note=StringFormat("row %d",i);
     }
  }
//+------------------------------------------------------------------+
//| FixedTick                                                        |
//| A tick at T0_MSC plus ms milliseconds with fixed prices and the  |
//| bid and ask flags. last and both volumes stay 0.                 |
//+------------------------------------------------------------------+
MqlTick FixedTick(const long ms,const double bid)
  {
   MqlTick t;
   ZeroMemory(t);
   t.time_msc=T0_MSC+ms;
   t.time=(datetime)(t.time_msc/1000);
   t.bid=bid;
   t.ask=bid+0.00002;
   t.flags=TICK_FLAG_BID|TICK_FLAG_ASK;
   return(t);
  }
//+------------------------------------------------------------------+
//| WriteRows                                                        |
//| Writes a decision file with the recorder: context InpFast=fast,  |
//| the given number of fixed ticks and the rows.                    |
//+------------------------------------------------------------------+
bool WriteRows(const string name,STestRow &r[],const string fast="12",const int ticks=2,const double bid0=1.04123)
  {
   CDecisionRecorder rec;
   rec.Context("InpFast",fast);
   rec.Info("version","test");
   if(!rec.Begin(DIR+name,false,SYM))
     {
      Print("cannot write ",name,": ",rec.Error());
      return(false);
     }
   for(int i=0; i<ticks; i++)
      rec.AddTick(FixedTick(500*i,(i==0) ? bid0 : 1.04124));
   for(int i=0; i<ArraySize(r); i++)
      if(!rec.RecordAt(StringToTime(r[i].t),r[i].kind,SYM,r[i].vol,r[i].px,r[i].sl,r[i].tp,r[i].ret,r[i].note))
        {
         Print("cannot record row ",i,": ",rec.Error());
         return(false);
        }
   return(rec.End());
  }
//+------------------------------------------------------------------+
//| ReadLines                                                        |
//+------------------------------------------------------------------+
int ReadLines(const string name,string &lines[])
  {
   ArrayResize(lines,0);
   int h=FileOpen(DIR+name,FILE_READ|FILE_TXT|FILE_ANSI);
   if(h==INVALID_HANDLE)
      return(0);
   while(!FileIsEnding(h))
     {
      string s=FileReadString(h);
      int n=ArraySize(lines);
      ArrayResize(lines,n+1);
      lines[n]=s;
     }
   FileClose(h);
   return(ArraySize(lines));
  }
//+------------------------------------------------------------------+
//| WriteLines                                                       |
//+------------------------------------------------------------------+
void WriteLines(const string name,const string &lines[])
  {
   int h=FileOpen(DIR+name,FILE_WRITE|FILE_TXT|FILE_ANSI);
   for(int i=0; i<ArraySize(lines); i++)
      FileWriteString(h,lines[i]+"\n");
   FileClose(h);
  }
//+------------------------------------------------------------------+
//| FindLine                                                         |
//| Index of the first line that starts with prefix, -1 if none.     |
//+------------------------------------------------------------------+
int FindLine(const string &lines[],const string prefix)
  {
   for(int i=0; i<ArraySize(lines); i++)
      if(StringFind(lines[i],prefix)==0)
         return(i);
   return(-1);
  }
//+------------------------------------------------------------------+
//| EditCopy                                                         |
//| Copies golden.csv to name with line idx replaced by text, or     |
//| removed when text is NULL.                                       |
//+------------------------------------------------------------------+
void EditCopy(const string name,const int idx,const string text)
  {
   string lines[];
   ReadLines("golden.csv",lines);
   if(text==NULL)
     {
      for(int i=idx; i<ArraySize(lines)-1; i++)
         lines[i]=lines[i+1];
      ArrayResize(lines,ArraySize(lines)-1);
     }
   else
      lines[idx]=text;
   WriteLines(name,lines);
  }
//+------------------------------------------------------------------+
//| Load                                                             |
//| Loads a test file and returns false with the error in why.       |
//+------------------------------------------------------------------+
bool Load(const string name,string &why)
  {
   CGfFile f;
   bool ok=f.Load(DIR+name,false);
   why=f.Error();
   return(ok);
  }
//+------------------------------------------------------------------+
//| Cmp                                                              |
//| Compares a test file with golden.csv.                            |
//+------------------------------------------------------------------+
ENUM_GF_VERDICT Cmp(CGoldenCompare &c,const string name,const string golden="golden.csv")
  {
   return(c.Run(DIR+golden,DIR+name,false));
  }
//+------------------------------------------------------------------+
//| TestRecorder                                                     |
//+------------------------------------------------------------------+
void TestRecorder(void)
  {
   CDecisionRecorder a;
   Check(!a.Record("BUY",SYM,0.1,1.1,0,0,0),"Record before Begin is refused");
   Check(!a.Begin(DIR+"x.csv",false,"NO_SUCH_SYMBOL_37"),"Begin with an unknown symbol is refused");
   CDecisionRecorder r;
   Check(r.Context("InpFast","12"),"a context key is accepted");
   Check(!r.Context("InpFast","13"),"a repeated context key is refused");
   Check(!r.Context("",""),"an empty context key is refused");
   Check(r.Info("version","test"),"an info key is accepted");
   Check(r.Begin(DIR+"rec.csv",false,SYM),"Begin creates the file");
   Check(!r.Context("Late","1"),"a context key after Begin is refused");
   Check(r.DataHash()=="CBF29CE484222325","the hash of no ticks is the FNV-1a offset basis",r.DataHash());
   r.AddTick(FixedTick(0,1.04123));
   Check(r.DataHash()=="0A7F9EFF6E79E321","the hash of one fixed tick matches the Python value",r.DataHash());
   r.AddTick(FixedTick(500,1.04124));
   Check(r.DataHash()=="20EC3116B9559594" && r.Ticks()==2,"the hash of two fixed ticks matches the Python value",r.DataHash());
   datetime t=StringToTime("2026.02.02 10:00:00");
   Check(!r.RecordAt(t,"buy",SYM,0.1,1.1,0,0,0),"a lower-case kind is refused");
   Check(!r.RecordAt(t,"",SYM,0.1,1.1,0,0,0),"an empty kind is refused");
   Check(!r.RecordAt(t,"ABCDEFGHIJKLMNOPQ",SYM,0.1,1.1,0,0,0),"a kind of 17 characters is refused");
   Check(r.RecordAt(t,"BUY",SYM,0.666,1.041234,1.039,1.045,10009,"a,b \"c\"\nd"),"a row is written");
   Check(r.RecordAt(t,"MY_KIND_2",SYM,0.1,1.1,0,0,0),"a second row in the same second is written");
   Check(!r.RecordAt(t-1,"BUY",SYM,0.1,1.1,0,0,0),"a row earlier than the last one is refused");
   Check(!r.RecordAt(0,"BUY",SYM,0.1,1.1,0,0,0),"a row at time 0 is refused");
   Check(!r.RecordAt(t,"BUY","",0.1,1.1,0,0,0),"a row with an empty symbol is refused");
   double nan=MathSqrt(-1.0);
   bool ok=!r.RecordAt(t,"BUY",SYM,0.1,nan,0,0,0) && StringFind(r.Error(),"price")>=0;
   Check(ok,"a NaN price is refused",r.Error());
   ok=!r.RecordAt(t,"BUY",SYM,1e40,1.1,0,0,0) && StringFind(r.Error(),"volume")>=0;
   Check(ok,"a volume that prints with more than 32 characters is refused",r.Error());
   Check(r.Rows()==2,"two rows are counted");
   Check(r.End(),"End closes the file");
   Check(!r.End(),"a second End does nothing");
   Check(!r.RecordAt(t+60,"BUY",SYM,0.1,1.1,0,0,0),"Record after End is refused");
   CGfFile f;
   Check(f.Load(DIR+"rec.csv",false),"the recorded file loads",f.Error());
   SGfRow a0,a1;
   f.Row(0,a0);
   f.Row(1,a1);
   Check(a0.price_text=="1.04123" && a0.sl_text=="1.03900","prices are printed with the symbol's digits",a0.price_text);
   Check(a0.volume_text=="0.67","the volume is printed with the digits of the volume step",a0.volume_text);
   Check(a0.note=="a b  c  d","commas, quotes and line breaks in a note become spaces","'"+a0.note+"'");
   Check(a0.seq==0 && a1.seq==1,"seq counts the rows of one second");
   Check(f.Ticks()==2 && f.DataHash()=="20EC3116B9559594","the #end line carries the tick count and hash");
   string v;
   Check(f.Context("symbol",v) && v==SYM,"Begin adds the symbol as context");
   Check(f.Context("period",v) && f.Context("deposit",v) && f.Context("mode",v),"Begin adds period, deposit and mode");
   Check(f.Info("program",v) && f.Info("version",v) && v=="test","program and version are info lines");
   Check(f.Context("build",v) && v==IntegerToString(TerminalInfoInteger(TERMINAL_BUILD)) && !f.Info("build",v),
         "the terminal build is context, not info");
   Check(f.Context("server",v) && f.Context("margin_mode",v),"Begin adds the server and the margin mode");
   Check(f.Context("contract_size",v) && v=="100000" && f.Context("volume_step",v) && v=="0.01",
         "Begin adds the contract size and the volume step of the symbol",v);
   Check(f.Context("swap_long",v) && f.Context("swap_short",v) && f.Context("calc_mode",v) && f.Context("stops_level",v),
         "Begin adds the swaps, the calculation mode and the stops level");
//--- Record() takes the time of the last tick, here 2026.02.02 10:00:01.500, not TimeCurrent()
   CDecisionRecorder s;
   s.Begin(DIR+"stamp.csv",false,SYM);
   s.AddTick(FixedTick(1500,1.04123));
   s.Record("BUY",SYM,0.1,1.04125,0,0,10009);
   s.End();
   CGfFile fs;
   SGfRow rs;
   Check(fs.Load(DIR+"stamp.csv",false) && fs.Row(0,rs) && rs.time==StringToTime("2026.02.02 10:00:01"),
         "Record stamps the row with the time of the last tick",TimeToString(rs.time,TIME_DATE|TIME_SECONDS));
  }
//+------------------------------------------------------------------+
//| TestLoader                                                       |
//+------------------------------------------------------------------+
void TestLoader(void)
  {
   string why,lines[];
   Check(Load("golden.csv",why),"the golden test file loads",why);
   Check(!Load("no_such_file.csv",why) && StringFind(why,"cannot open")>=0,"a missing file is refused",why);
   ReadLines("golden.csv",lines);
   int cols=FindLine(lines,"time,");
   int first=cols+1;
   int end=FindLine(lines,"#end");
   EditCopy("l_first.csv",0,"time,seq,kind");
   Check(!Load("l_first.csv",why) && StringFind(why,"line 1")>=0,"a file without the format line is refused",why);
   EditCopy("l_v2.csv",0,"#golden_file,2");
   Check(!Load("l_v2.csv",why) && StringFind(why,"not supported")>=0,"format version 2 is refused",why);
   EditCopy("l_noend.csv",end,NULL);
   Check(!Load("l_noend.csv",why) && StringFind(why,"no #end")>=0,"a file without #end is refused",why);
   EditCopy("l_rows.csv",end,"#end,rows,11,ticks,2,data,20EC3116B9559594");
   Check(!Load("l_rows.csv",why) && StringFind(why,"11 rows")>=0,"an #end row count that does not match is refused",why);
   EditCopy("l_short.csv",first+2,"2026.02.03 09:00:00,0,CLOSE,EURUSD,0.66");
   Check(!Load("l_short.csv",why) && StringFind(why,StringFormat("line %d",first+3))>=0,"a short row is refused with its line number",why);
   string row=lines[first];
   string bad=row;
   StringReplace(bad,"1.04123","1.0x123");
   EditCopy("l_num.csv",first,bad);
   Check(!Load("l_num.csv",why) && StringFind(why,"not a number")>=0,"a malformed price is refused",why);
   bad=row;
   StringReplace(bad,"2026.02.02 10:00:00","2026.02.30 10:00:00");
   EditCopy("l_time.csv",first,bad);
   Check(!Load("l_time.csv",why) && StringFind(why,"time")>=0,"an impossible date is refused",why);
   bad=row;
   StringReplace(bad,"2026.02.02 10:00:00","2026.02.07 10:00:00");
   EditCopy("l_order.csv",first,bad);
   Check(!Load("l_order.csv",why) && StringFind(why,"goes back")>=0,"rows out of time order are refused",why);
   string after[];
   ArrayCopy(after,lines);
   int na=ArraySize(after);
   ArrayResize(after,na+1);
   after[na]="2026.02.07 10:00:00,0,BUY,EURUSD,0.10,1.0,0,0,0,x";
   WriteLines("l_after.csv",after);
   Check(!Load("l_after.csv",why) && StringFind(why,"after the #end")>=0,"text after #end is refused",why);
   EditCopy("l_ctx.csv",1,lines[2]);
   Check(!Load("l_ctx.csv",why) && StringFind(why,"twice")>=0,"a context key that appears twice is refused",why);
//--- columns found by name: move the price column to the front of every line
   string moved[];
   ArrayCopy(moved,lines);
   for(int i=cols; i<end; i++)
     {
      string p[];
      int n=StringSplit(moved[i],',',p);
      if(n<10)
         continue;
      string s=p[5];
      for(int k=0; k<n; k++)
         if(k!=5)
            s+=","+p[k];
      moved[i]=s;
     }
   WriteLines("l_moved.csv",moved);
   Check(Load("l_moved.csv",why),"a file with the columns in another order loads",why);
   CGoldenCompare c;
   Check(Cmp(c,"l_moved.csv")==GF_PASS,"and compares as PASS with the golden file",c.Message());
   string noret=lines[cols];
   StringReplace(noret,",ret,",",retcode,");
   EditCopy("l_noret.csv",cols,noret);
   Check(!Load("l_noret.csv",why) && StringFind(why,"'ret' is missing")>=0,"a missing required column is refused",why);
   EditCopy("l_dup.csv",cols,lines[cols]+",kind");
   Check(!Load("l_dup.csv",why) && StringFind(why,"twice")>=0,"a column that appears twice is refused",why);
//--- the optional columns seq and note may be absent
   string slim[];
   ArrayCopy(slim,lines);
   for(int i=cols; i<end; i++)
     {
      string p[];
      int n=StringSplit(slim[i],',',p);
      if(n<10)
         continue;
      slim[i]=p[0]+","+p[2]+","+p[3]+","+p[4]+","+p[5]+","+p[6]+","+p[7]+","+p[8];
     }
   WriteLines("l_slim.csv",slim);
   Check(Load("l_slim.csv",why),"a file without the seq and note columns loads",why);
  }
//+------------------------------------------------------------------+
//| TestCompare                                                      |
//+------------------------------------------------------------------+
void TestCompare(void)
  {
   STestRow r[];
   CGoldenCompare c;
   SGfDiff d;
   string lines[];
   ReadLines("golden.csv",lines);
   int first=FindLine(lines,"time,")+1;
//--- the same decisions
   Base(r);
   WriteRows("same.csv",r);
   Check(Cmp(c,"same.csv")==GF_PASS && c.Same()==10 && c.Differences()==0,"identical files give PASS with 10 pairs");
//--- one volume changed
   Base(r);
   r[4].vol=0.72;
   WriteRows("vol.csv",r);
   Check(Cmp(c,"vol.csv")==GF_DIFF && c.Count(GF_CHANGED)==1 && c.Same()==9,"a changed volume gives one CHANGED row");
   c.Diff(0,d);
   Check(d.golden_line==first+5 && StringFind(d.detail,"volume 0.71 -> 0.72")>=0,"CHANGED names the line and the field",
         StringFormat("line %d detail %s",d.golden_line,d.detail));
//--- price tolerance, one point off
   Base(r);
   r[0].px=1.04124;
   WriteRows("px.csv",r);
   Check(Cmp(c,"px.csv")==GF_DIFF,"a price one point off is CHANGED with no tolerance");
   c.SetPriceTolerance(0.00001);
   Check(Cmp(c,"px.csv")==GF_PASS,"and PASS with a tolerance of one point");
   c.SetPriceTolerance(0.000009);
   Check(Cmp(c,"px.csv")==GF_DIFF,"and CHANGED with a tolerance just below one point");
//--- 1.04302 minus 1.04301 is 1.0000000000065512e-05 in double, a hair above one point
   Base(r);
   r[1].px=1.04302;
   WriteRows("px_up.csv",r);
   c.SetPriceTolerance(0.00001);
   Check(Cmp(c,"px_up.csv")==GF_PASS,"a one-point difference that rounds above 0.00001 is still within one point");
   c.SetPriceTolerance(0.0);
//--- one row removed: one MISSING, the later rows stay paired
   Base(r);
   STestRow m[];
   ArrayResize(m,9);
   for(int i=0,k=0; i<10; i++)
      if(i!=1)
         m[k++]=r[i];
   WriteRows("missing.csv",m);
   Check(Cmp(c,"missing.csv")==GF_DIFF && c.Count(GF_MISSING)==1 && c.Same()==9 && c.Differences()==1,
         "a removed row gives one MISSING and no shift");
//--- one row added at a new time
   STestRow e[];
   ArrayResize(e,11);
   for(int i=0,k=0; i<10; i++)
     {
      e[k++]=r[i];
      if(i==4)
        {
         e[k]=r[i];
         e[k].t="2026.02.03 20:00:00";
         e[k].kind="SELL";
         k++;
        }
     }
   WriteRows("extra.csv",e);
   Check(Cmp(c,"extra.csv")==GF_DIFF && c.Count(GF_EXTRA)==1 && c.Same()==10,"an added row gives one EXTRA and no shift");
//--- one row added inside a second that already has two rows
   ArrayResize(e,11);
   for(int i=0,k=0; i<10; i++)
     {
      if(i==3)
        {
         e[k]=r[i];
         e[k].kind="BUY";
         k++;
        }
      e[k++]=r[i];
     }
   WriteRows("extra_same.csv",e);
   Check(Cmp(c,"extra_same.csv")==GF_DIFF && c.Count(GF_EXTRA)==1 && c.Same()==10,
         "an added row inside a busy second gives one EXTRA");
//--- the kind changed
   Base(r);
   r[9].kind="BUY";
   WriteRows("kind.csv",r);
   Check(Cmp(c,"kind.csv")==GF_DIFF && c.Count(GF_MISSING)==1 && c.Count(GF_EXTRA)==1,"a changed kind gives MISSING and EXTRA");
//--- the retcode changed
   Base(r);
   r[1].ret=10016;
   WriteRows("ret.csv",r);
   Check(Cmp(c,"ret.csv")==GF_DIFF && c.Diff(0,d) && StringFind(d.detail,"ret 10009 -> 10016")>=0,"a changed retcode is CHANGED");
//--- notes are compared only on request
   Base(r);
   r[2].note="another note";
   WriteRows("note.csv",r);
   Check(Cmp(c,"note.csv")==GF_PASS,"a changed note is ignored by default");
   c.CompareNotes(true);
   Check(Cmp(c,"note.csv")==GF_DIFF,"and CHANGED when notes are compared");
   c.CompareNotes(false);
//--- a retcode change alone can be left out
   c.CompareRetcode(false);
   Check(Cmp(c,"ret.csv")==GF_PASS,"a changed retcode gives PASS when retcodes are not compared");
   c.CompareRetcode(true);
//--- two kinds swapped inside one second
   Base(r);
   STestRow tmp=r[2];
   r[2]=r[3];
   r[3]=tmp;
   WriteRows("swap.csv",r);
   Check(Cmp(c,"swap.csv")==GF_DIFF && c.Count(GF_ORDER)==1 && c.Same()==10 && c.Differences()==1,
         "two kinds swapped inside one second give one ORDER difference");
   d.detail="";
   c.Diff(0,d);
   Check(StringFind(d.detail,"golden order CLOSE EURUSD SELL EURUSD | new order SELL EURUSD CLOSE EURUSD")>=0,
         "ORDER names both orders",d.detail);
   c.CompareOrder(false);
   Check(Cmp(c,"swap.csv")==GF_PASS,"and PASS when the order is not compared");
   c.CompareOrder(true);
//--- a row of the same kind inserted in front of an equal row of the same second
   Base(r);
   ArrayResize(e,11);
   for(int i=0,k=0; i<10; i++)
     {
      if(i==3)
        {
         e[k]=r[i];
         e[k].px=1.04150;
         k++;
        }
      e[k++]=r[i];
     }
   WriteRows("same_kind.csv",e);
   bool ok=(Cmp(c,"same_kind.csv")==GF_DIFF);
   Check(ok && c.Count(GF_EXTRA)==1 && c.Count(GF_CHANGED)==0 && c.Same()==10,
         "a row of the same kind inserted in a second pairs the equal rows first and gives one EXTRA",
         StringFormat("changed %d extra %d same %d",c.Count(GF_CHANGED),c.Count(GF_EXTRA),c.Same()));
//--- context
   Base(r);
   WriteRows("ctx.csv",r,"13");
   Check(Cmp(c,"ctx.csv")==GF_CONTEXT && c.Differences()==0 && StringFind(c.Message(),"InpFast 12 -> 13")>=0,
         "a different input gives CONTEXT and no row comparison",c.Message());
   CGoldenCompare ci;
   ci.IgnoreContext("InpFast");
   Check(Cmp(ci,"ctx.csv")==GF_PASS,"an ignored context key gives PASS");
//--- data
   Base(r);
   WriteRows("data.csv",r,"12",2,1.04125);
   Check(Cmp(c,"data.csv")==GF_DATA && c.Differences()==0,"a different tick gives DATA even with the same decisions");
   WriteRows("ticks.csv",r,"12",3);
   Check(Cmp(c,"ticks.csv")==GF_DATA,"one more tick gives DATA");
   r[4].vol=0.72;
   WriteRows("data_vol.csv",r,"12",2,1.04125);
   Check(Cmp(c,"data_vol.csv")==GF_DATA && c.Count(GF_CHANGED)==1,"DATA still counts the changed rows");
   Check(StringFind(c.Message(),"1 row difference")>=0,"and the DATA message names their count",c.Message());
//--- severity: a cut file wins over a context difference
   string cut[];
   ReadLines("ctx.csv",cut);
   ArrayResize(cut,ArraySize(cut)-2);
   WriteLines("ctx_cut.csv",cut);
   Check(Cmp(c,"ctx_cut.csv")==GF_FORMAT,"FORMAT wins over CONTEXT");
//--- empty files
   STestRow none[];
   WriteRows("empty.csv",none);
   WriteRows("empty2.csv",none);
   Check(Cmp(c,"empty2.csv","empty.csv")==GF_PASS,"two files without rows give PASS");
   Base(r);
   ArrayResize(r,3);
   WriteRows("three.csv",r);
   Check(Cmp(c,"three.csv","empty.csv")==GF_DIFF && c.Count(GF_EXTRA)==3,"three rows against none give three EXTRA rows");
   Check(Cmp(c,"empty.csv","three.csv")==GF_DIFF && c.Count(GF_MISSING)==3,"none against three rows give three MISSING rows");
//--- the differences come out in time order and go to the CSV
   Base(r);
   r[1].vol=0.67;
   r[8].tp=1.05;
   WriteRows("two.csv",r);
   Cmp(c,"two.csv");
   SGfDiff d0,d1;
   Check(c.Diff(0,d0) && c.Diff(1,d1) && d0.time<d1.time,"differences are listed in time order");
   Check(c.WriteDiffCsv(DIR+"two_diff.csv",false) && ReadLines("two_diff.csv",lines)==4,"the diff CSV has a verdict line, a column line and one line per difference");
   Check(GfCount(1,"difference")=="1 difference" && GfCount(2,"difference")=="2 differences","counts use the singular for 1");
  }
//+------------------------------------------------------------------+
//| AccountReady                                                     |
//| Waits up to 60 seconds until the terminal is connected and the   |
//| account values stay the same for one second. Begin() writes the  |
//| deposit and the margin mode as context, so a file written before |
//| the login and a file written after it differ in their context.   |
//+------------------------------------------------------------------+
bool AccountReady(void)
  {
   string last="";
   for(int i=0; i<60 && !IsStopped(); i++)
     {
      string now=StringFormat("%I64d %.2f %I64d %s",AccountInfoInteger(ACCOUNT_LOGIN),
                              AccountInfoDouble(ACCOUNT_BALANCE),AccountInfoInteger(ACCOUNT_MARGIN_MODE),
                              AccountInfoString(ACCOUNT_SERVER));
      if(TerminalInfoInteger(TERMINAL_CONNECTED) && AccountInfoInteger(ACCOUNT_LOGIN)>0 && now==last)
         return(true);
      last=now;
      Sleep(1000);
     }
   return(false);
  }
//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   if(!AccountReady())
     {
      Print("TEST cannot start: the terminal is not connected to an account");
      return;
     }
   STestRow r[];
   Base(r);
   if(!WriteRows("golden.csv",r))
     {
      Print("TEST cannot write the golden test file");
      return;
     }
   TestRecorder();
   TestLoader();
   TestCompare();
   PrintFormat("TEST %d passed, %d failed",g_pass,g_fail);
  }
//+------------------------------------------------------------------+
