# Async

> AsyncSTX for concurrent requests, and client calls alongside WebSocket streams.

Source: https://docs.stxapp.io/sdks/python/async/

`AsyncSTX` is the SDK's implementation; `STX` runs it on a private event loop. Use `AsyncSTX` when you keep many requests in flight or combine client calls with streams.

```python
import asyncio

from stx import AsyncSTX

async def main():
    async with AsyncSTX() as client:
        me, markets, orders, fills = await asyncio.gather(
            client.me(),
            client.markets(status="open", limit=5),
            client.orders(limit=5),
            client.fills(limit=5),
        )
        print(me.user_id, len(markets), len(orders), len(fills))

asyncio.run(main())
```

One `AsyncSTX` holds one HTTP connection pool; share it across tasks rather than creating one per request. Close it with `async with` or `await client.close()`.

## Iterating pages

```python
import asyncio

from stx import AsyncSTX

async def main():
    async with AsyncSTX() as client:
        count = 0
        async for market in client.iter_markets(status="open", limit=200):
            count += 1
            if count >= 300:
                break
        print("saw", count, "markets")

asyncio.run(main())
```

## Client calls and streams together

```python
import asyncio

from stx import AsyncSTX

async def main():
    async with AsyncSTX() as client:
        ids = [m.market_id for m in await client.markets(status="open", limit=3)]
        async with client.websocket() as ws:
            books = {}

            def on_book(msg):
                books[msg.payload["market_id"]] = msg.payload  # replace, never merge

            await ws.orderbook(ids, on_message=on_book)
            fills = await ws.fills()
            await fills.wait_snapshot()
            await asyncio.sleep(5)
            print("books held:", len(books))

asyncio.run(main())
```

## Sync code

`STX` has every `AsyncSTX` client method without `await`, and works inside a program or notebook that already runs an event loop. `client.async_client` is the underlying `AsyncSTX`, bound to `STX`'s own loop thread. WebSockets are async only.

```python
from stx import STX

with STX() as client:
    for order in client.iter_orders(limit=50):
        print(order.id, order.status)
        break
```
