//+------------------------------------------------------------------+
//|                                                   TickLoader.mqh |
//+------------------------------------------------------------------+
#ifndef TICKLOADER_MQH
#define TICKLOADER_MQH

//+------------------------------------------------------------------+
//| CTickLoader                                                      |
//| Wraps CopyTicksRange() to load raw ticks for a session window,   |
//| preferring real trade ticks and falling back to all ticks only   |
//| when the absence of trade ticks is confirmed (zero ticks and no  |
//| error), for example on forex symbols.                            |
//+------------------------------------------------------------------+
class CTickLoader
  {
private:
   int               m_last_error;
   int               m_last_count;
   bool              m_partial;
   bool              m_all_ticks;

public:
                     CTickLoader(void);
                    ~CTickLoader(void);
   int               Load(const string symbol, const datetime from, const datetime to, MqlTick &ticks[]);
   int               LastError(void);
   bool              IsPartial(void);
   bool              UsedAllTicks(void);
  };

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CTickLoader::CTickLoader(void)
  {
   m_last_error = 0;
   m_last_count = 0;
   m_partial    = false;
   m_all_ticks  = false;
  }

//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CTickLoader::~CTickLoader(void)
  {
  }

//+-------------------------------------------------------------------+
//| Load                                                              |
//| Loads every tick for the symbol between from and to using         |
//| CopyTicksRange() with COPY_TICKS_TRADE first. COPY_TICKS_ALL is   |
//| requested only when the absence of trade ticks is confirmed: the  |
//| trade request returned zero ticks and reported no error. A failed |
//| request is never answered with a different tick type; 4403 and    |
//| 4407 are retried in the original mode, with or without ticks      |
//| returned. Only 4407 escalates the buffer to buffer_cap, since a   |
//| 4403 timeout is a synchronization problem, not a space problem.   |
//| UsedAllTicks() reports which mode produced the data.              |
//| The destination array is explicitly pre-sized rather than relying |
//| on dynamic-array auto-growth, which can stall on some terminal    |
//| builds and return ERR_HISTORY_SMALL_BUFFER (4407). The normal     |
//| pre-size is the previous call's tick count plus 50% headroom,     |
//| never below buffer_floor. ::ResetLastError() runs immediately     |
//| before every CopyTicksRange() call so m_last_error can never be a |
//| stale code from an earlier call. Returns the tick count actually  |
//| loaded; call IsPartial() afterward to find out whether it should  |
//| be trusted as the complete session.                               |
//|                                                                   |
//| Constants are engineering defaults, not tuned values:             |
//|  max_retries 5 x retry_delay 500 ms bounds the wait at about 2.5 s|
//|  buffer_floor is only an initial capacity, not a limit            |
//|  buffer_cap is a memory ceiling, used only after a 4407           |
//+-------------------------------------------------------------------+
int CTickLoader::Load(const string symbol, const datetime from, const datetime to, MqlTick &ticks[])
  {
   long      from_msc      = (long)from * 1000;
   long      to_msc        = (long)to   * 1000;
   int       copied        = 0;
   const int max_retries   = 5;
   const int retry_delay   = 500;      // milliseconds
   const int buffer_cap    = 4000000;  // ceiling, only used after a 4407 retry
   const int buffer_floor  = 50000;    // minimum initial capacity

   m_partial   = false;
   m_all_ticks = false;

//--- normal pre-size: previous known count plus 50% headroom, or the floor
   int pre_size = m_last_count + m_last_count / 2;
   if(pre_size < buffer_floor)
      pre_size = buffer_floor;

   for(int attempt = 0; attempt < max_retries; attempt++)
     {
      ::ArrayResize(ticks, pre_size);
      m_all_ticks = false;

      //--- always request real trade ticks first
      ::ResetLastError();
      copied = ::CopyTicksRange(symbol, ticks, COPY_TICKS_TRADE, from_msc, to_msc);
      m_last_error = ::GetLastError();

      //--- fall back only when the absence of trade ticks is confirmed:
      //--- nothing returned and no error reported
      if(copied == 0 && m_last_error == 0)
        {
         ::ArrayResize(ticks, pre_size);
         ::ResetLastError();
         copied = ::CopyTicksRange(symbol, ticks, COPY_TICKS_ALL, from_msc, to_msc);
         m_last_error = ::GetLastError();
         m_all_ticks  = true;
        }

      //--- a result that exactly fills the offered buffer may have been
      //--- truncated at the buffer's edge rather than genuinely ending there
      if(copied > 0 && copied == pre_size)
         m_partial = true;

      //--- success or any non-transient error ends the loop
      if(m_last_error != 4403 && m_last_error != 4407)
         break;

      //--- 4403 and 4407 are retried in the same tick mode, even when some
      //--- ticks came back with them. Only 4407 escalates the buffer.
      m_partial = true;
      if(m_last_error == 4407)
         pre_size = buffer_cap;
      ::Sleep(retry_delay);
     }

   if(copied < 0)
      copied = 0;

//--- partial data accepted after exhausting all retries: the caller
//--- still gets the ticks (some data beats none), but m_partial stays
//--- true so it is not displayed or logged as a complete session
   if(copied > 0 && (m_last_error == 4403 || m_last_error == 4407))
      m_partial = true;

   m_last_count = copied;

//--- trim the array back down to the actual tick count
   ::ArrayResize(ticks, copied);

   return(copied);
  }

//+------------------------------------------------------------------+
//| LastError                                                        |
//| Returns the error code captured from the most recent Load call,  |
//| for diagnostics when the caller wants to log a loading failure.  |
//+------------------------------------------------------------------+
int CTickLoader::LastError(void)
  {
   return(m_last_error);
  }

//+------------------------------------------------------------------+
//| IsPartial                                                        |
//| Returns true when the most recent Load() result should not be    |
//| treated as a complete, trustworthy session: a retryable error    |
//| (4403/4407) occurred at least once, or the final copy exactly    |
//| filled the pre-sized buffer. This is a best-effort signal, not a |
//| guarantee -- a fixed buffer_cap can still silently truncate a    |
//| session large enough to fill it on the very first attempt.       |
//+------------------------------------------------------------------+
bool CTickLoader::IsPartial(void)
  {
   return(m_partial);
  }

//+------------------------------------------------------------------+
//| UsedAllTicks                                                     |
//| Returns true when the most recent Load() result came from        |
//| COPY_TICKS_ALL, meaning every tick counts as one unit of volume. |
//+------------------------------------------------------------------+
bool CTickLoader::UsedAllTicks(void)
  {
   return(m_all_ticks);
  }

#endif // TICKLOADER_MQH
//+------------------------------------------------------------------+