//+------------------------------------------------------------------+
//|                                          PropChallengeStats.mqh  |
//|   Turns a Strategy Tester run into a prop-challenge pass rate    |
//+------------------------------------------------------------------+
#property strict

//+------------------------------------------------------------------+
//| One set of challenge rules                                       |
//+------------------------------------------------------------------+
struct SChallengeRules
  {
   string            name;
   double            daily_pct;     // daily loss limit, % of the day-start equity
   double            dd_pct;        // maximum drawdown, % of initial or of the peak
   bool              trailing;      // true = drawdown floor follows the highest close
   double            target_pct;    // profit target, % of initial
   int               max_days;      // trading days allowed (0 = unlimited)
  };

//+------------------------------------------------------------------+
//| Result of checking one equity path against one rule set          |
//+------------------------------------------------------------------+
enum ENUM_CHALLENGE_OUTCOME
  {
   CH_PASSED=0,
   CH_DAILY_BREACH=1,
   CH_DD_BREACH=2,
   CH_TIMEOUT=3
  };

//+------------------------------------------------------------------+
//| CPropChallengeStats                                              |
//+------------------------------------------------------------------+
class CPropChallengeStats
  {
private:
   double            m_initial;
   double            m_close[];     // equity at the end of each day
   double            m_low[];       // lowest equity seen during each day
   long              m_day;         // index of the current day (days since 1970)
   uint              m_rand;        // state of the random generator

   double            Random(void);
   ENUM_CHALLENGE_OUTCOME Check(const double &close[],const double &low[],const int days,
                                  const SChallengeRules &rules,int &days_used) const;

public:
                     CPropChallengeStats(void) : m_initial(0.0),m_day(-1),m_rand(1) {}
   void              Init(void);
   void              OnTick(void);
   int               Days(void) const { return ArraySize(m_close); }
   ENUM_CHALLENGE_OUTCOME Historical(const SChallengeRules &rules,int &days_used) const;
   double            PassRate(const SChallengeRules &rules,const int simulations,const uint seed);
   void              Report(const SChallengeRules &rules[],const int simulations);
  };

//+------------------------------------------------------------------+
//| Simple linear congruential generator: repeatable results         |
//+------------------------------------------------------------------+
double CPropChallengeStats::Random(void)
  {
   m_rand=m_rand*1664525+1013904223;
   return((double)(m_rand>>8)/16777216.0);   // [0,1)
  }

//+------------------------------------------------------------------+
void CPropChallengeStats::Init(void)
  {
   m_initial=AccountInfoDouble(ACCOUNT_EQUITY);
   ArrayResize(m_close,0,512);
   ArrayResize(m_low,0,512);
   m_day=-1;
  }

//+------------------------------------------------------------------+
//| Record the day's closing and lowest equity                       |
//+------------------------------------------------------------------+
void CPropChallengeStats::OnTick(void)
  {
   double equity=AccountInfoDouble(ACCOUNT_EQUITY);
   long   day   =(long)(TimeCurrent()/86400);
   if(day!=m_day)
     {
      int n=ArraySize(m_close);
      ArrayResize(m_close,n+1,512);
      ArrayResize(m_low,n+1,512);
      m_close[n]=equity;
      m_low[n]  =equity;
      m_day=day;
      return;
     }
   int last=ArraySize(m_close)-1;
   m_close[last]=equity;
   if(equity<m_low[last])
      m_low[last]=equity;
  }

//+------------------------------------------------------------------+
//| Walk an equity path day by day and apply the rules               |
//+------------------------------------------------------------------+
ENUM_CHALLENGE_OUTCOME CPropChallengeStats::Check(const double &close[],const double &low[],const int days,
                                                  const SChallengeRules &rules,int &days_used) const
  {
   double start =m_initial;   // equity at the start of the current day
   double peak  =m_initial;
   double target=m_initial*(1.0+rules.target_pct/100.0);
   for(int d=0; d<days; d++)
     {
      days_used=d+1;
      double daily_floor=start*(1.0-rules.daily_pct/100.0);
      double dd_base    =rules.trailing ? peak : m_initial;
      double dd_floor   =dd_base-m_initial*rules.dd_pct/100.0;
      if(low[d]<=daily_floor)
         return(CH_DAILY_BREACH);
      if(low[d]<=dd_floor)
         return(CH_DD_BREACH);
      if(close[d]>=target)
         return(CH_PASSED);
      if(rules.max_days>0 && days_used>=rules.max_days)
         return(CH_TIMEOUT);
      start=close[d];
      if(close[d]>peak)
         peak=close[d];
     }
   return(CH_TIMEOUT);
  }

//+------------------------------------------------------------------+
//| The tester run itself, checked against one rule set              |
//+------------------------------------------------------------------+
ENUM_CHALLENGE_OUTCOME CPropChallengeStats::Historical(const SChallengeRules &rules,int &days_used) const
  {
   days_used=0;
   return(Check(m_close,m_low,ArraySize(m_close),rules,days_used));
  }

//+------------------------------------------------------------------+
//| Bootstrap: rebuild many paths from the recorded days             |
//+------------------------------------------------------------------+
double CPropChallengeStats::PassRate(const SChallengeRules &rules,const int simulations,const uint seed)
  {
   int n=ArraySize(m_close);
   if(n<5 || simulations<=0)
      return(0.0);
//--- each day as a pair of relative moves: close change and intraday dip
   double ret[],dip[];
   ArrayResize(ret,n);
   ArrayResize(dip,n);
   double prev=m_initial;
   for(int i=0; i<n; i++)
     {
      ret[i]=m_close[i]/prev-1.0;
      dip[i]=m_low[i]/prev-1.0;
      prev=m_close[i];
     }
   int len=(rules.max_days>0) ? rules.max_days : n;
   double close[],low[];
   ArrayResize(close,len);
   ArrayResize(low,len);
   m_rand=seed;
   int passed=0;
   for(int s=0; s<simulations; s++)
     {
      double eq=m_initial;
      for(int d=0; d<len; d++)
        {
         int k=(int)(Random()*n);
         if(k>=n)
            k=n-1;
         low[d]  =eq*(1.0+dip[k]);
         eq      =eq*(1.0+ret[k]);
         close[d]=eq;
        }
      int used=0;
      if(Check(close,low,len,rules,used)==CH_PASSED)
         passed++;
     }
   return(100.0*passed/simulations);
  }

//+------------------------------------------------------------------+
//| Print a comparison table to the tester journal                   |
//+------------------------------------------------------------------+
void CPropChallengeStats::Report(const SChallengeRules &rules[],const int simulations)
  {
   string outcome[]={"passed","daily limit breached","drawdown breached","target not reached"};
   PrintFormat("PropChallengeStats: %d trading days recorded, initial equity %.2f",ArraySize(m_close),m_initial);
   for(int i=0; i<ArraySize(rules); i++)
     {
      int used=0;
      ENUM_CHALLENGE_OUTCOME h=Historical(rules[i],used);
      double rate=PassRate(rules[i],simulations,12345+i);
      PrintFormat("  %-28s historical: %-20s after %3d days | bootstrap pass rate %5.1f%% (%d paths)",
                  rules[i].name,outcome[(int)h],used,rate,simulations);
     }
  }
//+------------------------------------------------------------------+
