> For the complete documentation index, see [llms.txt](https://docs.koinju.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.koinju.io/data/order-book.md). Agents can also search and read this documentation through its [MCP server](https://docs.koinju.io/~gitbook/mcp).

# Order books

Historical crypto order books over SQL and REST. Get the book of a market at any time, and the cost of an order on it. The data comes from the native messages of Binance, Bybit, OKX, Kraken and Hyperl

Koinju keeps the order book in the native message format of each exchange. Two parameterized views give the book of one market at one time, and the market impact of an order on that book. The raw messages are in a table that you can also query. Two [REST endpoints](#rest-api) give the same books as JSON.

The order books are included in Professional and Enterprise. See [Data access by tier](#data-access-by-tier).

## SQL API

### `public_data.raw_orderbook`

The raw messages: one row for each message of the exchange.

| Column       | Type                   | Description                                                                                                                                          |
| ------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `exchange`   | LowCardinality(String) | The exchange ID.                                                                                                                                     |
| `market`     | String                 | The exchange's own symbol for the market.                                                                                                            |
| `ts`         | DateTime64(3, 'UTC')   | The time of the exchange for the message.                                                                                                            |
| `event_type` | Enum8                  | `update` or `snapshot`.                                                                                                                              |
| `seq`        | UInt64                 | The number of the message. Its meaning depends on the exchange, see below.                                                                           |
| `prev_seq`   | UInt64                 | For an update, the `seq` of the message before it, on the exchanges that link their messages. 0 for a snapshot, and for Kraken Spot and Hyperliquid. |
| `raw`        | String                 | The message as JSON, in the format of the exchange.                                                                                                  |

| Exchange IDs                        | `raw`                                                                          | `seq`                                                          | Levels of a snapshot, on each side     |
| ----------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------- | -------------------------------------- |
| `binance`, `binance-usdm-future`    | `depthUpdate` messages, and snapshots with `lastUpdateId`, `bids` and `asks`   | the final update ID `u`                                        | tens of thousands for a busy market    |
| `bybit`, `bybit-usdm-future`        | `orderbook.50` messages of type `delta` and `snapshot`                         | the update ID `u`                                              | up to 50                               |
| `okx`, `okx-future`                 | `books` messages with `action` `update` and `snapshot`. Their `checksum` is 0. | `seqId`                                                        | up to 400                              |
| `kraken`                            | `book` messages of the version 2 API                                           | the receive time in nanoseconds. Kraken Spot has no update ID. | up to 1,000                            |
| `kraken-future`                     | `book` and `book_snapshot` messages                                            | `seq`. It can start again at a new snapshot.                   | about 1,000 to 2,000 for a busy market |
| `hyperliquid`, `hyperliquid-future` | `l2Book` messages. Each one is a snapshot, with the type `snapshot`.           | the time of the message in milliseconds                        | up to 20                               |

* Until a merge of the table, a message can show two times. Read with `FINAL`, or keep one row with `LIMIT 1 BY exchange, event_type, market, ts, seq`.
* Always filter on `exchange`, `event_type`, `market` and a range of `ts`. That is the order of the table.

### `api.order_book`

The book of one market at one time. The view starts from the last snapshot at or before `at`, in the 24 hours before `at`. Then it applies each update after that snapshot, up to `at`. With no such snapshot, `bids` and `asks` are empty and `snapshot_seq` is NULL. A symbol that the exchange does not use, for example the Koinju symbol `BTC-USDT-PERP`, also gives an empty book.

#### Parameters

| Parameter  | Type                 | Description                                                                                                                                                                                                         |
| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `exchange` | String               | An exchange ID                                                                                                                                                                                                      |
| `market`   | String               | The exchange's own symbol for the market. For example `BTCUSDT` (Binance, Bybit), `BTC-USDT` and `BTC-USDT-SWAP` (OKX), `BTC/USD` (Kraken Spot), `PF_XBTUSD` (Kraken Futures), `BTC` and `HYPE_USDC` (Hyperliquid). |
| `at`       | DateTime64(3, 'UTC') | A time in UTC, to the millisecond.                                                                                                                                                                                  |

#### Columns

| Column            | Type                                        | Description                                                     |
| ----------------- | ------------------------------------------- | --------------------------------------------------------------- |
| `bids`            | Array(Tuple(price String, quantity String)) | The bid levels, from the highest price.                         |
| `asks`            | Array(Tuple(price String, quantity String)) | The ask levels, from the lowest price.                          |
| `snapshot_seq`    | Nullable(UInt64)                            | The `seq` of the snapshot that the book starts from.            |
| `updates_applied` | UInt64                                      | The number of updates that the view applied after the snapshot. |
| `snapshot_age_ms` | Nullable(Int64)                             | The time from the snapshot to `at`, in milliseconds.            |

* The prices and the quantities are the strings that the exchange sent. The view does not round them.
* Kraken Spot and Kraken Futures send numbers, not strings, and the view reads them as `Float64`. Thus `50.0` shows as `50`, `0.00000001` shows as `1e-8`, and a number keeps at most 17 significant digits.

### `api.order_book_impact`

The cost to buy or to sell a quantity at the time `at`, on the book of `api.order_book`. It takes the three parameters above, and two more:

| Parameter  | Type                 | Description                                                                                                                                                                                                         |
| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `exchange` | String               | An exchange ID                                                                                                                                                                                                      |
| `market`   | String               | The exchange's own symbol for the market. For example `BTCUSDT` (Binance, Bybit), `BTC-USDT` and `BTC-USDT-SWAP` (OKX), `BTC/USD` (Kraken Spot), `PF_XBTUSD` (Kraken Futures), `BTC` and `HYPE_USDC` (Hyperliquid). |
| `at`       | DateTime64(3, 'UTC') | A time in UTC, to the millisecond.                                                                                                                                                                                  |
| `side`     | String               | `buy` takes the asks, `sell` takes the bids. Another value gives an error.                                                                                                                                          |
| `quantity` | Float64              | The quantity, in the unit of the book of the exchange. For OKX perpetual swaps, that unit is contracts.                                                                                                             |

| Column                              | Type              | Description                                                                                                                       |
| ----------------------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `best_bid`, `best_ask`, `mid_price` | Nullable(Float64) | The top of the book, and the mean of the two.                                                                                     |
| `filled_quantity`                   | Float64           | The quantity that the book can fill. It is less than `quantity` when the book is too small.                                       |
| `mean_price`                        | Nullable(Float64) | The mean price of the fill.                                                                                                       |
| `worst_price`                       | Nullable(Float64) | The price of the last level that the fill uses.                                                                                   |
| `levels_used`                       | UInt32            | The number of levels that the fill uses.                                                                                          |
| `impact_bps`                        | Nullable(Float64) | The cost of the fill against `mid_price`, in basis points. It is positive when a buy fills above `mid_price`, or a sell below it. |

The view adds the quantities of the levels as exact decimals.

***

#### Data Access by Tier

| Data        | Free | Developer | Professional           | Enterprise             |
| ----------- | ---- | --------- | ---------------------- | ---------------------- |
| Order books | —    | —         | Full available history | Full available history |

On a Free or Developer plan, a call of the views fails with error 47, `Unknown expression or function identifier snapshot`. That error means that the plan has no access to the order books.

A Professional SQL query has a maximum execution time of 60 seconds and a memory limit of 2 GB. The plan's daily result allowance also applies. See [Pricing](https://docs.koinju.io/pricing.md#sql-limits).

***

#### Performance

A book takes longer when more updates follow its snapshot. Most markets get a snapshot about once an hour. Kraken Spot gets fewer, and each Hyperliquid message is a snapshot.

* A book of a quiet market takes less than a second.
* A book of a busy market far from its snapshot takes several seconds. For example, `BTCUSDT` on Binance USD-M Futures takes about 2 to 7 seconds at 30 minutes after the hour.
* For the fastest answer, ask for a time soon after a snapshot.

#### Known limits

* The view does not check the chain of the update IDs. After a lost update, the book is wrong and shows no sign of it, until the next snapshot.
* For Kraken Spot, a group of markets can be silent for 2 to 4 seconds before their new snapshots. The updates of that time are missing in the data. The book is correct again from the new snapshot.

***

### Example Queries

#### 1. The full book at one time

```sql
SELECT bids, asks, updates_applied, snapshot_age_ms
FROM api.order_book(exchange = 'okx', market = 'BTC-USDT', at = '2026-05-20 12:05:00')
```

#### 2. The cost of a buy of 100 BTC

```sql
SELECT filled_quantity, mean_price, worst_price, levels_used, impact_bps,
       (mean_price - mid_price) * filled_quantity AS cost_usdt
FROM api.order_book_impact(exchange = 'binance-usdm-future', market = 'BTCUSDT',
                           at = '2026-11-20 12:05:00', side = 'buy', quantity = 100)
```

On that book, the buy uses 210 levels. It pays 3.06 basis points, or 1,883 USDT, more than the mid price.

#### 3. The spread and the depth near the mid price

The spread, and the quantity of the bids and of the asks within 10 basis points of the mid price.

```sql
WITH toFloat64(bids[1].1) AS best_bid, toFloat64(asks[1].1) AS best_ask, (best_bid + best_ask) / 2 AS mid
SELECT best_bid, best_ask, (best_ask - best_bid) / mid * 10000 AS spread_bps,
    arraySum(l -> toFloat64(l.2), arrayFilter(l -> toFloat64(l.1) >= mid * 0.999, bids)) AS bid_depth,
    arraySum(l -> toFloat64(l.2), arrayFilter(l -> toFloat64(l.1) <= mid * 1.001, asks)) AS ask_depth
FROM api.order_book(exchange = 'binance-usdm-future', market = 'BTCUSDT', at = '2026-10-18 12:05:00')
```

#### 4. One market on three exchanges

The cost of a buy of 2 BTC at the same time on Binance, Bybit and OKX.

```sql
SELECT 'binance' AS exchange, filled_quantity, mean_price, impact_bps
FROM api.order_book_impact(exchange = 'binance', market = 'BTCUSDT', at = '2026-10-18 12:05:00', side = 'buy', quantity = 2)
UNION ALL
SELECT 'bybit', filled_quantity, mean_price, impact_bps
FROM api.order_book_impact(exchange = 'bybit', market = 'BTCUSDT', at = '2026-10-18 12:05:00', side = 'buy', quantity = 2)
UNION ALL
SELECT 'okx', filled_quantity, mean_price, impact_bps
FROM api.order_book_impact(exchange = 'okx', market = 'BTC-USDT', at = '2026-10-18 12:05:00', side = 'buy', quantity = 2)
```

#### 5. The raw tape of one second

```sql
SELECT ts, seq, prev_seq, raw
FROM public_data.raw_orderbook
WHERE exchange = 'bybit-usdm-future'
  AND event_type IN ('snapshot', 'update')
  AND market = 'BTCUSDT'
  AND ts >= '2026-11-20 12:00:00' AND ts < '2026-11-20 12:00:01'
ORDER BY ts, seq
LIMIT 1 BY exchange, event_type, market, ts, seq
```

#### 6. The markets of an exchange

The symbols to use in `market`, and the snapshots of each one on one day.

```sql
SELECT market, uniqExact(ts, seq) AS snapshots
FROM public_data.raw_orderbook
WHERE exchange = 'okx' AND event_type = 'snapshot'
  AND ts >= '2026-10-18 00:00:00' AND ts < '2026-10-19 00:00:00'
GROUP BY market
ORDER BY market
```

## REST API

Two endpoints of `https://api.koinju.io` give the same data as the two views, as JSON. They are included in Professional and Enterprise. Send your API key in the `x-api-key` header, as for the other endpoints of [How to connect](https://docs.koinju.io/how-to-connect.md#rest-api).

### `GET /order-book`

The book of one market at one time, as `api.order_book` gives it.

| Parameter  | Required | Description                                                                                                      |
| ---------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `exchange` | Yes      | An exchange ID of the order books, for example `binance-usdm-future`.                                            |
| `market`   | Yes      | The exchange's own symbol for the market, as for the views. For example `BTCUSDT`, not `BTC-USDT-PERP`.          |
| `at`       | Yes      | A time in ISO 8601, for example `2026-11-20T12:05:00Z`. Milliseconds are allowed. A time with no zone is in UTC. |
| `depth`    | No       | The levels on each side, from 1 to 5,000. With no `depth`, the answer holds the full book.                       |

{% code overflow="wrap" %}

```bash
curl -s -H 'x-api-key: YOUR_API_KEY' \
  'https://api.koinju.io/order-book?exchange=binance-usdm-future&market=BTCUSDT&at=2026-11-20T12:05:00Z&depth=3'
```

{% endcode %}

The answer is one JSON object. The prices and the quantities are the strings of the exchange. `snapshot_seq` is a string too, because some exchanges give numbers above 2^53.

```json
{
  "exchange": "binance-usdm-future",
  "market": "BTCUSDT",
  "at": "2026-11-20T12:05:00.000Z",
  "bids": [
    {"price": "61541.40", "quantity": "14.760"},
    {"price": "61541.10", "quantity": "0.004"},
    {"price": "61540.40", "quantity": "3.540"}
  ],
  "asks": [
    {"price": "61541.50", "quantity": "0.165"},
    {"price": "61541.60", "quantity": "0.002"},
    {"price": "61541.70", "quantity": "0.002"}
  ],
  "snapshot_seq": "12178389643899",
  "updates_applied": 11463,
  "snapshot_age_ms": 300139
}
```

With no `depth`, this book holds 15,120 bids and 12,654 asks.

### `GET /order-book/impact`

The cost to buy or to sell a quantity at the time `at`, as `api.order_book_impact` gives it.

| Parameter                  | Required | Description                                                                                                 |
| -------------------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| `exchange`, `market`, `at` | Yes      | As for `/order-book`.                                                                                       |
| `side`                     | Yes      | `buy` takes the asks, `sell` takes the bids.                                                                |
| `quantity`                 | Yes      | A positive number, in the unit of the book of the exchange. For OKX perpetual swaps, the unit is contracts. |

{% code overflow="wrap" %}

```bash
curl -s -H 'x-api-key: YOUR_API_KEY' \
  'https://api.koinju.io/order-book/impact?exchange=binance-usdm-future&market=BTCUSDT&at=2026-11-20T12:05:00Z&side=buy&quantity=1'
```

{% endcode %}

```json
{
  "exchange": "binance-usdm-future",
  "market": "BTCUSDT",
  "at": "2026-11-20T12:05:00.000Z",
  "side": "buy",
  "quantity": 1,
  "best_bid": 61541.4,
  "best_ask": 61541.5,
  "mid_price": 61541.45,
  "filled_quantity": 1,
  "mean_price": 61542.8233,
  "worst_price": 61543.5,
  "levels_used": 10,
  "impact_bps": 0.2232
}
```

A buy of 1 BTC at that time takes 10 levels of the asks, and it costs 0.22 basis points more than the mid price.

### Errors

| Status | When                                                                                                                    | Body                                                                           |
| ------ | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `403`  | No API key, a key that is not valid, or a plan with no order books                                                      | `message`. For a Free or Developer plan, also `pricing_url` and `discord_url`. |
| `422`  | An unknown exchange, an `at` that is not a time, or a bad `side`, `quantity` or `depth`                                 | `message` and `docs_url`                                                       |
| `422`  | No book: no snapshot in the 24 hours before `at`. A market that is not the symbol of the exchange gives this error too. | `message` and `docs_url`                                                       |
| `429`  | More calls than the throttle of the plan, or a daily quota that is used                                                 | `message`                                                                      |
| `502`  | The book took more than 25 seconds, or the database failed                                                              | `message`                                                                      |

### Limits

* Each of the two endpoints takes 1 call a second on the Professional plan, with a burst of 2.
* The calls count toward Professional's 1,000 REST requests per day. SQL has a separate daily result allowance. See [Pricing](https://docs.koinju.io/pricing.md).
* An answer takes as long as the same book in the view, see [Performance](#performance). Set a timeout of 30 seconds in your client.
