alpacahq / alpaca-py

The Official Python SDK for Alpaca API
https://alpaca.markets/sdks/python/getting_started.html
Apache License 2.0
491 stars 122 forks source link

[Question]: How do I stream both market data from OptionDataStream and StockDataStream? #476

Closed jamesmawm closed 2 weeks ago

jamesmawm commented 2 weeks ago

Question form pre-submit checklist.

Question

I have something like this defined:

self.options_data_stream = OptionDataStream(self.api_key, self.api_secret)
self.stock_data_stream = StockDataStream(self.api_key, self.api_secret)

When I try to run both:

await asyncio.gather([
  asyncio.run(self.stock_data_stream.run()),
   asyncio.run(self.options_data_stream.run())
 ])

Only the first .run() works. I couldn't get data from the options_data_stream(). How do I stream both stock market and options at the same time?

hiohiohio commented 2 weeks ago

@jamesmawm Could you please try this?

async def run():
  await asyncio.gather(
    asyncio.create_task(self.stock_data_stream._run_forever()),
    asyncio.create_task(self.options_data_stream._run_forever())
  )

asyncio.run(run())

.run() calls asyncio.run() in inside. You could use ._run_forever() instead. But as you can see it has _ prefix in the function name, it means we have an option to change it completely at any given version of alpaca-py including the name of function _run_forever(). So, please be aware of this.

jamesmawm commented 2 weeks ago

This is perfect, thanks @hiohiohio! Absolutely, looking forward to seeing this in the official docs.