//+------------------------------------------------------------------+
//|                                               RunsTestReport.mqh |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Includes                                                         |
//+------------------------------------------------------------------+
#include <Math\Stat\ChiSquare.mqh>
#include <RunsTest\RunsTest.mqh>
#include <RunsTest\TradeSequence.mqh>
#include <RunsTest\StreakStats.mqh>

//+------------------------------------------------------------------+
//| Settings of one report                                           |
//+------------------------------------------------------------------+
struct SRunsReportSettings
  {
   string            title;         // first line of the report
   datetime          from;          // trades closed from this time
   datetime          to;            // up to this time
   string            symbol;        // "" for every symbol
   long              magic_from;    // -1 for no lower bound
   long              magic_to;      // -1 for no upper bound
   ENUM_BE_MODE      be_mode;       // breakeven handling
   double            be_eps;        // breakeven band, -1 = half a cent of the deposit currency
   double            alpha;         // two-sided significance level
   int               min_each;      // fewest wins and fewest losses to judge
   int               streak_k;      // losses in a row for the conditional rates
   int               shuffles;      // shuffles for the streak checks
   uint              seed;          // seed of the shuffles
   int               blocks;        // blocks for the drift test and within-block shuffles
  };

//+------------------------------------------------------------------+
//| Default settings: all history, all symbols, all magics           |
//+------------------------------------------------------------------+
void RunsReportDefaults(SRunsReportSettings &s,const string title)
  {
   s.title=title;
   s.from=0;
   s.to=TimeCurrent()+86400;
   s.symbol="";
   s.magic_from=-1;
   s.magic_to=-1;
   s.be_mode=BE_SKIP;
   s.be_eps=-1.0;
   s.alpha=0.05;
   s.min_each=10;
   s.streak_k=3;
   s.shuffles=10000;
   s.seed=12345;
   s.blocks=5;
  }

//+------------------------------------------------------------------+
//| Win rate of consecutive blocks and a chi-square test of equality |
//+------------------------------------------------------------------+
double BlockWinRates(const bool &seq[],const int blocks,double &rates[],double &chi2)
  {
   int n=ArraySize(seq);
   chi2=0.0;
   ArrayResize(rates,0);
   if(blocks<2 || n<2*blocks)
      return(1.0);
   ArrayResize(rates,blocks);
   int wins=0;
   for(int i=0; i<n; i++)
      if(seq[i])
         wins++;
   double pool=(double)wins/n;
   if(pool<=0.0 || pool>=1.0)
      return(1.0);
//--- 2 x blocks table: (wins - expected)^2 / (size * p * (1 - p)) summed
   for(int b=0; b<blocks; b++)
     {
      int lo=CStreakStats::BlockStart(b,n,blocks);
      int hi=CStreakStats::BlockStart(b+1,n,blocks);
      int w=0;
      for(int i=lo; i<hi; i++)
         if(seq[i])
            w++;
      int size=hi-lo;
      rates[b]=(double)w/size;
      chi2+=MathPow(w-size*pool,2)/(size*pool*(1.0-pool));
     }
   int err=0;
   return(MathCumulativeDistributionChiSquare(chi2,blocks-1.0,false,false,err));
  }

//+------------------------------------------------------------------+
//| One conditional rate as a report line                            |
//+------------------------------------------------------------------+
string RateLine(const string label,const SRateCheck &r,const string unit)
  {
   if(r.n==0)
      return(label+": no such trades");
   return(StringFormat("%s: loss rate %.1f%% (%d %s), shuffled %.1f%% (95%% range %.1f-%.1f%%), p %.3f",
                       label,100.0*r.observed,r.n,unit,100.0*r.shuffled,
                       100.0*r.lo,100.0*r.hi,r.p));
  }

//+------------------------------------------------------------------+
//| Load the history, run all checks and print the report            |
//+------------------------------------------------------------------+
bool RunsTestPrintReport(const SRunsReportSettings &s)
  {
   CTradeSequence trades;
   CRunsTest      test;
   CStreakStats   streaks;
   bool           seq[];
//--- history to sequence
   trades.SetBreakevenMode(s.be_mode);
   trades.SetBreakevenEps(s.be_eps);
   if(!trades.LoadFromHistory(s.from,s.to,s.symbol,s.magic_from,s.magic_to))
     {
      PrintFormat("Runs test: HistorySelect failed, error %d",GetLastError());
      return(false);
     }
   int n=trades.Build(seq);
//--- the checks
   test.SetAlpha(s.alpha);
   test.SetMinEach(s.min_each);
   test.Run(seq);
   streaks.Analyse(seq,s.streak_k,s.shuffles,s.seed,s.blocks);
   double rates[],chi2=0.0;
   double drift_p=BlockWinRates(seq,s.blocks,rates,chi2);
   SRateCheck after,first;
   streaks.After(after);
   streaks.First(first);
//--- report
   PrintFormat("=== Runs test: %s ===",s.title);
   PrintFormat("Filter: symbol %s, magic %I64d to %I64d, closed %s to %s",
               s.symbol=="" ? "any" : s.symbol,s.magic_from,s.magic_to,
               TimeToString(s.from,TIME_DATE|TIME_SECONDS),TimeToString(s.to,TIME_DATE|TIME_SECONDS));
   PrintFormat("Trades %d (wins %d, losses %d), breakeven %d (%s, |net| <= %.4f), open at the end %d",
               n,test.Wins(),test.Losses(),trades.Breakeven(),
               EnumToString(s.be_mode),trades.BreakevenEps(),trades.StillOpen());
   PrintFormat("Runs %d, expected %.1f, Z %.2f",test.Runs(),test.ExpectedRuns(),test.Z());
   PrintFormat("Exact p: fewer runs %.4f, more runs %.4f, two-sided %.4f (normal %.4f)",
               test.PLow(),test.PHigh(),test.PTwoSided(),test.PTwoSidedNormal());
   PrintFormat("Verdict at alpha %.2f: %s",s.alpha,test.VerdictText());
   PrintFormat("Longest losing streak %d, shuffles with one as long: p %.3f (%d shuffles)",
               streaks.LongestLoss(),streaks.LongestLossP(),streaks.Shuffles());
   Print(RateLine(StringFormat("After %d or more losses in a row",streaks.K()),after,"trades"));
   Print(RateLine(StringFormat("First trade after exactly %d losses",streaks.K()),first,"streaks"));
   string list="";
   for(int b=0; b<ArraySize(rates); b++)
      list+=StringFormat("%s%.1f%%",b==0 ? "" : " ",100.0*rates[b]);
   if(ArraySize(rates)>0)
      PrintFormat("Win rate in %d blocks: %s, chi-square %.2f, p %.3f",
                  ArraySize(rates),list,chi2,drift_p);
   if(streaks.Blocks()>0)
      PrintFormat("Within-block shuffles (%d blocks): runs p %.3f, streak p %.3f, after p %.3f, first p %.3f",
                  streaks.Blocks(),streaks.BlockRunsP(),streaks.BlockStreakP(),
                  streaks.BlockAfterP(),streaks.BlockFirstP());
   return(true);
  }

//+------------------------------------------------------------------+
//| Write every buy and sell deal to a CSV in the common Files folder|
//+------------------------------------------------------------------+
bool RunsTestExportDeals(const string file)
  {
   if(!HistorySelect(0,TimeCurrent()+86400))
      return(false);
//--- the common folder survives the end of a tester run
   int h=FileOpen(file,FILE_WRITE|FILE_CSV|FILE_ANSI|FILE_COMMON,',');
   if(h==INVALID_HANDLE)
     {
      PrintFormat("Runs test: cannot write %s, error %d",file,GetLastError());
      return(false);
     }
   FileWrite(h,"ticket","position","time_msc","type","entry","volume",
             "profit","swap","commission","fee","magic","symbol");
   int total=HistoryDealsTotal();
   for(int i=0; i<total; i++)
     {
      ulong ticket=HistoryDealGetTicket(i);
      if(ticket==0)
         continue;
      FileWrite(h,(long)ticket,
                HistoryDealGetInteger(ticket,DEAL_POSITION_ID),
                HistoryDealGetInteger(ticket,DEAL_TIME_MSC),
                HistoryDealGetInteger(ticket,DEAL_TYPE),
                HistoryDealGetInteger(ticket,DEAL_ENTRY),
                DoubleToString(HistoryDealGetDouble(ticket,DEAL_VOLUME),8),
                DoubleToString(HistoryDealGetDouble(ticket,DEAL_PROFIT),8),
                DoubleToString(HistoryDealGetDouble(ticket,DEAL_SWAP),8),
                DoubleToString(HistoryDealGetDouble(ticket,DEAL_COMMISSION),8),
                DoubleToString(HistoryDealGetDouble(ticket,DEAL_FEE),8),
                HistoryDealGetInteger(ticket,DEAL_MAGIC),
                HistoryDealGetString(ticket,DEAL_SYMBOL));
     }
   FileClose(h);
   PrintFormat("Runs test: %d deals written to Common\\Files\\%s",total,file);
   return(true);
  }
//+------------------------------------------------------------------+
