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


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 import StockDataStream
from import TradingClient
from import LimitOrderRequest
from import OrderSide, TimeInForce
from 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) 
    tradingStreamClient.subscribe_trade_updates(tradeDataHandler) #This line will never be called since it is after the first .run() call
if __name__ == "__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