async def websocket_connection(
            self) -> (signalr_aio.Connection, signalr_aio.hubs.Hub):
        if self._websocket_connection and self._websocket_hub:
            return self._websocket_connection, self._websocket_hub

        self._websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED,
                                                            session=None)
        self._websocket_hub = self._websocket_connection.register_hub("c2")

        trading_pairs = self._trading_pairs
        for trading_pair in trading_pairs:
            # TODO: Refactor accordingly when V3 WebSocket API is released
            # WebSocket API requires trading_pair to be in 'Quote-Base' format
            trading_pair = f"{trading_pair.split('-')[1]}-{trading_pair.split('-')[0]}"
            self.logger().info(f"Subscribed to {trading_pair} deltas")
            self._websocket_hub.server.invoke("SubscribeToExchangeDeltas",
                                              trading_pair)

            self.logger().info(f"Query {trading_pair} snapshot.")
            self._websocket_hub.server.invoke("queryExchangeState",
                                              trading_pair)

        self._websocket_connection.start()

        return self._websocket_connection, self._websocket_hub
    async def listen_for_user_stream(self, ev_loop: asyncio.AbstractEventLoop, output: asyncio.Queue):
        while True:
            try:
                self._websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED, session=None)
                self.hub = self._websocket_connection.register_hub("c3")

                await self.authenticate()
                self.hub.server.invoke("Subscribe", ["heartbeat", "order", "balance", "execution"])
                self._websocket_connection.start()

                async for raw_message in self._socket_user_stream(self._websocket_connection):
                    decode: Dict[str, Any] = self._transform_raw_message(raw_message)
                    self.logger().debug(f"Got ws message {decode}")
                    if decode.get("error") is not None:
                        self.logger().error(decode["error"])
                        continue

                    content_type = decode.get("event_type")
                    if content_type is not None:
                        if content_type in ["balance", "order", "execution"]:
                            output.put_nowait(decode)
                        elif content_type == "re-authenticate":
                            await self.authenticate()
                        elif content_type == "heartbeat":
                            self.logger().debug("WS heartbeat")
                            continue

            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error(
                    "Unexpected error with Bittrex WebSocket connection. " "Retrying after 30 seconds...", exc_info=True
                )
                await asyncio.sleep(30.0)
    async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                self._websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED, session=None)
                hub = self._websocket_connection.register_hub("c2")

                self.logger().info("Invoked GetAuthContext")
                hub.server.invoke("GetAuthContext", self._bittrex_auth.api_key)
                self._websocket_connection.start()

                async for raw_message in self._socket_user_stream(self._websocket_connection):
                    decode: Dict[str, Any] = self._transform_raw_message(raw_message)
                    if decode.get("error") is not None:
                        self.logger().error(decode["error"])
                        continue

                    if decode.get("content") is not None:
                        signature = decode["content"].get("signature")
                        content_type = decode["event_type"]
                        if signature is not None:
                            hub.server.invoke("Authenticate", self._bittrex_auth.api_key, signature)
                            continue

                        if content_type in ["uO", "uB"]:  # uB: Balance Delta, uO: Order Delta
                            order_delta: OrderBookMessage = self.order_book_class.diff_message_from_exchange(decode)
                            output.put_nowait(order_delta)

            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error(
                    "Unexpected error with Bittrex WebSocket connection. " "Retrying after 30 seconds...", exc_info=True
                )
                await asyncio.sleep(30.0)
    async def _build_websocket_connection(self) -> signalr_aio.Connection:
        websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED, session=None)
        websocket_hub = websocket_connection.register_hub("c3")

        subscription_names = [f"trade_{trading_pair}" for trading_pair in self._trading_pairs]
        subscription_names.extend([f"orderbook_{trading_pair}_25" for trading_pair in self._trading_pairs])
        websocket_hub.server.invoke("Subscribe", subscription_names)
        self.logger().info(f"Subscribed to {self._trading_pairs} deltas")

        websocket_connection.start()
        self.logger().info("Websocket connection started...")

        return websocket_connection
Exemple #5
0
    async def websocket_connection(
            self) -> (signalr_aio.Connection, signalr_aio.hubs.Hub):
        if self._websocket_connection and self._websocket_hub:
            return self._websocket_connection, self._websocket_hub

        self._websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED,
                                                            session=None)
        self._websocket_hub = self._websocket_connection.register_hub("c3")

        trading_pairs = self._trading_pairs
        for trading_pair in trading_pairs:
            self._websocket_hub.server.invoke("Subscribe",
                                              [f"orderbook_{trading_pair}_25"])
            self._websocket_hub.server.invoke("Subscribe",
                                              [f"trade_{trading_pair}"])
            self.logger().info(f"Subscribed to {trading_pair} deltas")

        self._websocket_connection.start()
        self.logger().info("Websocket connection started...")

        return self._websocket_connection, self._websocket_hub