> For the complete documentation index, see [llms.txt](https://agentdex.gitbook.io/agentdex-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://agentdex.gitbook.io/agentdex-docs/developers/websocket-api.md).

# Websocket API

Two WebSocket surfaces serve different needs:

| Surface            | Use when                                                                                                       |
| ------------------ | -------------------------------------------------------------------------------------------------------------- |
| **Market Data WS** | You want a clean public + private feed: tickers, candles, order book, account events. The recommended default. |
| **Direct WS**      | You need direct access to engine messages (advanced low-latency execution, market makers).                     |

Both live behind the same gateway and use the same Keychain key for authentication, but the message protocols differ.

### Market Data WS — the default

#### Connection

```
wss://agentdex.xyz/ws
```

#### Authentication

Public topics need no auth. Private topics require an authentication message after connection:

{% code title="Authenticate" %}

```json
{ "method": "authenticate",
  "params": { "token": "<api_key_or_jwt>" } }
```

{% endcode %}

Server replies with success/failure. To refresh, send `refresh`; to disconnect cleanly, send `deauthenticate`.

#### Topics

**Public**:

| Topic                             | Payload                                        |
| --------------------------------- | ---------------------------------------------- |
| `ticker.{instrument}`             | Mark, index, fair, SMA, last, 24h stats.       |
| `tickers`                         | All instruments at once.                       |
| `orderbook.{instrument}`          | Snapshot + diffs; bid/ask aggregated by price. |
| `trades.{instrument}`             | Public trade stream.                           |
| `candles.{instrument}.{interval}` | OHLCV.                                         |
| `funding.{instrument}`            | Funding rate updates and settlements.          |

**Private** (require `authenticate`):

| Topic          | Payload                                                         |
| -------------- | --------------------------------------------------------------- |
| `balance`      | USDT balance updates.                                           |
| `position`     | Open positions with PnL, margin, liq price.                     |
| `order`        | Order state transitions (open → filled / cancelled / rejected). |
| `fill`         | Individual fills with fee, price, side.                         |
| `notification` | Liquidation events, ADL events, force-withdrawal availability.  |

#### Subscription protocol

{% code title="Subscribe to a topic" %}

```json
{ "method": "subscribe",
  "params": { "topic": "orderbook.BTC_USDT_PERPETUAL" } }
```

{% endcode %}

Response:

{% code title="Snapshot response" %}

```json
{ "topic": "orderbook.BTC_USDT_PERPETUAL",
  "type": "snapshot",
  "data": { "bids": [[...]], "asks": [[...]], "seq": 12345 } }
```

{% endcode %}

Subsequent messages are diffs:

{% code title="Diff response" %}

```json
{ "topic": "orderbook.BTC_USDT_PERPETUAL",
  "type": "diff",
  "data": { "bids": [["80500","0"]], "asks": [], "seq": 12346 } }
```

{% endcode %}

Apply diffs in `seq` order. A gap → resubscribe to pick up a fresh snapshot.

#### Heartbeats and reconnect

The server sends a ping every 10–15 s; respond with pong. If you miss two pings, drop and reconnect with backoff (1 s → 30 s). On reconnect, re-authenticate and re-subscribe; snapshots are replayed.

### Direct WS — low-latency engine access

#### Access

The direct WS is a low-latency surface intended for market makers and advanced execution clients. It uses a separate **Access-Key / Secret-Key** pair (not the standard `X-Api-Key`) with request signing. Endpoint and signing details are shared with qualified clients on request — the Market Data WS above is the recommended default for everyone else.

#### Topics

The direct WS exposes the matching engine's event stream directly: order events, trade events, position deltas, ticker diffs. Schemas mirror the engine's event types and are subject to engine-version evolution.

### Order placement via WebSocket

The Market Data WS does **not** currently support order placement — submit orders via REST or MCP, observe via WS. The direct WS supports streaming order placement for advanced clients.

### Sequence numbers and gap detection

Every diff carries an instrument-scoped `seq` that increments by 1 per message. If your client receives `seq=N+2` without `seq=N+1`:

1. Discard buffered diffs.
2. Resubscribe to fetch a fresh snapshot.
3. Resume applying diffs from the new snapshot's `seq`.

For order book reconstruction, this is the standard exchange-WS pattern.

### Known limitations

* The Market Data WS `mark_price` field in some topics is computed by a simpler formula than the matching engine's (no median, just fair or last). For risk-critical decisions, use `get_ticker` REST/MCP or subscribe to the full ticker components — see [Mark price](/agentdex-docs/trading/mark-price.md).
* Backfill via WS is limited; pull historical data from the REST history endpoints.
* Per-topic rate limits apply; use snapshot+diff rather than polling.

For full topic schemas and authoritative field lists, see the full WebSocket API reference.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://agentdex.gitbook.io/agentdex-docs/developers/websocket-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
