async def _authenticate(self, ws: WSAssistant):
        """
        Authenticates user to websocket
        """
        try:
            auth_payload: Dict[str,
                               Any] = self._bitmart_auth.get_ws_auth_payload(
                                   bitmart_utils.get_ms_timestamp())
            ws_message: WSRequest = WSRequest(auth_payload)

            await ws.send(ws_message)
            ws_response = await ws.receive()

            auth_resp: Dict[str, Any] = ws_response.data

            if "errorCode" in auth_resp.keys():
                self.logger().error(
                    f"WebSocket login errored with message: {auth_resp['errorMessage']}",
                    exc_info=True)
                raise ConnectionError
        except asyncio.CancelledError:
            raise
        except Exception:
            self.logger().error(
                "Error occurred when authenticating to user stream.",
                exc_info=True)
            raise
    async def _authenticate(self, ws: websockets.WebSocketClientProtocol):
        """
        Authenticates user to websocket
        """
        try:
            auth_payload: Dict[str,
                               Any] = self._bitmart_auth.get_ws_auth_payload(
                                   bitmart_utils.get_ms_timestamp())
            await ws.send(
                ujson.dumps(auth_payload, escape_forward_slashes=False))
            auth_resp = await ws.recv()
            auth_resp: Dict[str, Any] = ujson.loads(auth_resp)

            if "errorCode" in auth_resp:
                self.logger().error(
                    f"WebSocket login errored with message: {auth_resp['errorMessage']}",
                    exc_info=True)
                raise
        except asyncio.CancelledError:
            raise
        except Exception:
            self.logger().info(
                "Error occurred when authenticating to user stream. ",
                exc_info=True)
            raise
示例#3
0
    async def _api_request(self,
                           method: str,
                           path_url: str,
                           params: Optional[Dict[str, Any]] = None,
                           auth_type: str = None) -> Dict[str, Any]:
        """
        Sends an aiohttp request and waits for a response.
        :param method: The HTTP method, e.g. get or post
        :param path_url: The path url or the API end point
        :param params: Request parameters
        :param auth_type: Type of Authorization header to send in request, from {"SIGNED", "KEYED", None}
        :returns A response in json format.
        """
        params = params or {}
        async with self._throttler.execute_task(path_url):
            url = f"{CONSTANTS.REST_URL}/{path_url}"

            headers = self._bitmart_auth.get_headers(
                bitmart_utils.get_ms_timestamp(), params, auth_type)

            if method == "get":
                request = RESTRequest(method=RESTMethod.GET,
                                      url=url,
                                      headers=headers,
                                      params=params)
                rest_assistant = await self._get_rest_assistant()
                response = await rest_assistant.call(request=request)
            elif method == "post":
                post_json = json.dumps(params)
                request = RESTRequest(method=RESTMethod.POST,
                                      url=url,
                                      headers=headers,
                                      data=post_json)
                rest_assistant = await self._get_rest_assistant()
                response = await rest_assistant.call(request=request)
            else:
                raise NotImplementedError

            try:
                parsed_response = json.loads(await response.text())
            except Exception as e:
                raise IOError(
                    f"Error parsing data from {url}. Error: {str(e)}")
            if response.status != 200:
                raise IOError(
                    f"Error calling {url}. HTTP status is {response.status}. "
                    f"Message: {parsed_response['message']}")
            if int(parsed_response["code"]) != 1000:
                raise IOError(
                    f"{url} API call failed, error message: {parsed_response['message']}"
                )
            return parsed_response