Python SDK: how to stream market data and trades update simultaneously?

Hello,

I am trying to leverage Python SDK to stream market data and trades update simultaneously.

Basically, I’d like to stream market data, based on that market data, I’d like to place orders, and I’d like to get updates when these orders get filled. The problem I have is that to stream market data, I need to call two .run() functions, which cannot work.

I don’t have a good enough mastery of asyncio to handle this properly. Could you help me out?

The code would look something like this:

from alpaca.data.live import StockDataStream
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from alpaca.trading.stream import TradingStream

async def tradeDataHandler(data):
    #treat received trade updates

async def quoteDataHandler(data):
    #treat received market data
      
def main():
    dataStreamClient = StockDataStream(API_KEY, SECRET_KEY)
    tradingStreamClient = TradingStream(API_KEY, SECRET_KEY, paper=True) 
    
    dataStreamClient.subscribe_quotes(quoteDataHandler,"TSLA")
    tradingStreamClient.subscribe_trade_updates(tradeDataHandler)
    
    tradingStreamClient.run()
    dataStreamClient.run() #This line will never be called since it is after the first .run() call
        
if __name__ == "__main__":
    main()

In case anyone is interested, It is possible to accomplish it by either using multiple threads (Threading module), or using asynchronous python (asyncio module) and calling the .run() functions in parallel tasks.

1 Like