alpacahq / alpaca-trade-api-python

Python client for Alpaca's trade API
https://pypi.org/project/alpaca-trade-api/
Apache License 2.0
1.73k stars 534 forks source link

Close the WebSocket connection immediately when the stream is stopped #685

Open fumoboy007 opened 1 year ago

fumoboy007 commented 1 year ago

Currently, when the stream is stopped, we set the stream status accordingly and then wait for the _consume loop to check the stream status and close the WebSocket connection. The _consume loop calls self._ws.recv() with a timeout of 5 seconds, so it can take up to 5 seconds for the WebSocket connection to be closed after the stream is stopped. This is unnecessarily inefficient and complicated.

Instead, we could close the WebSocket connection immediately when the stream is stopped. The _consume loop would still be broken out of properly because self._ws.recv() would raise a ConnectionClosed error.