> For the complete documentation index, see [llms.txt](https://docs.nexus.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nexus.xyz/apis-and-rates/apis-and-rates/exchange-websocket.md).

# Exchange WebSocket

Real-time order book, trade and account streams: subscriptions, tokens, and reconnection.

The WebSocket API delivers real-time order book updates, trades, candles, engine status, and account events (orders, fills, positions, balances, liquidations). It is the recommended path for any latency-sensitive integration.

### Connecting

There are two WebSocket endpoints, and only one of them takes a token.

**`/stream`: public market data, no token.** Open the socket with no credentials and send one message listing channels, such as `{"subscribe": ["book:BTC-USDX-PERP"]}`. Only that first message is read, so reconnect to change channels. Frames are tagged by `type` (`BookUpdate`, `Trade`, `MarketHalted`, `MarketResumed`, and `gap` when the connection falls behind). Auto-deleveraging settlements are not published on `/stream`, because they identify the accounts involved. Every book frame is a full top-20 snapshot rather than a delta, so a reconnect needs no replay. The server sends no heartbeat, and the public hosts close the connection about 30 seconds after it opens, so reconnect and resubscribe. The limits and channels below do not apply to `/stream`.

**`/ws`: account and public channels, token required.** Browsers cannot attach custom auth headers to a WebSocket upgrade, so this endpoint uses a short-lived token rather than a header:

1. Call `POST /ws/token`, signed with your HMAC key or a registered agent key (a normal signed REST request). This mints a **60-second, single-use** opaque token. Your secret never crosses the WebSocket boundary.
2. Open a WebSocket to `/ws?token=…` and subscribe with `{"op": "subscribe", "channel": "…", "market": "…"}` messages.

Tokens are single-use and reaped after 60 seconds, and they are only valid on the network that minted them. Mint a fresh one for each connection. The legacy `POST /ws-tokens` still mints tokens, but nothing on the current API needs them: `/stream` takes none and `/ws` takes one from `POST /ws/token`.

### Connection limits (`/ws`)

* Maximum **5 active connections per IP**, applied at upgrade time on every tier. A 6th connection is rejected with `HTTP 429` on the upgrade. Nothing is evicted, and the single-use token is spent, so mint a fresh one before retrying.
* A per-account connection cap applies on top of that: **5** at the Pro tier, **100** at MarketMaker.
* Subscriptions are capped per connection *and* per account at the same number (Pro 50, MarketMaker 1,000), so more sockets do not buy more subscriptions.
* Inbound client frames are limited per connection (Pro 10/s, MarketMaker 50/s) with a 2× burst; sustained flooding closes the connection with code `1008`.
* **These ceilings are their own budget.** They are independent of the REST request budget and of the trading-action budget. See [Rate Limits](https://docs.nexus.xyz/api-reference/guides/rate-limits).

### Channels (`/ws`)

Subscriptions are per-market where noted. Available channels:

| Channel        | Scope      | Payload                      |
| -------------- | ---------- | ---------------------------- |
| `book`         | per market | Order book depth updates     |
| `trades`       | per market | Executed trades              |
| `candles`      | per market | OHLCV candles                |
| `engine`       | global     | Engine throughput and status |
| `orders`       | account    | Order lifecycle updates      |
| `fills`        | account    | Your executed fills          |
| `positions`    | account    | Position changes             |
| `balances`     | account    | Balance changes              |
| `liquidations` | account    | Liquidation events           |

Account-scoped channels (`orders`, `fills`, `positions`, `balances`, `liquidations`) require an authenticated subscription tied to your token.

### Delivery targets

The system targets low-latency fan-out; published latency goals tighten across release gates (order-book and fill delivery measured from the matching event to client receipt). Current testnet behavior is suitable for development and integration testing.

> **Status:** testnet preview. Exact subscription message framing and per-channel schemas are defined in the OpenAPI spec at `/openapi.json` and in the [API Reference](https://docs.nexus.xyz/api-reference)'s WebSocket pages; use those as the authoritative source for message shapes.


---

# 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.nexus.xyz/apis-and-rates/apis-and-rates/exchange-websocket.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.
