WebSocket closure and EA deinitialization issues in MT5 - EA remains connected after removal"

 
I'm experiencing problems with WebSocket closure and EA deinitialization in my MetaTrader 5 Expert Advisor. The main issues are:
  • When removing the EA from the chart or closing the chart:
  • MT5 hangs briefly
  • The Expert tab still shows the EA as connected
  • The server-side still sees the EA as registered
  • The journal tab shows the EA as removed
  • When sending an order to MT5:
  • MT5 crashes, shuts down, and disappears
  • Here are the relevant parts of my code


    void OnDeinit(const int reason)
    {
       EventKillTimer();
       Print("Deinitializing EA...");
       CloseWebSocket();
       Print("WebSocket closed. Reason: ", reason);
    }
    
    void CloseWebSocket()
    {
       if(hWebSocket != NULL)
       {
          uchar empty[];
          WinHttpWebSocketClose(hWebSocket, WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS, empty, 0);
          CloseHandleWithTimeout(hWebSocket, 5000);
          hWebSocket = NULL;
       }
       
       if(hRequest != NULL)
       {
          CloseHandleWithTimeout(hRequest, 5000);
          hRequest = NULL;
       }
       
       if(hConnect != NULL)
       {
          CloseHandleWithTimeout(hConnect, 5000);
          hConnect = NULL;
       }
       
       if(hSession != NULL)
       {
          CloseHandleWithTimeout(hSession, 5000);
          hSession = NULL;
       }
       
       isConnected = false;
    }
    
    bool CloseHandleWithTimeout(long &handle, int timeoutMs)
    {
        uint startTime = GetTickCount();
        while (GetTickCount() - startTime < timeoutMs)
        {
            if (WinHttpCloseHandle(handle))
            {
                handle = 0;
                return true;
            }
            Sleep(10);
        }
        Print("Failed to close handle within timeout");
        return false;
    }
    I suspect the issue might be in how I'm handling the WebSocket closure and resource deallocation. Any insights or suggestions on how to properly close the WebSocket connection and ensure clean EA deinitialization would be greatly appreciated.