I could not receive events triggered by instructions before tranding_stream.run() command, and instructions after that command would never execute. So I figured out this solution where I launch trading_stream._run_forever() asynchronously. Here is the code:
from alpaca.trading.stream import TradingStream
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import LimitOrderRequest
import asyncio
API_KEY = ''
API_SECRET = ''
async def update_handler(data):
# trade updates will arrive in our async handler
print(data)
async def run_stream(trading_stream):
await trading_stream._run_forever()
async def main():
trading_stream = TradingStream(API_KEY, API_SECRET, paper=True)
trading_stream.subscribe_trade_updates(update_handler)
# Start the stream in a separate task and wait 3 seconds for the ws connection to establish
asyncio.create_task(run_stream(trading_stream))
await asyncio.sleep(3)
# Send an order to check if we receive events
trading_client = TradingClient(API_KEY, API_SECRET, paper=True)
order = LimitOrderRequest(symbol="TSLA", qty=1, side="buy", type="limit", limit_price=150, time_in_force="day", extended_hours=True)
trading_client.submit_order(order_data=order)
print("order sent")
# Keep the main coroutine running indefinitely
await asyncio.Event().wait()
asyncio.run(main())