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

# streams

OCX offers three streaming transports: WebSocket for interactive subscriptions, and Server-Sent Events (SSE) for fire-and-forget read-only streams.

## Envelope

Every streamed message uses the same envelope, regardless of transport:

```json
{
  "eventId":       "price-123456-1714000000000",
  "eventType":     "PerpPrice",
  "eventSeq":      123456,
  "engineTs":      1714000000000,
  "sourceTs":      1714000000000,
  "correlationId": null,
  "causationId":   null,
  "payload":       { /* event-specific */ }
}
```

| Field           | Description                                                   |
| --------------- | ------------------------------------------------------------- |
| `eventId`       | Unique per message: `{type}-{seq}-{ts}`                       |
| `eventType`     | Discriminator — branch on this                                |
| `eventSeq`      | Monotonic per-stream sequence                                 |
| `engineTs`      | OCX engine timestamp (unix ms)                                |
| `sourceTs`      | Upstream data timestamp (unix ms). `null` for internal events |
| `correlationId` | Optional request correlation                                  |
| `causationId`   | If this event is caused by another, its ID                    |
| `payload`       | Event-specific body                                           |

## Reconnection & gap recovery

* Track the last `eventSeq` you've processed per stream.
* On reconnect, the server sends a fresh snapshot. Treat that snapshot as the new baseline.
* If you observe a gap (received `seq N`, next is `seq N+2`) on the same connection, reconnect to force a snapshot resync.
* Hot-path streams maintain a replay buffer of 5,000 frames, so short client pauses usually don't require a full snapshot.

***

## Available streams

| Endpoint                         | Transport |   Auth   | Emits                               |
| -------------------------------- | --------- | :------: | ----------------------------------- |
| `GET /ws/perps/prices`           | WebSocket |  public  | Perp mark price ticks               |
| `GET /perps/book-stream`         | SSE       |  public  | Linear orderbook snapshots + deltas |
| `GET /markets/board/stream`      | SSE       |  public  | Options board snapshots + deltas    |
| `GET /stream/options/ticks`      | SSE       |  public  | Option tick snapshots + deltas      |
| `GET /ws/feeds`                  | WebSocket |  public  | Options orderbook + fills           |
| `GET /ws/quotes`                 | WebSocket |  public  | Quote stream                        |
| `GET /portfolio/balances/stream` | SSE       | required | Balance snapshots                   |

***

## Subscription protocol (WebSocket)

Clients send JSON frames; the server acks.

### Subscribe

```json
{
  "method": "subscribe",
  "subscription": {
    "type": "prices",
    "symbol": "BTC-PERP"
  }
}
```

Server ack:

```json
{ "type": "ack", "subscription": { "type": "prices", "symbol": "BTC-PERP" } }
```

### Unsubscribe

```json
{
  "method": "unsubscribe",
  "subscription": { "type": "prices", "symbol": "BTC-PERP" }
}
```

### Ping / Pong

Clients should send a text `"ping"` every 30 seconds to keep the connection alive. The server replies with `"pong"`. If the server doesn't receive a ping for 90 seconds, it closes the connection.

***

## Example — subscribing to perp prices

```js
const ws = new WebSocket('wss://api.ocx.global/ws/perps/prices');

ws.onopen = () => {
  ws.send(JSON.stringify({
    method: 'subscribe',
    subscription: { type: 'prices', symbol: 'BTC-PERP' }
  }));
};

ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  if (msg.eventType === 'PerpPrice') {
    console.log(msg.payload.symbol, msg.payload.price);
  }
};

// Keep-alive
setInterval(() => ws.readyState === 1 && ws.send('ping'), 30000);
```

***

## Example — subscribing to the linear orderbook (SSE)

```js
const es = new EventSource(
  'https://api.ocx.global/perps/book-stream?marketId=BTC-PERP'
);

es.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  if (msg.eventType === 'OrderbookSnapshot') {
    book = applySnapshot(msg.payload);
  } else if (msg.eventType === 'OrderbookDelta') {
    book = applyDelta(book, msg.payload);
  }
};
```

The first message after connection is always an `OrderbookSnapshot`. Subsequent messages are `OrderbookDelta`s that mutate the snapshot in place.

***

## Example — option tick stream (SSE)

```js
const es = new EventSource(
  'https://api.ocx.global/stream/options/ticks?underlying=BTC'
);

es.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  // msg.eventType: "OptionSnapshot" or "OptionDelta"
  // msg.payload.ticks: array of { instrumentId, bid, ask, mark, iv, delta }
};
```

***

## Payload shapes

### Perp price

```json
{
  "kind":   "price",
  "symbol": "BTC-PERP",
  "price":  "67450.00",
  "tsMs":   1714000000000
}
```

### Orderbook snapshot

```json
{
  "kind":     "snapshot",
  "marketId": "BTC-PERP",
  "sequence": 123456,
  "bids":     [["67450", "0.5"], ["67449", "1.2"]],
  "asks":     [["67451", "0.3"], ["67452", "0.8"]]
}
```

### Orderbook delta

```json
{
  "kind":     "delta",
  "marketId": "BTC-PERP",
  "sequence": 123457,
  "changes": [
    { "side": "bid", "price": "67450", "size": "0.8" },
    { "side": "ask", "price": "67452", "size": "0" }
  ]
}
```

A `size` of `"0"` means the level was removed.

### Option tick

```json
{
  "kind": "delta",
  "seq": 43,
  "ticks": [
    {
      "instrumentId": "BTC-2026-06-26-60000-C",
      "bid":          "0.045",
      "ask":          "0.055",
      "mark":         "0.050",
      "iv":           "0.65",
      "delta":        "0.52"
    }
  ]
}
```


---

# 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:

```
GET https://ocx.gitbook.io/ocx-doc/ocx/api/streams.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
