Python websockets.WebSocketClientProtocol() Examples

The following are 30 code examples of websockets.WebSocketClientProtocol(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module websockets , or try the search function .
Example #1
Source File: binance_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                trading_pairs: List[str] = await self.get_trading_pairs()
                ws_path: str = "/".join([f"{trading_pair.lower()}@trade" for trading_pair in trading_pairs])
                stream_url: str = f"{DIFF_STREAM_URL}/{ws_path}"

                async with websockets.connect(stream_url) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    async for raw_msg in self._inner_messages(ws):
                        msg = ujson.loads(raw_msg)
                        trade_msg: OrderBookMessage = BinanceOrderBook.trade_message_from_exchange(msg)
                        output.put_nowait(trade_msg)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
                                    exc_info=True)
                await asyncio.sleep(30.0) 
Example #2
Source File: kraken_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                ws_message: str = await self.get_ws_subscription_message("trade")

                async with websockets.connect(DIFF_STREAM_URL) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    await ws.send(ws_message)
                    async for raw_msg in self._inner_messages(ws):
                        msg: List[Any] = ujson.loads(raw_msg)
                        trades: List[Dict[str, Any]] = [{"pair": msg[-1], "trade": trade} for trade in msg[1]]
                        for trade in trades:
                            trade_msg: OrderBookMessage = KrakenOrderBook.trade_message_from_exchange(trade)
                            output.put_nowait(trade_msg)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
                                    exc_info=True)
                await asyncio.sleep(30.0) 
Example #3
Source File: kraken_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    if ((msg != "{\"event\":\"heartbeat\"}" and
                         "\"event\":\"systemStatus\"" not in msg and
                         "\"event\":\"subscriptionStatus\"" not in msg)):
                        yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #4
Source File: bitfinex_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _get_response(self, ws: websockets.WebSocketClientProtocol):
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    self._last_recv_time = time.time()
                    yield msg
                except asyncio.TimeoutError:
                    raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #5
Source File: bitfinex_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                ws: websockets.WebSocketClientProtocol
                async with websockets.connect(BITFINEX_WS_URI) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    payload = self._bitfinex_auth.generate_auth_payload()
                    await ws.send(json.dumps(payload))

                    async for raw_msg in self._get_response(ws):
                        transformed_msg: BitfinexOrderBookMessage = self._transform_message_from_exchange(raw_msg)
                        if transformed_msg:
                            output.put_nowait(transformed_msg)

            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error(
                    "Unexpected error with Bitfinex WebSocket connection. " "Retrying after 30 seconds...",
                    exc_info=True,
                )
                await asyncio.sleep(self.MESSAGE_TIMEOUT) 
Example #6
Source File: kucoin_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close()

    # get required data to create a websocket request 
Example #7
Source File: chromerdp.py    From chrome-prerender with MIT License 6 votes vote down vote up
def _reset(self) -> None:
        self._ws_task: Optional[Future] = None
        self._futures: Dict[int, Future] = {}
        self._callbacks: Dict[str, Callable[[Dict], Any]] = {}
        self.websocket: Optional[websockets.WebSocketClientProtocol] = None
        self._request_id: int = 0

        self._render_future = self.loop.create_future()
        self._mhtml = MHTML()

        self._requests_sent: int = 0
        self._responses_received: Dict = {}
        self._res_body_request_ids: Dict = {}
        self._last_active_time: float = 0
        self._url: Optional[str] = None
        self._intercept_requests: bool = False
        self._proxy: str = '' 
Example #8
Source File: huobi_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #9
Source File: radar_relay_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #10
Source File: binance_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    self._last_recv_time = time.time()
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                        self._last_recv_time = time.time()
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except websockets.exceptions.ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #11
Source File: mock_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #12
Source File: chrome.py    From chromewhip with MIT License 6 votes vote down vote up
def __init__(self, title, url, ws_uri, tab_id):
        self.id_ = tab_id
        self._title = title
        self._url = url
        self._ws_uri = ws_uri
        self.target_id = ws_uri.split('/')[-1]
        self._ws: Optional[websockets.WebSocketClientProtocol] = None
        self._message_id = 0
        self._current_task: Optional[asyncio.Task] = None
        self._ack_events = {}
        self._ack_payloads = {}
        self._input_events = {}
        self._trigger_events = {}
        self._event_payloads = {}
        self._recv_task = None
        self._log = logging.getLogger('chromewhip.chrome.ChromeTab')
        self._send_log = logging.getLogger('chromewhip.chrome.ChromeTab.send_handler')
        self._recv_log = logging.getLogger('chromewhip.chrome.ChromeTab.recv_handler') 
Example #13
Source File: remote_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #14
Source File: stream.py    From td-ameritrade-python-api with MIT License 6 votes vote down vote up
def build_pipeline(self) -> websockets.WebSocketClientProtocol:
        """Builds a data pipeine for processing data.

        Often we want to take the data we are streaming and
        use it in other functions or store it in other platforms.
        This method makes the process of building a pipeline easy
        by handling all the connection setup and request setup.

        Returns:
        ----
        websockets.WebSocketClientProtocol -- The websocket connection.
        """

        # In this case, we don't want things printing to the console.
        self.print_to_console = False

        # Connect to Websocket.
        await self._connect()

        # Build the Data Request.
        await self._send_message(self._build_data_request())

        return self.connection 
Example #15
Source File: binance_api_order_book_data_source.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #16
Source File: radar_relay_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                trading_pairs: List[str] = await self.get_trading_pairs()
                async with websockets.connect(WS_URL) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    for trading_pair in trading_pairs:
                        request: Dict[str, str] = {
                            "type": "SUBSCRIBE",
                            "topic": "BOOK",
                            "market": trading_pair
                        }
                        await ws.send(ujson.dumps(request))
                    async for raw_msg in self._inner_messages(ws):
                        msg = ujson.loads(raw_msg)
                        # Valid Diff messages from RadarRelay have action key
                        if "action" in msg:
                            diff_msg: RadarRelayOrderBookMessage = RadarRelayOrderBook.diff_message_from_exchange(
                                msg, time.time())
                            output.put_nowait(diff_msg)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
                                    exc_info=True)
                await asyncio.sleep(30.0) 
Example #17
Source File: huobi_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                trading_pairs: List[str] = await self.get_trading_pairs()
                async with websockets.connect(HUOBI_WS_URI) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    for trading_pair in trading_pairs:
                        subscribe_request: Dict[str, Any] = {
                            "sub": f"market.{trading_pair}.trade.detail",
                            "id": trading_pair
                        }
                        await ws.send(json.dumps(subscribe_request))

                    async for raw_msg in self._inner_messages(ws):
                        # Huobi compresses their ws data
                        encoded_msg: bytes = gzip.decompress(raw_msg)
                        # Huobi's data value for id is a large int too big for ujson to parse
                        msg: Dict[str, Any] = json.loads(encoded_msg.decode('utf-8'))
                        if "ping" in msg:
                            await ws.send(f'{{"op":"pong","ts": {str(msg["ping"])}}}')
                        elif "subbed" in msg:
                            pass
                        elif "ch" in msg:
                            trading_pair = msg["ch"].split(".")[1]
                            for data in msg["tick"]["data"]:
                                trade_message: OrderBookMessage = HuobiOrderBook.trade_message_from_exchange(
                                    data, metadata={"trading_pair": trading_pair}
                                )
                                output.put_nowait(trade_message)
                        else:
                            self.logger().debug(f"Unrecognized message received from Huobi websocket: {msg}")
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
                                    exc_info=True)
                await asyncio.sleep(30.0) 
Example #18
Source File: bitfinex_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _get_response(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #19
Source File: bitfinex_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _listen_trades_for_pair(self, pair: str, output: asyncio.Queue):
        while True:
            try:
                async with websockets.connect(BITFINEX_WS_URI) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    subscribe_request: Dict[str, Any] = {
                        "event": "subscribe",
                        "channel": "trades",
                        "symbol": f"t{pair}",
                    }
                    await ws.send(ujson.dumps(subscribe_request))
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # response
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # subscribe info
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # snapshot
                    async for raw_msg in self._get_response(ws):
                        msg = self._prepare_trade(raw_msg)
                        if msg:
                            msg_book: OrderBookMessage = BitfinexOrderBook.trade_message_from_exchange(
                                msg,
                                metadata={"symbol": f"{pair}"}
                            )
                            output.put_nowait(msg_book)
            except asyncio.CancelledError:
                raise
            except Exception as err:
                self.logger().error(f"listen trades for pair {pair}", err)
                self.logger().error(
                    "Unexpected error with WebSocket connection. "
                    f"Retrying after {int(self.MESSAGE_TIMEOUT)} seconds...",
                    exc_info=True)
                await asyncio.sleep(self.MESSAGE_TIMEOUT) 
Example #20
Source File: test_bitfinex_auth.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def con_auth(self):
        async with websockets.connect(BITFINEX_WS_AUTH_URI) as ws:
            ws: websockets.WebSocketClientProtocol = ws
            payload = self.auth.generate_auth_payload()
            await ws.send(json.dumps(payload))
            msg = await asyncio.wait_for(ws.recv(), timeout=30)  # response
            return msg 
Example #21
Source File: bitfinex_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _listen_order_book_for_pair(self, pair: str, output: asyncio.Queue):
        while True:
            try:
                async with websockets.connect(BITFINEX_WS_URI) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    subscribe_request: Dict[str, Any] = {
                        "event": "subscribe",
                        "channel": "book",
                        "prec": "R0",
                        "symbol": f"t{pair}",
                    }
                    await ws.send(ujson.dumps(subscribe_request))
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # response
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # subscribe info
                    await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)  # snapshot

                    async for raw_msg in self._get_response(ws):
                        # print("------------- debug 3 ============== raw update message:")
                        # print(raw_msg)
                        msg = self._parse_raw_update(pair, raw_msg)

                        # print("------------- debug 3 ============== update message:")
                        # print(msg)

                        if msg is not None:
                            output.put_nowait(msg)
            except asyncio.CancelledError:
                raise
            except Exception as err:
                self.logger().error(err)
                self.logger().network(
                    f"Unexpected error with WebSocket connection.",
                    exc_info=True,
                    app_warning_msg="Unexpected error with WebSocket connection. "
                                    f"Retrying in {int(self.MESSAGE_TIMEOUT)} seconds. "
                                    "Check network connection."
                )
                await asyncio.sleep(self.MESSAGE_TIMEOUT) 
Example #22
Source File: dolomite_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        await self._get_tracking_pair_done_event.wait()

        try:
            trading_pairs: List[str] = await self.get_trading_pairs()

            async with websockets.connect(self.WS_URL) as ws:
                ws: websockets.WebSocketClientProtocol = ws

                for trading_pair in trading_pairs:
                    orderbook_subscription_request = {
                        "action": SNAPSHOT_WS_SUBSCRIBE_ACTION,
                        "data": {"market": trading_pair},
                        "route": SNAPSHOT_WS_ROUTE,
                    }

                    await ws.send(ujson.dumps(orderbook_subscription_request))

                    async for raw_msg in self._inner_messages(ws):
                        message = ujson.loads(raw_msg)

                        if message["route"] == SNAPSHOT_WS_ROUTE and message["action"] == SNAPSHOT_WS_UPDATE_ACTION:
                            snapshot_timestamp: float = time.time()
                            snapshot_msg: DolomiteOrderBookMessage = self.order_book_class.snapshot_message_from_exchange(
                                message, snapshot_timestamp, {"market": trading_pair}
                            )

                            output.put_nowait(snapshot_msg)
                            self.logger().debug(f"Saved order book snapshot for {trading_pair} at {snapshot_timestamp}")

        except asyncio.CancelledError:
            raise
        except Exception:
            self.logger().error("Unexpected error.", exc_info=True)
            await asyncio.sleep(5.0) 
Example #23
Source File: coinbase_pro_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        """
        *required
        Subscribe to user stream via web socket, and keep the connection open for incoming messages
        :param ev_loop: ev_loop to execute this function in
        :param output: an async queue where the incoming messages are stored
        """
        while True:
            try:
                async with websockets.connect(COINBASE_WS_FEED) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    subscribe_request: Dict[str, any] = {
                        "type": "subscribe",
                        "product_ids": self._trading_pairs,
                        "channels": ["user"]
                    }
                    auth_dict: Dict[str] = self._coinbase_pro_auth.generate_auth_dict("get", "/users/self/verify", "")
                    subscribe_request.update(auth_dict)
                    await ws.send(ujson.dumps(subscribe_request))
                    async for raw_msg in self._inner_messages(ws):
                        msg = ujson.loads(raw_msg)
                        msg_type: str = msg.get("type", None)
                        if msg_type is None:
                            raise ValueError(f"Coinbase Pro Websocket message does not contain a type - {msg}")
                        elif msg_type == "error":
                            raise ValueError(f"Coinbase Pro Websocket received error message - {msg['message']}")
                        elif msg_type in ["open", "match", "change", "done"]:
                            order_book_message: OrderBookMessage = self.order_book_class.diff_message_from_exchange(msg)
                            output.put_nowait(order_book_message)
                        elif msg_type in ["received", "activate", "subscriptions"]:
                            # these messages are not needed to track the order book
                            pass
                        else:
                            raise ValueError(f"Unrecognized Coinbase Pro Websocket message received - {msg}")
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with Coinbase Pro WebSocket connection. "
                                    "Retrying after 30 seconds...", exc_info=True)
                await asyncio.sleep(30.0) 
Example #24
Source File: coinbase_pro_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        """
        Generator function that returns messages from the web socket stream
        :param ws: current web socket connection
        :returns: message in AsyncIterable format
        """
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    self._last_recv_time = time.time()
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        self._last_recv_time = time.time()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #25
Source File: coinbase_pro_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        """
        Generator function that returns messages from the web socket stream
        :param ws: current web socket connection
        :returns: message in AsyncIterable format
        """
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #26
Source File: liquid_api_user_stream_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        """
        Generator function that returns messages from the web socket stream
        :param ws: current web socket connection
        :returns: message in AsyncIterable format
        """
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=Constants.MESSAGE_TIMEOUT)
                    self._last_recv_time = time.time()
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        self._last_recv_time = time.time()
                        await asyncio.wait_for(pong_waiter, timeout=Constants.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #27
Source File: liquid_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        """
        Generator function that returns messages from the web socket stream
        :param ws: current web socket connection
        :returns: message in AsyncIterable format
        """
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=Constants.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=Constants.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
Example #28
Source File: remote_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        while True:
            try:
                async with websockets.connect(self.DIFF_STREAM_URL,
                                              extra_headers=self.authentication_headers) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    async for msg in self._inner_messages(ws):
                        output.put_nowait(msg)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
                                    exc_info=True)
                await asyncio.sleep(30.0) 
Example #29
Source File: node_subscriber.py    From loopchain with Apache License 2.0 5 votes vote down vote up
def __init__(self, channel, rs_target):
        scheme = 'wss' if ('https://' in rs_target) else 'ws'
        netloc = parse.urlparse(rs_target).netloc
        self._target_uri = f"{scheme}://{netloc}/api/ws/{channel}"
        self._exception = None
        self._websocket: WebSocketClientProtocol = None
        self._subscribe_event: Event = None

        ws_methods.add(self.node_ws_PublishHeartbeat)
        ws_methods.add(self.node_ws_PublishNewBlock)

        logging.debug(f"websocket target uri : {self._target_uri}") 
Example #30
Source File: BinanceWebsocket.py    From crypto-bot with Apache License 2.0 5 votes vote down vote up
def __init__(self, client: Client):
        Thread.__init__(self)
        Logger.__init__(self)


        self.client = client
        self.stop = False

        self.ticker_websocket: WebSocketClientProtocol = None
        self.user_webscoket: WebSocketClientProtocol = None

        self.ticker_ws_future = None
        self.user_ws_future = None
        self.mngmt_future = None

        self.connection_key = None
        self.user_info_cb = None

        self.ticker_cb = None
        self.symbols = None

        if not BinanceWebsocket.__EVENT_LOOP:
            self.loop = asyncio.get_event_loop()
            BinanceWebsocket.__EVENT_LOOP = self.loop
        else:
            self.loop = BinanceWebsocket.__EVENT_LOOP

        self.time = None

        self.name = 'Binance WebSocket Thread'