# Launching TradingStream in async mode

**URL:** <https://forum.alpaca.markets/t/launching-tradingstream-in-async-mode/14268>\
**Category:** Alpaca Trading\
**Created:** [May 23, 2024, 7:35pm UTC](https://forum.alpaca.markets/t/launching-tradingstream-in-async-mode/14268 "2024-05-23T19:35:27Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Manuel\_Polavieja](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/manuel_polavieja/32/6182_2.png) [@Manuel\_Polavieja](https://forum.alpaca.markets/u/Manuel_Polavieja)\
**Post date:** [May 23, 2024, 7:35pm UTC](https://forum.alpaca.markets/t/launching-tradingstream-in-async-mode/14268/1 "2024-05-23T19:35:28Z")

</div>

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:

```auto
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())

```
