---
url: >-
  https://game-engine-io.github.io/enginex-frontend-sdk/predictions/live-orderbook.md
---
# Live orderbook

The demo above runs the real SDK (`createPredictions`, `createRealtime`) with `createMockFetch`,
`withPredictionsRoutes` and `createMockRealtime` from [`@getenginex/sdk/testing`](/guide/testing): no call
leaves for the network. The book is public: the base comes from `markets.getOrderbook` and **each
`orderbook_update` replaces the base** (the demo treats the message as the whole book, which is the safest
convention while the delta format is not confirmed, see the warning below). **Dropping the connection**
loses a trade on purpose and `onResync` reloads the book over HTTP. After login, the form sends a limit
order (price from 1 to 99) or a market order (no price) with `orders.place` and one `Idempotency-Key` per
intent; the submitted order also shows up in the book, through realtime. In the **Network failure**
scenario the response is lost and the retry reuses the key and gets the same order. The key appears
**masked** in the **Under the hood** panel, like the WebSocket URL (`token`).

`predictionsTopics.orderbook({ marketId })` announces every change in a market's orderbook without
polling. The concepts (connection, status, `onResync`) are in [Realtime](/concepts/realtime). The topic is
public: it works without login.

## 1. Base over HTTP, then realtime

The SDK does **not** apply deltas: the base comes from `markets.getOrderbook` and the app decides how to
combine the updates with it.

```ts
import { createRealtime } from '@getenginex/sdk/realtime'
import { createPredictions } from '@getenginex/sdk-predictions'
import { predictionsTopics } from '@getenginex/sdk-predictions/realtime'

const predictions = createPredictions(enginex)
const realtime = createRealtime(enginex)

async function loadBook(marketId: string) {
  const book = await predictions.markets.getOrderbook({ marketId, depth: 20 })
  render(book)
}

async function watchBook(marketId: string) {
  await loadBook(marketId) // initial base
  const topic = predictionsTopics.orderbook({ marketId })
  const off = realtime.subscribe(topic, (update, meta) => {
    // update: { marketId, bids, asks, lastPriceYes, lastPriceNo, spread, updatedAt }
    if (meta.kind === 'snapshot') return render(update) // full snapshot (sequenced mode)
    applyUpdate(update) // app rule, see the warning below
  })
  // after a drop and reconnection, reload the base over HTTP
  const offResync = realtime.onResync(topic, () => void loadBook(marketId))
  return () => {
    off()
    offResync()
  }
}
```

::: warning Delta semantics
The gateway publishes each `orderbook_update` in the orderbook format, but the SDK **does not guarantee**
the application convention: it is not verified whether a message carries the whole book or only the levels
that changed, nor whether `quantity: 0` removes the level. That is why the SDK has no merge helper. If your
gateway publishes partial levels, confirm the convention with the gateway team before merging; the safest
path is to treat each message as the current snapshot and reload over HTTP on `onResync`.
:::

## Snapshot in sequenced mode

Only in single-tenant mode (`WS_SEQUENCED=true`) does the gateway number the messages and send a snapshot
on subscribe. On the orderbook topic that snapshot has the same format as `orderbook_update` and is
delivered with `meta.kind === 'snapshot'` (and `meta.seq`). In multi-tenant production there is no
snapshot or `seq`: a message lost in a drop is not detectable, and `onResync` is what keeps the screen
right.

## Other topics

```ts
// executed trades
realtime.subscribe(predictionsTopics.trades({ marketId }), (trade) => {
  // { tradeId, marketId, side: 'yes' | 'no', price, quantity, makerFee, takerFee, executedAt }
})

// prices, volume and market status
realtime.subscribe(predictionsTopics.market({ marketId }), (m) => {
  // { marketId, eventId, status, lastPriceYes, lastPriceNo, volume24h, totalVolume, openInterest,
  //   bestBidYes?, bestAskYes?, bestBidNo?, bestAskNo?, updatedAt }
})
```

On `trades`, the sequenced-mode snapshot is the gateway's raw price history (a different format from
`trade_update`): the SDK **does not deliver it** (like the core's `balance`); new trades keep arriving,
and the base comes from `markets.getPriceHistory`. On `market`, the snapshot has the same format as
`market_update` and is delivered.

## Live orders

`predictionsTopics.orders()` is private: it uses the session's user and `realtime.subscribe` throws
`UNAUTHENTICATED` without login. Each status change of one of the user's orders arrives as an
`OrderStatusUpdate`:

```ts
const off = realtime.subscribe(predictionsTopics.orders(), (order) => {
  // { orderId, marketId, side, direction, status, price, quantity, filledQuantity, remainingQuantity,
  //   lastFillPrice?, lastFillQuantity?, lastFillTradeId?, updatedAt }
  if (order.status === 'filled') toast('Order filled')
})
// reload the orders over HTTP (private topic: applies to the session's user)
realtime.onResync(predictionsTopics.orders(), () => void predictions.orders.list())
```

`side`, `direction` and `status` arrive in lowercase (`'yes'`, `'buy'`, `'partial'`), even if the gateway
publishes `ORDER_SIDE_YES`: the SDK accepts both styles. Don't use the event to post a balance:
`wallet.getBalance()` and `coreTopics.balance()` are the source of the money.

## Testing

```ts
import { createMockRealtime } from '@getenginex/sdk/testing'

const mock = createMockRealtime()
const enginex = createEnginexClient({ /* ... */ webSocket: mock.webSocket })
// ... subscribe, wait for the connection to open
mock.emit('predictions:orderbook:mkt-1', 'orderbook_update', {
  market_id: 'mkt-1',
  bids: [{ price: 61, quantity: 100, order_count: 2 }],
  asks: [{ price: 63, quantity: 50, order_count: 1 }],
  last_price_yes: 62,
  last_price_no: 38,
  spread: 2,
  updated_at: '2026-09-30T12:00:00Z',
})
mock.emitSequenced('predictions:orderbook:mkt-1', 'snapshot', 1, { /* same payload */ })
```
