---
url: https://game-engine-io.github.io/enginex-frontend-sdk/predictions/orders.md
---
# Orders

The `orders` namespace of [`@getenginex/sdk-predictions`](/predictions/) places, lists, cancels and amends
orders. **All methods require login**: without a session, they reject with `UNAUTHENTICATED` before any
request.

See an order being sent, with the `Idempotency-Key` and the book changing live, in the
[Live orderbook](/predictions/live-orderbook) demo.

## Price, quantity and enums

* **Price**: integer in cents. On a **limit** order (the default) `price` is required, from 1 to 99. On a
  **market** order `price` is optional: omitted, the SDK sends `0` (which is what the player app sends);
  provided, it is an integer from 0 to 99. **Quantity**: integer number of contracts, greater than zero. The
  gateway **doesn't validate** any of this, so the SDK rejects values outside the rules with
  `CONFIGURATION_ERROR`, with no request (limit with `price: 0` or without `price`, `100`, `60.5`, or
  `quantity: 0`, `1.5`).
* `postOnly` and `reduceOnly`, when provided, must be booleans.
* `side` is `'yes' | 'no'`, `direction` is `'buy' | 'sell'`, `orderType` is `'limit' | 'market'` (default
  `limit`) and `timeInForce` is `'gtc' | 'ioc' | 'fok'` (default `gtc`). A value outside these also
  rejects before the request: the gateway would treat an unknown `orderType` as `limit`, and an order
  different from the one requested costs money.
* In the response, `status` is `pending`, `open`, `partial`, `filled`, `canceled`, `expired` or `rejected`,
  in lowercase and without the protobuf prefix, the same in REST and realtime.

## Place an order

```ts
// Limit order: stays in the book until it executes or is canceled
const order = await predictions.orders.place({
  marketId: 'mkt-1',
  side: 'yes',
  direction: 'buy',
  price: 60, // 60 cents per contract
  quantity: 10,
})

// Market order: executes whatever is in the book right away, with no price (the SDK sends price: 0)
await predictions.orders.place({
  marketId: 'mkt-1',
  side: 'yes',
  direction: 'buy',
  orderType: 'market',
  timeInForce: 'ioc',
  quantity: 5,
})
```

The `PlaceOrderInput` type is a union discriminated by `orderType`: `price` is required on a limit order
and optional on a market order. A nonzero `price` on a market order is **not a cap guaranteed by the SDK**:
it is the predictions service that interprets it, and the production player app always sends `0`. Use it
only if you know what it does.

`place` returns the `Order` (the gateway answers HTTP 200). `postOnly: true` rejects the order if it would
cross the spread; `reduceOnly: true` only allows reducing an existing position.

## Idempotency and retry

`place` moves money, so it is **idempotent**. The same key goes in the `Idempotency-Key` header **and** in
the body's `idempotency_key` field (the gateway accepts both), and it is the same on the retry the SDK does
by itself after refreshing the session (401). Without `options.idempotencyKey`, the SDK generates one key
per call.

This protects session refresh, but **not** a network error: if the call fails with `NETWORK_ERROR` or
`TIMEOUT`, the order may or may not have reached the gateway. To retry without duplicating, generate the key
**once per player intent** (one click on "Buy"), store it and pass the same one on every attempt. Whitespace
at the ends of the key is trimmed, and the same text goes in the header and the body:

```ts
const key = crypto.randomUUID() // one per click, not one per attempt

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

async function buy() {
  for (let attempt = 0; ; attempt++) {
    try {
      return await predictions.orders.place(input, { idempotencyKey: key }) // same key: no duplicate order
    } catch (error) {
      const retryable =
        isEnginexError(error, 'NETWORK_ERROR') || isEnginexError(error, 'TIMEOUT') || isEnginexError(error, 'KEY_IN_USE')
      if (!retryable || attempt === 3) throw error
      await wait(500 * 2 ** attempt) // wait before retrying (see KEY_IN_USE below)
    }
  }
}
```

The gateway stores the key and protects against repetition with two errors, which arrive with the `code`
(the SDK delivers them even when they come in the middleware's raw format):

* `KEY_IN_USE` (HTTP 409): the first call with this key **is still being processed**. Wait (with *backoff*,
  as above) and retry with the **same** key; don't generate another, or the order may go out twice.
* `PAYLOAD_MISMATCH` (HTTP 422): the same key was used with a **different order** (another market, price or
  quantity). Each different intent needs a new key. (`INVALID_KEY`, HTTP 400, is a key outside the accepted
  format.)

On an insecure origin (`http://`, no `crypto.randomUUID`), the SDK generates the key with
`crypto.getRandomValues`. With no Web Crypto at all, it can't generate the key and rejects with
`CONFIGURATION_ERROR`: pass your own `idempotencyKey`.

A new key is a new order. An empty key (`''`) counts as absent and the SDK generates another.

## Batch

```ts
const results = await predictions.orders.placeBatch({
  orders: [
    { marketId: 'mkt-1', side: 'yes', direction: 'buy', price: 60, quantity: 10 },
    { marketId: 'mkt-2', side: 'no', direction: 'buy', price: 30, quantity: 5 },
  ],
})
for (const result of results) {
  if (result.success) console.log(result.index, result.order.id)
  else console.warn(result.index, result.error.message)
}
```

* The batch is **not atomic**: each order succeeds or fails on its own, and an `insufficient balance` on
  the second doesn't undo the first. The result comes **by `index`** (the position in the list sent),
  already in order, and failures don't become exceptions. The gateway returns only the error message, so
  `error.code` is `undefined`.
* The batch route **doesn't go through the gateway's idempotency middleware**: there is no
  `Idempotency-Key` header and `options.idempotencyKey` is ignored. Each order carries a **distinct**
  `idempotency_key` in the body: the `idempotencyKey` you pass on the order (trimmed; a repeat within the
  same batch is `CONFIGURATION_ERROR`) or one generated by the SDK, new on every call.
* To **safely retry a batch after a network error**, store the keys and resend the same ones on each order
  (`{ ...order, idempotencyKey: 'batch-7-a' }`). Without your own keys, **don't retry blindly**: the orders
  from the first send may have gone in; check `orders.list()` first.
* In the mutations (`createPredictionsMutations`, `useEnginexMutations`), the SDK does this for you: the
  keys are kept per result of `createPredictionsMutations` after an ambiguous failure (network, timeout,
  5xx, `KEY_IN_USE` or `VALIDATION_ERROR` after a 2xx) **or a partial success**, and are reused while the
  batch content stays the same. Full success, an unambiguous error or a different batch generate new
  keys. See [React](/frameworks/react#idempotency-in-mutations).
* The response is validated in `strict` mode: it must carry the indexes `0..n-1` once each and the `order`
  on each success; otherwise the call rejects with `VALIDATION_ERROR`.
* An empty list or one with an invalid order rejects with `CONFIGURATION_ERROR` before the request: no order
  goes out.

## List, get, cancel and amend

```ts
const orders = await predictions.orders.list() // fixed first page of 50; no filters or pagination
const one = await predictions.orders.get({ orderId: order.id })
const canceled = await predictions.orders.cancel({ orderId: order.id }) // status 'canceled'
const amended = await predictions.orders.amend({ orderId: order.id, newPrice: 55, newQuantity: 8 })
```

`amend` takes `newPrice` and/or `newQuantity` (with neither, `CONFIGURATION_ERROR` with no request) and
returns the updated order. The gateway implements it as cancel and replace, so **use the returned order**
(the `id` and the queue position may change). `amend` is **not idempotent**: it sends no key, and repeating
it after a network error may amend twice. Check the state with `get` first.

An `orderId` that is empty, has leading or trailing whitespace, or contains `/`, `.` or `..` rejects with
`CONFIGURATION_ERROR` before the request. The same goes for the `marketId` of `place`/`placeBatch`.

## Errors {#errors}

Always decide by `code`, not by HTTP status: several predictions codes arrive as **HTTP 500** because the
gateway doesn't map them (`MARKET_NOT_FOUND`, `MARKET_NOT_OPEN`, `ORDER_NOT_FOUND`, `NO_LIQUIDITY`).

```ts
try {
  await predictions.orders.place(input, { idempotencyKey: key })
} catch (error) {
  if (isEnginexError(error, 'INSUFFICIENT_BALANCE')) showDeposit()
  else if (isEnginexError(error, 'NO_LIQUIDITY')) notify('No offers at this price')
  else if (isEnginexError(error, 'MARKET_NOT_OPEN')) notify('Market closed')
  else throw error
}
```

## Testing

`withPredictionsRoutes()` includes the order routes (log in on the mock first: without a token they answer
`401`):

* `place` returns an `open` order (collateral reserved); with `orderType: 'market'` it executes right away
  and becomes a position. The **same** idempotency key returns the same order, without creating another.
* A market order without `price` executes at the side's last price, and the order's `price` stays `0`.
* `placeBatch` places each order on its own: an unknown `marketId` fails that order (`success: false`) and
  the others proceed.
* An unknown market gives `MARKET_NOT_FOUND` and an unknown order, `ORDER_NOT_FOUND`, both with HTTP 500,
  like the gateway. To simulate `NO_LIQUIDITY` or `INSUFFICIENT_BALANCE`, override the route:

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

createMockFetch(
  withPredictionsRoutes({
    routes: { 'POST /api/v1/predictions/orders': () => fail(500, 'NO_LIQUIDITY', 'no liquidity') },
  }),
)
```
