async def subscribe_to_order_book_streams(self, trading_pairs: List[str]): try: channels = [] for pair in trading_pairs: channels.extend( [ f"{self.DIFF_CHANNEL_ID}.{crypto_com_utils.convert_to_exchange_trading_pair(pair)}.150", f"{self.TRADE_CHANNEL_ID}.{crypto_com_utils.convert_to_exchange_trading_pair(pair)}", ] ) subscription_payload = { self._ID_FIELD_NAME: get_tracking_nonce(), self._METHOD_FIELD_NAME: self._SUBSCRIPTION_OPERATION, self._NONCE_FIELD_NAME: get_ms_timestamp(), self._PARAMS_FIELD_NAME: {self._CHANNEL_PARAMS: channels}, } await self.send_request(subscription_payload) except asyncio.CancelledError: raise except Exception: self.logger().error( "Unexpected error occurred subscribing to order book trading and delta streams...", exc_info=True ) raise
async def _emit(self, method: str, data: Optional[Any] = {}) -> int: id = self.generate_request_id() nonce = get_ms_timestamp() payload = { "id": id, "method": method, "nonce": nonce, "params": copy.deepcopy(data), } if self._isPrivate: auth = self._auth.generate_auth_dict( method, request_id=id, nonce=nonce, data=data, ) payload["sig"] = auth["sig"] payload["api_key"] = auth["api_key"] await self._client.send(ujson.dumps(payload)) return id
async def _api_request(self, method: str, path_url: str, params: Dict[str, Any] = {}, is_auth_required: bool = False) -> 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 is_auth_required: Whether an authentication is required, when True the function will add encrypted signature to the request. :returns A response in json format. """ async with self._throttler.execute_task(path_url): url = f"{CONSTANTS.REST_URL}/{path_url}" client = await self._http_client() if is_auth_required: request_id = crypto_com_utils.RequestId.generate_request_id() data = {"params": params} params = self._crypto_com_auth.generate_auth_dict( path_url, request_id, crypto_com_utils.get_ms_timestamp(), data) headers = self._crypto_com_auth.get_headers() else: headers = {"Content-Type": "application/json"} if method == "get": response = await client.get(url, headers=headers) elif method == "post": post_json = json.dumps(params) response = await client.post(url, data=post_json, headers=headers) 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 fetching data from {url}. HTTP status is {response.status}. " f"Message: {parsed_response}") if parsed_response["code"] != 0: raise IOError( f"{url} API call failed, response: {parsed_response}") # print(f"REQUEST: {method} {path_url} {params}") # print(f"RESPONSE: {parsed_response}") return parsed_response
async def authenticate(self): request_id = get_tracking_nonce() nonce = get_ms_timestamp() auth = self._auth.generate_auth_dict( self.AUTH_REQUEST, request_id=request_id, nonce=nonce, ) auth_payload = { self._ID_FIELD_NAME: request_id, self._METHOD_FIELD_NAME: self.AUTH_REQUEST, self._NONCE_FIELD_NAME: nonce, self._SIGNATURE_FIELD_NAME: auth["sig"], self._API_KEY_FIELD_NAME: auth["api_key"], } await self.send_request(auth_payload)
async def subscribe_to_user_streams(self): try: channels = self._USER_CHANNEL_LIST subscription_payload = { self._ID_FIELD_NAME: get_tracking_nonce(), self._METHOD_FIELD_NAME: self._SUBSCRIPTION_OPERATION, self._NONCE_FIELD_NAME: get_ms_timestamp(), self._PARAMS_FIELD_NAME: {self._CHANNEL_PARAMS: channels}, } await self.send_request(subscription_payload) self.logger().info("Successfully subscribed to user stream...") except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error occurred subscribing to user streams...", exc_info=True) raise