> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qelso.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> pip install qelso: every endpoint as a typed method, with pagers, resumable streams and DataFrames.

```bash theme={null}
pip install qelso
pip install "qelso[pandas]"   # with DataFrames
```

Python 3.10 or later. Every endpoint is a method on the client, and every response is a typed model.

## The client

```python theme={null}
from qelso import Qelso

client = Qelso()                       # reads QELSO_API_KEY
client = Qelso(api_key="pk_live_...")  # or pass it
```

Use it as a context manager (`with Qelso() as client:`) to close its connections when you're done. `AsyncQelso` is the same client for `asyncio`.

## The methods

Each endpoint has a method named after it, and the endpoints that page or stream have two more.

| Endpoint | One page or object | Every row, page after page | One stream |
| - | - | - | - |
| `GET /v2/markets` | `list_markets(...)` | `iter_markets(...)` | — |
| `GET /v2/markets/{market_id}` | `get_market(id)` | — | — |
| `GET /v2/markets/{market_id}/prices` | `get_market_prices(id, ...)` | `iter_market_prices(...)` | `stream_market_prices(...)` |
| `GET /v2/markets/{market_id}/trades` | `get_market_trades(id, ...)` | `iter_market_trades(...)` | `stream_market_trades(...)` |

The same pattern covers every endpoint: series, events, lifecycle, candles, statistics, books, best bid and ask, and book changes. Parameters keep the API's names. Times can be strings, dates, epoch milliseconds or `datetime` objects; a `datetime` without a timezone is taken as UTC.

## Pages

```python theme={null}
for market in client.iter_markets(venue="polymarket", category="economics", status="open", limit=1000):
    print(market.id, market.title)

pager = client.iter_market_prices("polymarket:3215007", start="2026-11-10", end="2026-11-17", resolution="10m")
df = pager.to_pandas()
print(pager.last_page.market.outcomes.yes.label)
```

`limit` is the page size: the larger the page, the fewer the requests.

## Streams

A stream returns a whole window in one request. If the connection breaks, the SDK resumes after the last row it received, so no row is repeated or skipped. Once rows are flowing, a request that fails is tried again after 1, 2, 4 … up to 30 seconds (or as long as `Retry-After` asks), so an outage is waited out; `max_resumes` (10 by default) counts failures in a row, and any new row resets it.

```python theme={null}
# CSV is the fastest way into pandas or a file.
prices = client.stream_market_prices("polymarket:3215007", start="2026-11-10", end="2026-11-17",
                                     resolution="10m", format="csv").to_pandas()

# Trades on plans that include them; book changes with Ultra:
with client.stream_market_trades("polymarket:3215007", start="2026-11-10", end="2026-11-17") as stream:
    for trade in stream:
        print(trade.ts, trade.price, trade.size, trade.aggressor)

client.stream_market_book_updates("polymarket:3215007", start="2026-11-16",
                                  end="2026-11-17", format="csv").save("book_updates.csv")
```

`save(path)` writes to `path.part` and renames it only when the stream has ended normally. If the stream fails anyway, the `.part` file keeps what arrived, and `save(path, resume=True)` on a new stream with the same parameters carries on from its last row. `stream.resume_after` gives the `after=` to continue from.

## DataFrames

`to_pandas()` works on every pager and stream. Times become UTC timestamps, and columns follow the API's field order. Books come in long form, one row per price level: `t`, `last_change`, `side`, `level` (0 is the best), `price`, `size`.

## Errors and retries

```python theme={null}
import qelso

try:
    client.get_market("polymarket:0")
except qelso.NotFoundError as e:
    print(e.code, e.message, e.request_id)
```

| Exception | When |
| - | - |
| `BadRequestError` | `400`: `invalid_parameter`, `invalid_cursor`, `window_too_large` |
| `AuthenticationError` | `401`: `unauthorized` |
| `PermissionDeniedError` | `403`: `forbidden_venue`, `forbidden_dataset`, `plan_history_limit`, `plan_resolution_not_allowed`, `suspended` |
| `NotFoundError` | `404` |
| `NotAcceptableError` | `406`: `not_acceptable` |
| `RateLimitError` | `429`: `rate_limited` |
| `QuotaExceededError` | `429`: `quota_exceeded` |
| `InternalServerError`, `ServiceUnavailableError`, `QueryTimeoutError` | `500`, `503`, `504` |
| `APIConnectionError`, `APITimeoutError` | The network failed, or a stream kept failing with no new row |
| `UnexpectedResponseError` | An answer the API shouldn't give, such as a JSON page for a stream |
| `InvalidRequestError` | The client can't send the request as configured, such as a malformed base URL or header; never retried |

All of them are `qelso.QelsoError`. The client retries rate limits (after `Retry-After`), temporary outages and network errors, up to `max_retries` times (3 by default). It never retries a used-up quota or a query that ran over its time limit.

Every response has `response_meta`: its request ID, the units it cost and your remaining rate limit.

## Async

```python theme={null}
import asyncio
from qelso import AsyncQelso

async def main():
    async with AsyncQelso() as client:
        async for market in client.iter_markets(venue="polymarket", status="open"):
            print(market.id)
        async with client.stream_market_trades("polymarket:3215007",
                                               start="2026-11-10", end="2026-11-17") as stream:
            async for trade in stream:
                ...

asyncio.run(main())
```

## New fields and values

v2 changes only by addition. The SDK reads fields and values added later without breaking your code: new fields appear in each model's `model_extra`, and new venues, datasets or error codes come through as plain strings.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.