> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/websockets/futures-market-data.md).

# futures market data

Public real-time market data for perpetual futures: order book, best quote, trades, candles, 24h ticker, mark price, funding.

Futures market data streams push live public data for every futures pair over WebSocket. They need no API key and carry no account data. For history and one-off snapshots (candles, order book, recent trades, funding, 24h statistics) use the [Futures Market Data REST endpoints](broken://pages/ebf2eeef93cba1c6ba8a58e5d8fabcfca4cb69d0).

### Host

```
wss://futures-marketdata-service.outpoll.com
```

| Stream                | Path              | Page                                                                  |
| --------------------- | ----------------- | --------------------------------------------------------------------- |
| Order book            | `/ws/book/depth`  | [Order Book](broken://pages/72d53f4e903b3c737073b4c2f8fd60cb4d677af2) |
| Best bid / ask        | `/ws/book/best`   | [Best Quote](broken://pages/9e24e8b0b94198dfde4789a97b836ca0e61bad78) |
| Trades and last price | `/ws/trades/last` | [Trades](broken://pages/f31a6452e7841bff66a5e956264bd147fe8075ca)     |
| Candles (OHLCV)       | `/ws/candles`     | [Candles](broken://pages/37867e1dff0131c7b473df4f8f3717539a39598e)    |
| 24h ticker            | `/ws/ticker/24h`  | [Ticker](broken://pages/4db12a4d7f38f47ec23b37ee31cdae377db56f0f)     |
| Mark price            | `/ws/mark-price`  | [Mark Price](broken://pages/5286fe3d39bfe5c8d3da41d76d94684c20bcfbb7) |
| Funding               | `/ws/funding`     | [Funding](broken://pages/d589f04760544c5dde250242c21c5ca97417f009)    |

Each stream is a separate WebSocket connection. One connection can follow any number of pairs on its stream, up to the [limits](#limits).

### Authentication

No authentication required.

### Connection Lifecycle

{% stepper %}
{% step %}

## Open a connection

Open a WebSocket connection to the stream path.
{% endstep %}

{% step %}

## Subscribe to pairs

Send a `subscribe` frame with the pairs you want.
{% endstep %}

{% step %}

## Receive current state and updates

The server sends the current state of each pair (where the stream has one), then pushes updates as they happen.
{% endstep %}

{% step %}

## Keep the connection alive

Send `ping` periodically to keep the connection alive; send `unsubscribe` to stop a pair.
{% endstep %}

{% step %}

## Reconnect when disconnected

On disconnect, reconnect and subscribe again — subscriptions are not kept across connections.
{% endstep %}
{% endstepper %}

There is no separate confirmation frame for a subscription. A successful subscribe is silent; the first data frame for the pair is the confirmation. A rejected one produces an [error frame](#errors).

All frames are JSON text frames, except the `ping` / `pong` keep-alive which is plain text.

### Pair ID

Every stream addresses pairs by the integer pair ID (`gid`). Get the list of pairs and their IDs from [Get Public Pairs](broken://pages/bba14d4639c3c29cf6fdbadc86ec5d4dfeea3b07#get-public-pairs).

### Subscribe and Unsubscribe

All streams use the same request frame.

| Field | Type              | Description                                                                                                                       |
| ----- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `act` | string            | `subscribe` or `unsubscribe`                                                                                                      |
| `pi`  | integer           | One pair ID                                                                                                                       |
| `ps`  | array of integers | Several pair IDs; when present, `pi` is ignored                                                                                   |
| `all` | boolean           | `true` = every pair on this stream, including pairs listed later. Supported on best quote, trades, ticker, mark price and funding |
| `dp`  | integer           | Order book only: number of levels per side                                                                                        |
| `g`   | number            | Order book only: price grouping step                                                                                              |
| `iv`  | string            | Candles only: candle interval                                                                                                     |

Subscribe to one pair:

```json
{"act": "subscribe", "pi": 1}
```

Subscribe to several pairs:

```json
{"act": "subscribe", "ps": [1, 2, 5]}
```

Subscribe to every pair:

```json
{"act": "subscribe", "all": true}
```

Unsubscribe uses the same shapes:

```json
{"act": "unsubscribe", "ps": [2, 5]}
```

```json
{"act": "unsubscribe", "all": true}
```

* Subscribing again to a pair you already follow replaces its parameters (`dp`, `g`, `iv`) and does not count against the limit.
* `unsubscribe` with `all: true` removes the all-pairs subscription only; pairs subscribed by ID stay.
* A pair subscribed both by ID and through `all: true` is delivered once.
* Unsubscribing from a pair you do not follow is ignored.
* A frame with any other `act` value is ignored.

### Limits

| Limit                                    | Value | Error when exceeded                                            |
| ---------------------------------------- | ----- | -------------------------------------------------------------- |
| Pair IDs in one `subscribe` frame (`ps`) | 500   | `too_many_pairs` — the whole frame is rejected                 |
| Distinct pairs per connection            | 500   | `subscription_limit` — the pairs beyond the limit are rejected |

Use `all: true` instead of listing pairs when you need the whole market.

{% hint style="warning" %}
**Slow consumers.** The server buffers outgoing frames per connection. A client that does not read fast enough (more than 512 KB pending, or a frame waiting longer than 2 seconds) is disconnected with close code `1013`. Read frames continuously and do heavy processing outside the receive loop.
{% endhint %}

### Ping

Send the text `ping` (not JSON). The server answers with the text `pong`.

```
ping
```

```
pong
```

Send a ping every 20–30 seconds, and reconnect if no frame (data or `pong`) arrives for a while.

### Errors

Errors arrive as a JSON frame on the same connection. The connection stays open.

```json
{"er": "unknown_pair", "msg": "pairId 999 not found"}
```

| Field | Type   | Description                                              |
| ----- | ------ | -------------------------------------------------------- |
| `er`  | string | Error code                                               |
| `msg` | string | Human-readable description (may change — don't parse it) |

| Code                 | Cause                                                                                            |
| -------------------- | ------------------------------------------------------------------------------------------------ |
| `parse_error`        | The frame is neither `ping` nor valid JSON of the request shape (for example a non-numeric `pi`) |
| `invalid_pair`       | Pair ID is zero or negative                                                                      |
| `unknown_pair`       | No pair with this ID                                                                             |
| `too_many_pairs`     | More than 500 IDs in `ps`                                                                        |
| `subscription_limit` | The connection already follows 500 pairs                                                         |
| `invalid_group`      | Order book only: `g` has more than 8 decimal places or more than 18 integer digits               |

In a `ps` list, each rejected pair produces its own error frame; the valid pairs in the same frame are subscribed.

### Number and Time Format

* Prices, sizes and rates are JSON **numbers** with exact decimal values. Parse them as decimals, not floats (in Python: `json.loads(msg, parse_float=Decimal)`).
* Very small values can be written in exponent notation, for example `9.8E-7`.
* Price levels are `[price, size]` arrays.
* Time is epoch **milliseconds**, UTC.
* Field names are short keys; each stream page lists its fields.

### Python Example

{% code title="futures\_market\_data.py" %}

```python
import asyncio
import json
from decimal import Decimal

import websockets

URL = "wss://futures-marketdata-service.outpoll.com/ws/ticker/24h"


async def keepalive(ws):
    while True:
        await asyncio.sleep(20)
        await ws.send("ping")


async def main():
    async with websockets.connect(URL) as ws:
        await ws.send(json.dumps({"act": "subscribe", "ps": [1, 2]}))
        ping_task = asyncio.create_task(keepalive(ws))
        try:
            async for raw in ws:
                if raw == "pong":
                    continue
                msg = json.loads(raw, parse_float=Decimal)
                if "er" in msg:
                    print("error:", msg["er"], msg["msg"])
                    continue
                print(msg)
        finally:
            ping_task.cancel()


asyncio.run(main())
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.outpoll.com/api/futures-api/websockets/futures-market-data.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
