> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xentfi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Order Book

> How XentFi Pro's order book works — markets, order types, matching, and the order/trade lifecycle for programmatic trading.

<Note>
  This page explains the **concepts** behind XentFi Pro's order book. For the full request/response schema of every endpoint, see the [XentFi Pro API Reference](/xentfi-pro/overview).
</Note>

## Overview

XentFi Pro adds a hybrid **off-chain matching / on-chain settlement** order book on top of your existing XentFi wallets. Orders are matched off-chain for speed, and matched trades settle on-chain in batches — so you get exchange-grade order types and latency without giving up self-custody of the wallets involved.

```mermaid theme={null}
flowchart LR
    Order[POST /v1/orderbook/orders] --> Risk[Risk checks<br/>rate limit, price band]
    Risk --> Reserve[Atomic balance reservation]
    Reserve --> Book[Resting in order book]
    Book --> Batch[Batch auction<br/>every batchAuctionIntervalMs]
    Batch --> Match[Matched: price-time priority]
    Match --> Trade[Trade recorded<br/>maker + taker fees]
    Trade --> Settle[Settlement batch<br/>every 2s]
```

## Markets

A **market** is a trading pair (e.g. `USDC-USDT`) scoped to one blockchain, with its own tick size, lot size, order size limits, fee schedule, and batch-auction cadence.

| Field                           | Description                                                                                  |
| ------------------------------- | -------------------------------------------------------------------------------------------- |
| `symbol`                        | The market's trading pair, e.g. `USDC-USDT`.                                                 |
| `baseAssetId` / `quoteAssetId`  | The two assets being traded.                                                                 |
| `tickSize`                      | Minimum price increment.                                                                     |
| `lotSize`                       | Minimum quantity increment.                                                                  |
| `minOrderSize` / `maxOrderSize` | Order size bounds.                                                                           |
| `makerFeeBps` / `takerFeeBps`   | Fee schedule, in basis points.                                                               |
| `batchAuctionIntervalMs`        | How often resting orders are matched (default `250`ms).                                      |
| `maxDeviationFromMidBps`        | Price-band width used to reject fat-finger/spoofing orders.                                  |
| `status`                        | `ACTIVE`, `PAUSED`, `HALTED`, or `AUCTION_ONLY` — see [Market status](#market-status) below. |

Discover available markets with `GET /v1/orderbook/markets`, and a single market's live config with `GET /v1/orderbook/markets/{marketSymbol}`.

### Market status

New markets are created in `PAUSED` status by design — this gives you a chance to verify asset configuration and confirm the settlement wallet is funded before trading opens. A market moves to `ACTIVE` via `PATCH /v1/orderbook/markets/{marketSymbol}`.

| Status         | Meaning                                                                                          |
| -------------- | ------------------------------------------------------------------------------------------------ |
| `ACTIVE`       | Accepting and matching orders normally.                                                          |
| `PAUSED`       | Not yet activated, or paused by an operator (`pauseReason` explains why).                        |
| `HALTED`       | Trading stopped — typically a circuit breaker (e.g. gas price spike) or an operational incident. |
| `AUCTION_ONLY` | Only participates in batch auctions, no continuous matching.                                     |

## Order types

| Type                        | Behavior                                                                                                                                                                                                                                     |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LIMIT`                     | Rests on the book at your specified `price` until matched or cancelled.                                                                                                                                                                      |
| `MARKET`                    | Executes immediately against the best available price(s); no `price` field. Checked against the reference price oracle (see [Liquidity](/essentials/liquidity#price-oracle--market-order-protection)) to avoid walking a thin or stale book. |
| `POST_ONLY`                 | Only ever adds liquidity — rejected instead of matching immediately, so it never pays taker fees.                                                                                                                                            |
| `IOC` (Immediate-Or-Cancel) | Fills whatever is immediately available, cancels the rest.                                                                                                                                                                                   |
| `FOK` (Fill-Or-Kill)        | Fills completely and immediately, or is cancelled entirely — no partial fills.                                                                                                                                                               |

`timeInForce` (`GTC`, `IOC`, `FOK`, `GTT`) is set independently of `type` and controls how long an order (typically a `LIMIT`) is allowed to rest before it's cancelled.

## Placing an order

```bash theme={null}
curl -X POST https://api.pro.xentfi.com/v1/orderbook/orders \
  -H "apiKey: your-api-key" \
  -H "orgId: your-org-id" \
  -H "Content-Type: application/json" \
  -d '{
    "marketSymbol": "USDC-USDT",
    "walletId": "your-wallet-id",
    "side": "BUY",
    "type": "LIMIT",
    "timeInForce": "GTC",
    "price": "1.0002",
    "quantity": "500",
    "clientOrderId": "my-app-order-00147"
  }'
```

`clientOrderId` is your own idempotency key, unique per organization + app — always set one so a retried request after a timeout can't place the same order twice.

<Warning>
  A `201` response means the order was **admitted** to the book, not that it filled. Matching happens asynchronously on the market's batch-auction cadence. Poll `GET /v1/orderbook/orders/{orderId}` or subscribe to your private realtime channel (see below) to track fills.
</Warning>

## Order lifecycle

```mermaid theme={null}
stateDiagram-v2
    [*] --> PENDING_RISK
    PENDING_RISK --> OPEN: risk checks + balance reservation pass
    PENDING_RISK --> REJECTED: risk checks fail
    OPEN --> PARTIALLY_FILLED: partial match
    OPEN --> FILLED: full match
    OPEN --> CANCELLED: cancel request
    PARTIALLY_FILLED --> FILLED: remaining quantity matches
    PARTIALLY_FILLED --> CANCELLED: cancel request
    FILLED --> [*]
    CANCELLED --> [*]
    REJECTED --> [*]
```

Only orders in `OPEN` or `PARTIALLY_FILLED` status can be cancelled (`DELETE /v1/orderbook/orders/{orderId}`) — the reserved balance behind the order is released atomically as part of cancellation.

## Fees

Every trade charges the **maker** (the resting order that got matched against) and the **taker** (the order that triggered the match) separately, per the market's `makerFeeBps` / `takerFeeBps`. Maker fees are typically lower — sometimes zero or rebated — to reward the side providing liquidity. Fees are visible per trade on `Trade.makerFee` / `Trade.takerFee`.

## Market data

| Endpoint                                           | Returns                                                                        |
| -------------------------------------------------- | ------------------------------------------------------------------------------ |
| `GET /v1/orderbook/markets/{marketSymbol}/book`    | Current bid/ask depth snapshot, with a `sequence` number for websocket resync. |
| `GET /v1/orderbook/markets/{marketSymbol}/trades`  | Recent trades, most recent first.                                              |
| `GET /v1/orderbook/markets/{marketSymbol}/ticker`  | 24h open/high/low/last/volume.                                                 |
| `GET /v1/orderbook/markets/{marketSymbol}/candles` | OHLCV candles at `1m`/`5m`/`15m`/`1h`/`4h`/`1d` intervals.                     |

## Realtime updates

Rather than polling, subscribe to your organization's private order-update channel for pushed fills, cancels, and rejects:

```bash theme={null}
curl -X POST https://api.pro.xentfi.com/v1/orderbook/realtime/auth \
  -H "apiKey: your-api-key" \
  -H "orgId: your-org-id" \
  -H "Content-Type: application/json" \
  -d '{ "socket_id": "...", "channel_name": "private-orders-your-org-id" }'
```

Order book depth updates are published per-market and carry a WAL `sequence` number — if your client detects a gap, resync with `GET /v1/orderbook/markets/{marketSymbol}/book` rather than assuming continuity.

## Your trade history

* `GET /v1/orderbook/orders/{orderId}/trades` — fills for a specific order, whether it was maker or taker.
* `GET /v1/orderbook/wallets/{walletId}/trades` — full trade history for a wallet. Only visible if your organization has itself placed an order with that wallet.

## API Reference

| Endpoint                                       | Method      | Description                          |
| ---------------------------------------------- | ----------- | ------------------------------------ |
| `/v1/orderbook/orders`                         | POST        | Place an order                       |
| `/v1/orderbook/orders`                         | GET         | List orders                          |
| `/v1/orderbook/orders/{orderId}`               | GET         | Get an order                         |
| `/v1/orderbook/orders/{orderId}`               | DELETE      | Cancel an order                      |
| `/v1/orderbook/orders/{orderId}/trades`        | GET         | Fills for an order                   |
| `/v1/orderbook/wallets/{walletId}/trades`      | GET         | Trade history for a wallet           |
| `/v1/orderbook/markets`                        | GET / POST  | List / create markets                |
| `/v1/orderbook/markets/{marketSymbol}`         | GET / PATCH | Get / update a market                |
| `/v1/orderbook/markets/{marketSymbol}/book`    | GET         | Order book depth                     |
| `/v1/orderbook/markets/{marketSymbol}/trades`  | GET         | Recent trades                        |
| `/v1/orderbook/markets/{marketSymbol}/ticker`  | GET         | 24h ticker                           |
| `/v1/orderbook/markets/{marketSymbol}/candles` | GET         | OHLCV candles                        |
| `/v1/orderbook/realtime/auth`                  | POST        | Authorize a private realtime channel |

Full request/response schemas: [XentFi Pro API Reference](/xentfi-pro/overview).

## Related

<CardGroup cols={3}>
  <Card title="Liquidity & Settlement" icon="waves" href="/essentials/liquidity">
    How matched trades settle on-chain and how to keep a market funded.
  </Card>

  <Card title="XentFi Pro Quickstart" icon="rocket" href="/xentfi-pro/quickstart">
    Place your first order end to end.
  </Card>

  <Card title="XentFi Pro Authentication" icon="key" href="/xentfi-pro/authentication">
    Get an API key with the Trade scope.
  </Card>
</CardGroup>
