OrdersHistoryTotal() delay on changing history visibility in GUI

 

Is there a way to determine whether the process of toggling history visibility in GUI is complete and OrdersHistoryTotal() returns the value equal to what is visible in GUI? I need to do some calculations on the whole history at the beginning. Since I don't know what range of history is visible at the moment, I switch to All History via WinAPI, but it takes some time for this process to finalise and it happens asynchronously. I can delay the calculation for an arbitrary number of ms, but I'm looking for a more robust and elegant solution.


#property strict
#property indicator_chart_window

#include <WinUser32.mqh>

#import "user32.dll"
int GetAncestor(int hwnd, uint flags);
#import

#import "ntdll.dll"
int  RtlGetLastWin32Error();
#import

#define uSeconds2String(x) StringFormat("%d.%03d", (uint)(x / 1000000), (x % 1000000) / 1000)

#define GA_ROOT       (2)
#define MT4_WMCMD_ALL_HISTORY     33058
#define HANDLE_ROOT GetAncestor((int)ChartGetInteger(0,CHART_WINDOW_HANDLE,0),GA_ROOT)

int histtotal = 0;
bool stop = false;
//---
int OnInit()
  {
   Comment("");

   EventSetMillisecondTimer(100);

   histtotal = OrdersHistoryTotal();

   if(IsDllsAllowed())
     {
      ResetLastError();
      if(!SendMessageW(HANDLE_ROOT, WM_COMMAND, MT4_WMCMD_ALL_HISTORY, 0))
         PrintFormat("Error accessing whole history: %i", RtlGetLastWin32Error());
     }
   else
      Print("DLLs not allowed");

   return(INIT_SUCCEEDED);
  }
//---
void OnTimer()
  {
   static long cnt = 0;
   if(stop)
      return;
   if(!(cnt % 50))
      Comment("");
   int histtotalnow = OrdersHistoryTotal();
   string mess = StringFormat("orders: %i | uptime: %s\n",
                              histtotalnow,
                              uSeconds2String(GetMicrosecondCount())
                             );

   Comment(ChartGetString(0, CHART_COMMENT) + mess);
   if(histtotal != histtotalnow)
     {
      Comment(ChartGetString(0, CHART_COMMENT) + "== HISTORY CHANGE ==");
      stop = true;
     }
   cnt++;
  }
//---
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   return(rates_total);
  }