Orders
The orders namespace of @getenginex/sdk-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 demo.
Price, quantity and enums
- Price: integer in cents. On a limit order (the default)
priceis required, from 1 to 99. On a market orderpriceis optional: omitted, the SDK sends0(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 withCONFIGURATION_ERROR, with no request (limit withprice: 0or withoutprice,100,60.5, orquantity: 0,1.5). postOnlyandreduceOnly, when provided, must be booleans.sideis'yes' | 'no',directionis'buy' | 'sell',orderTypeis'limit' | 'market'(defaultlimit) andtimeInForceis'gtc' | 'ioc' | 'fok'(defaultgtc). A value outside these also rejects before the request: the gateway would treat an unknownorderTypeaslimit, and an order different from the one requested costs money.- In the response,
statusispending,open,partial,filled,canceled,expiredorrejected, in lowercase and without the protobuf prefix, the same in REST and realtime.
Place an order
// 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:
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
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 balanceon the second doesn't undo the first. The result comes byindex(the position in the list sent), already in order, and failures don't become exceptions. The gateway returns only the error message, soerror.codeisundefined. - The batch route doesn't go through the gateway's idempotency middleware: there is no
Idempotency-Keyheader andoptions.idempotencyKeyis ignored. Each order carries a distinctidempotency_keyin the body: theidempotencyKeyyou pass on the order (trimmed; a repeat within the same batch isCONFIGURATION_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; checkorders.list()first. - In the mutations (
createPredictionsMutations,useEnginexMutations), the SDK does this for you: the keys are kept per result ofcreatePredictionsMutationsafter an ambiguous failure (network, timeout, 5xx,KEY_IN_USEorVALIDATION_ERRORafter 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. - The response is validated in
strictmode: it must carry the indexes0..n-1once each and theorderon each success; otherwise the call rejects withVALIDATION_ERROR. - An empty list or one with an invalid order rejects with
CONFIGURATION_ERRORbefore the request: no order goes out.
List, get, cancel and amend
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
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).
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):
placereturns anopenorder (collateral reserved); withorderType: 'market'it executes right away and becomes a position. The same idempotency key returns the same order, without creating another.- A market order without
priceexecutes at the side's last price, and the order'spricestays0. placeBatchplaces each order on its own: an unknownmarketIdfails that order (success: false) and the others proceed.- An unknown market gives
MARKET_NOT_FOUNDand an unknown order,ORDER_NOT_FOUND, both with HTTP 500, like the gateway. To simulateNO_LIQUIDITYorINSUFFICIENT_BALANCE, override the route:
import { fail } from '@getenginex/sdk/testing'
createMockFetch(
withPredictionsRoutes({
routes: { 'POST /api/v1/predictions/orders': () => fail(500, 'NO_LIQUIDITY', 'no liquidity') },
}),
)