Restarting Stream Websocket after running stop_ws()

Hi all.

My application is trying to use the Stream websocket API from the Python package (alpaca-trade-api-python) to obtain the latest price of a ticker. I created an Alpaca class so that I can use its instance to execute all the Alpaca market related purposes. One of the purposes would be to obtain the latest price of a ticker during market open hours.

The algorithm I used to achieve the above is to first,

  1. instantiate the Stream class
  2. subscribe to the ticker
  3. get the latest quote
  4. execute stream.stop_ws() to return the latest price to the synchronous function.

I didn’t use stream.unsubscribe_quote() because I realised in an async function, unsubscribing to the ticker doesn’t stop the websocket connection and thus doesn’t return the function.

I want to keep using the Stream instance even after executing stop_ws() but I am unable to restart the Stream websocket connection even if I run stream.run().

This is a problem for me because after I execute stop_ws(), I need to reinstantiate the instance as the Stream instance’s websocket connection is closed.

What is the right way to restore the websocket connection or rather what would be the ideal way to get the latest price of the ticker using Stream websocket?

Thanks.

The Alpaca Data API v2 provides a REST endpoint for obtaining the latest trade price for the ticker. This endpoint should work much faster than your approach. In fact, streaming initialization/authentication/subscription requires several network roundtrips. The REST call will work faster especially if it runs over an HTTP/2 connection (I’m not sure about Python but .NET SDK supports it). The streaming connection is designed for long-live usage so you open it at the start and close only at the application stop.

wow thanks Oleg!

This is very helpful! Did not know about this API endpoint :slight_smile:

Can you tell me how to do that last part in python? How do you close the connection when terminating the program?