|
| 1 | +import asyncio |
| 2 | +import base64 |
| 3 | +import json |
| 4 | +from typing import List, Optional, Callable |
| 5 | + |
| 6 | +from websockets.sync.client import connect as sync_connect |
| 7 | +from websockets.asyncio.client import connect as async_connect |
| 8 | + |
| 9 | +from yfinance import utils |
| 10 | +from yfinance.pricing_pb2 import PricingData |
| 11 | +from google.protobuf.json_format import MessageToDict |
| 12 | + |
| 13 | + |
| 14 | +class BaseWebSocket: |
| 15 | + def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2", verbose=True): |
| 16 | + self.url = url |
| 17 | + self.verbose = verbose |
| 18 | + self.logger = utils.get_yf_logger() |
| 19 | + self._ws = None |
| 20 | + self._subscriptions = set() |
| 21 | + self._subscription_interval = 15 # seconds |
| 22 | + |
| 23 | + def _decode_message(self, base64_message: str) -> dict: |
| 24 | + try: |
| 25 | + decoded_bytes = base64.b64decode(base64_message) |
| 26 | + pricing_data = PricingData() |
| 27 | + pricing_data.ParseFromString(decoded_bytes) |
| 28 | + return MessageToDict(pricing_data, preserving_proto_field_name=True) |
| 29 | + except Exception as e: |
| 30 | + self.logger.error("Failed to decode message: %s", e, exc_info=True) |
| 31 | + print("Failed to decode message: %s", e) |
| 32 | + return { |
| 33 | + 'error': str(e), |
| 34 | + 'raw_base64': base64_message |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | +class AsyncWebSocket(BaseWebSocket): |
| 39 | + """ |
| 40 | + Asynchronous WebSocket client for streaming real time pricing data. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2", verbose=True): |
| 44 | + """ |
| 45 | + Initialize the AsyncWebSocket client. |
| 46 | +
|
| 47 | + Args: |
| 48 | + url (str): The WebSocket server URL. Defaults to Yahoo Finance's WebSocket URL. |
| 49 | + verbose (bool): Flag to enable or disable print statements. Defaults to True. |
| 50 | + """ |
| 51 | + super().__init__(url, verbose) |
| 52 | + self._message_handler = None # Callable to handle messages |
| 53 | + self._heartbeat_task = None # Task to send heartbeat subscribe |
| 54 | + |
| 55 | + async def _connect(self): |
| 56 | + if self._ws is None: |
| 57 | + self._ws = await async_connect(self.url) |
| 58 | + self.logger.info("Connected to WebSocket.") |
| 59 | + if self.verbose: |
| 60 | + print("Connected to WebSocket.") |
| 61 | + |
| 62 | + async def _periodic_subscribe(self): |
| 63 | + while True: |
| 64 | + try: |
| 65 | + await asyncio.sleep(self._subscription_interval) |
| 66 | + |
| 67 | + if self._subscriptions: |
| 68 | + message = {"subscribe": list(self._subscriptions)} |
| 69 | + await self._ws.send(json.dumps(message)) |
| 70 | + |
| 71 | + if self.verbose: |
| 72 | + print(f"Heartbeat subscription sent for symbols: {self._subscriptions}") |
| 73 | + except Exception as e: |
| 74 | + self.logger.error("Error in heartbeat subscription: %s", e, exc_info=True) |
| 75 | + if self.verbose: |
| 76 | + print(f"Error in heartbeat subscription: {e}") |
| 77 | + break |
| 78 | + |
| 79 | + async def subscribe(self, symbols: str | List[str]): |
| 80 | + """ |
| 81 | + Subscribe to a stock symbol or a list of stock symbols. |
| 82 | +
|
| 83 | + Args: |
| 84 | + symbols (str | List[str]): Stock symbol(s) to subscribe to. |
| 85 | + """ |
| 86 | + await self._connect() |
| 87 | + |
| 88 | + if isinstance(symbols, str): |
| 89 | + symbols = [symbols] |
| 90 | + |
| 91 | + self._subscriptions.update(symbols) |
| 92 | + |
| 93 | + message = {"subscribe": list(self._subscriptions)} |
| 94 | + await self._ws.send(json.dumps(message)) |
| 95 | + |
| 96 | + # Start heartbeat subscription task |
| 97 | + if self._heartbeat_task is None: |
| 98 | + self._heartbeat_task = asyncio.create_task(self._periodic_subscribe()) |
| 99 | + |
| 100 | + self.logger.info(f"Subscribed to symbols: {symbols}") |
| 101 | + if self.verbose: |
| 102 | + print(f"Subscribed to symbols: {symbols}") |
| 103 | + |
| 104 | + async def unsubscribe(self, symbols: str | List[str]): |
| 105 | + """ |
| 106 | + Unsubscribe from a stock symbol or a list of stock symbols. |
| 107 | +
|
| 108 | + Args: |
| 109 | + symbols (str | List[str]): Stock symbol(s) to unsubscribe from. |
| 110 | + """ |
| 111 | + await self._connect() |
| 112 | + |
| 113 | + if isinstance(symbols, str): |
| 114 | + symbols = [symbols] |
| 115 | + |
| 116 | + self._subscriptions.difference_update(symbols) |
| 117 | + |
| 118 | + message = {"unsubscribe": list(self._subscriptions)} |
| 119 | + await self._ws.send(json.dumps(message)) |
| 120 | + |
| 121 | + self.logger.info(f"Unsubscribed from symbols: {symbols}") |
| 122 | + if self.verbose: |
| 123 | + print(f"Unsubscribed from symbols: {symbols}") |
| 124 | + |
| 125 | + async def listen(self, message_handler: Optional[Callable[[dict], None]] = None): |
| 126 | + """ |
| 127 | + Start listening to messages from the WebSocket server. |
| 128 | +
|
| 129 | + Args: |
| 130 | + message_handler (Optional[Callable[[dict], None]]): Optional function to handle received messages. |
| 131 | + """ |
| 132 | + await self._connect() |
| 133 | + self._message_handler = message_handler |
| 134 | + |
| 135 | + self.logger.info("Listening for messages...") |
| 136 | + if self.verbose: |
| 137 | + print("Listening for messages...") |
| 138 | + |
| 139 | + # Start heartbeat subscription task |
| 140 | + if self._heartbeat_task is None: |
| 141 | + self._heartbeat_task = asyncio.create_task(self._periodic_subscribe()) |
| 142 | + |
| 143 | + try: |
| 144 | + async for message in self._ws: |
| 145 | + message_json = json.loads(message) |
| 146 | + encoded_data = message_json.get("message", "") |
| 147 | + decoded_message = self._decode_message(encoded_data) |
| 148 | + if self._message_handler: |
| 149 | + self._message_handler(decoded_message) |
| 150 | + else: |
| 151 | + print(decoded_message) |
| 152 | + except (KeyboardInterrupt, asyncio.CancelledError) as e: |
| 153 | + self.logger.info("WebSocket listening interrupted. Closing connection...") |
| 154 | + if self.verbose: |
| 155 | + print("WebSocket listening interrupted. Closing connection...") |
| 156 | + await self.close() |
| 157 | + except Exception as e: |
| 158 | + self.logger.error("Error while listening to messages: %s", e, exc_info=True) |
| 159 | + if self.verbose: |
| 160 | + print("Error while listening to messages: %s", e) |
| 161 | + |
| 162 | + async def close(self): |
| 163 | + """Close the WebSocket connection.""" |
| 164 | + if self._heartbeat_task: |
| 165 | + self._heartbeat_task.cancel() |
| 166 | + |
| 167 | + if self._ws is not None:# and not self._ws.closed: |
| 168 | + await self._ws.close() |
| 169 | + self.logger.info("WebSocket connection closed.") |
| 170 | + if self.verbose: |
| 171 | + print("WebSocket connection closed.") |
| 172 | + |
| 173 | + |
| 174 | +class WebSocket(BaseWebSocket): |
| 175 | + """ |
| 176 | + Synchronous WebSocket client for streaming real time pricing data. |
| 177 | + """ |
| 178 | + |
| 179 | + def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2", verbose=True): |
| 180 | + """ |
| 181 | + Initialize the WebSocket client. |
| 182 | +
|
| 183 | + Args: |
| 184 | + url (str): The WebSocket server URL. Defaults to Yahoo Finance's WebSocket URL. |
| 185 | + verbose (bool): Flag to enable or disable print statements. Defaults to True. |
| 186 | + """ |
| 187 | + super().__init__(url, verbose) |
| 188 | + |
| 189 | + def _connect(self): |
| 190 | + if self._ws is None: |
| 191 | + self._ws = sync_connect(self.url) |
| 192 | + self.logger.info("Connected to WebSocket.") |
| 193 | + if self.verbose: |
| 194 | + print("Connected to WebSocket.") |
| 195 | + |
| 196 | + def subscribe(self, symbols: str | List[str]): |
| 197 | + """ |
| 198 | + Subscribe to a stock symbol or a list of stock symbols. |
| 199 | +
|
| 200 | + Args: |
| 201 | + symbols (str | List[str]): Stock symbol(s) to subscribe to. |
| 202 | + """ |
| 203 | + self._connect() |
| 204 | + |
| 205 | + if isinstance(symbols, str): |
| 206 | + symbols = [symbols] |
| 207 | + |
| 208 | + self._subscriptions.update(symbols) |
| 209 | + |
| 210 | + message = {"subscribe": list(self._subscriptions)} |
| 211 | + self._ws.send(json.dumps(message)) |
| 212 | + |
| 213 | + self.logger.info(f"Subscribed to symbols: {symbols}") |
| 214 | + if self.verbose: |
| 215 | + print(f"Subscribed to symbols: {symbols}") |
| 216 | + |
| 217 | + def unsubscribe(self, symbols: str | List[str]): |
| 218 | + """ |
| 219 | + Unsubscribe from a stock symbol or a list of stock symbols. |
| 220 | +
|
| 221 | + Args: |
| 222 | + symbols (str | List[str]): Stock symbol(s) to unsubscribe from. |
| 223 | + """ |
| 224 | + self._connect() |
| 225 | + |
| 226 | + if isinstance(symbols, str): |
| 227 | + symbols = [symbols] |
| 228 | + |
| 229 | + self._subscriptions.difference_update(symbols) |
| 230 | + |
| 231 | + message = {"unsubscribe": list(self._subscriptions)} |
| 232 | + self._ws.send(json.dumps(message)) |
| 233 | + |
| 234 | + self.logger.info(f"Unsubscribed from symbols: {symbols}") |
| 235 | + if self.verbose: |
| 236 | + print(f"Unsubscribed from symbols: {symbols}") |
| 237 | + |
| 238 | + def listen(self, message_handler: Optional[Callable[[dict], None]] = None): |
| 239 | + """ |
| 240 | + Start listening to messages from the WebSocket server. |
| 241 | +
|
| 242 | + Args: |
| 243 | + message_handler (Optional[Callable[[dict], None]]): Optional function to handle received messages. |
| 244 | + """ |
| 245 | + self._connect() |
| 246 | + |
| 247 | + self.logger.info("Listening for messages...") |
| 248 | + if self.verbose: |
| 249 | + print("Listening for messages...") |
| 250 | + |
| 251 | + try: |
| 252 | + while True: |
| 253 | + message = self._ws.recv() |
| 254 | + message_json = json.loads(message) |
| 255 | + encoded_data = message_json.get("message", "") |
| 256 | + decoded_message = self._decode_message(encoded_data) |
| 257 | + |
| 258 | + if message_handler: |
| 259 | + message_handler(decoded_message) |
| 260 | + else: |
| 261 | + print(decoded_message) |
| 262 | + except KeyboardInterrupt: |
| 263 | + if self.verbose: |
| 264 | + print("Received keyboard interrupt.") |
| 265 | + self.close() |
| 266 | + except Exception as e: |
| 267 | + self.logger.error("Error while listening to messages: %s", e, exc_info=True) |
| 268 | + if self.verbose: |
| 269 | + print("Error while listening to messages: %s", e) |
| 270 | + |
| 271 | + def close(self): |
| 272 | + """Close the WebSocket connection.""" |
| 273 | + if self._ws is not None: |
| 274 | + self._ws.close() |
| 275 | + self.logger.info("WebSocket connection closed.") |
| 276 | + if self.verbose: |
| 277 | + print("WebSocket connection closed.") |
0 commit comments