//+------------------------------------------------------------------+
//|                                           BenchNaiveVsDirect.mq5 |
//+------------------------------------------------------------------+
#property script_show_inputs

#include <VolumeProfileAggregator/SessionWindow.mqh>
#include <VolumeProfileAggregator/TickLoader.mqh>
#include <VolumeProfileAggregator/VolumeProfile.mqh>

input int InpTargetBins = 200;   // approximate bin count
input int InpRuns       = 5;     // timed repetitions per method
input int InpMaxWaitRounds = 15; // tick sync attempts, 2 s apart

//+------------------------------------------------------------------+
//| TickVolume: same volume rule as CVolumeProfile::AddTick          |
//+------------------------------------------------------------------+
double TickVolume(const MqlTick &tick)
  {
   double vol = (tick.volume_real > 0.0) ? tick.volume_real : 1.0;
   if(tick.volume > 0 && tick.volume_real <= 0.0)
      vol = (double)tick.volume;
   return(vol);
  }

//+------------------------------------------------------------------+
//| NaiveAggregate: for every tick, test every bin boundary          |
//+------------------------------------------------------------------+
void NaiveAggregate(const MqlTick &ticks[], const int count, const double price_min,
                    const double bin_size, const int bins, double &out[])
  {
   ::ArrayResize(out, bins);
   ::ArrayInitialize(out, 0.0);
   for(int i = 0; i < count; i++)
     {
      double p = ResolveTickPrice(ticks[i]);
      if(p <= 0.0)
         continue;
      for(int j = 0; j < bins; j++)
        {
         double lo = price_min + (j - 0.5) * bin_size;
         double hi = price_min + (j + 0.5) * bin_size;
         bool   in_bin = (j == 0 || p >= lo) && (j == bins - 1 || p < hi);
         if(in_bin)
           {
            out[j] += TickVolume(ticks[i]);
            break;
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   CSessionWindow g_session;
   CTickLoader    loader;
   datetime from = 0, to = 0;
   if(!g_session.Resolve(from, to))
      return;

//--- a script runs once, so it has no timer to poll the terminal's tick
//--- sync the way the EA does. Ask repeatedly (each Load() already retries
//--- internally) until ticks arrive or the wait budget runs out.
   MqlTick ticks[];
   int count = 0;
   for(int wait = 0; wait < InpMaxWaitRounds; wait++)
     {
      count = loader.Load(::_Symbol, from, to, ticks);
      if(count > 0)
         break;
      ::PrintFormat("Bench: no ticks yet (round %d of %d), last error %d",
                    wait + 1, InpMaxWaitRounds, loader.LastError());
      ::Sleep(2000);
     }
   if(count <= 0)
     {
      ::Print("Bench: no ticks loaded, last error ", loader.LastError());
      return;
     }
   if(loader.IsPartial())
      ::Print("Bench: warning, tick load flagged partial");

   double price_min = 0.0, price_max = 0.0;
   bool   have = false;
   for(int i = 0; i < count; i++)
     {
      double p = ResolveTickPrice(ticks[i]);
      if(p <= 0.0)
         continue;
      if(!have)
        {
         price_min = p;
         price_max = p;
         have = true;
        }
      if(p < price_min)
         price_min = p;
      if(p > price_max)
         price_max = p;
     }
   if(!have)
      return;

   double step = ::SymbolInfoDouble(::_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if(step <= 0.0)
      step = ::SymbolInfoDouble(::_Symbol, SYMBOL_POINT);
   double bin_size = ::MathMax(1.0, ::MathCeil((price_max - price_min) / InpTargetBins / step)) * step;

   CVolumeProfile profile;
   profile.Initialize(price_min, price_max, bin_size);
   int bins = profile.BinCount();

   ::PrintFormat("Bench env: build=%d cores=%d ram_mb=%d x64=%s os=%s",
                 (int)::TerminalInfoInteger(TERMINAL_BUILD),
                 (int)::TerminalInfoInteger(TERMINAL_CPU_CORES),
                 (int)::TerminalInfoInteger(TERMINAL_MEMORY_PHYSICAL),
                 ::TerminalInfoInteger(TERMINAL_X64) ? "true" : "false",
                 ::TerminalInfoString(TERMINAL_OS_VERSION));
   ::PrintFormat("Bench data: symbol=%s from=%s to=%s ticks=%d bins=%d bin_size=%.5f",
                 ::_Symbol, ::TimeToString(from, TIME_DATE | TIME_SECONDS),
                 ::TimeToString(to, TIME_DATE | TIME_SECONDS), count, bins, bin_size);

   double naive[];
   for(int run = 0; run < InpRuns; run++)
     {
      ulong t0 = ::GetMicrosecondCount();
      NaiveAggregate(ticks, count, price_min, bin_size, bins, naive);
      double naive_ms = (::GetMicrosecondCount() - t0) / 1000.0;

      profile.Initialize(price_min, price_max, bin_size);
      ulong t1 = ::GetMicrosecondCount();
      profile.Aggregate(ticks, count);
      double direct_ms = (::GetMicrosecondCount() - t1) / 1000.0;

      int mismatch = 0;
      for(int j = 0; j < bins; j++)
         if(::MathAbs(naive[j] - profile.BinVolume(j)) > 1e-6)
            mismatch++;

      ::PrintFormat("Bench run %d: naive_ms=%.3f direct_ms=%.3f mismatched_bins=%d",
                    run + 1, naive_ms, direct_ms, mismatch);
     }
  }
//+------------------------------------------------------------------+