TypeScript SDK
A thin, typed client over /api/v1. Every money figure is computed on the server and returned as an exact instruction, so the client never derives one itself.
Getting it
The client has no dependencies and uses the platform fetch, so it runs unchanged in Node, a worker or an edge runtime. You can inject a fetch for tests or a proxy.
import { ParityClient } from './parity-sdk'; // the client Parity provides
const parity = new ParityClient({
baseUrl: process.env.PARITY_BASE!, // the host issued to you
apiKey: process.env.PARITY_KEY!, // pk_test_… sandbox, sk_live_… live
timeoutMs: 15_000, // per-request deadline (default)
maxRetries: 2, // GETs only (default)
});
const player = parity.forUser('your-own-player-id');- Catalogue and reporting calls are on the client. Calls for one end user are on
forUser, so theX-Parity-Userheader is always sent. parity.environmentis read from the key prefix. The real boundary is your tenant's mode on the server; the prefix at least tells you which key you hold.parity.rateLimitcarries the limiter's own figures from the last response, on success as well as refusal.
Parity sends the SDK as source files on request. This page describes version 1.0.1, and every request the SDK makes carries its version in the user agent, parity-sdk/1.0.1. Quote that version when you contact Parity, and ask for the current one before you go live.
Money is a Decimal, never a number
Every exact amount is a branded Decimal: a string at runtime, and not assignable from string or number at compile time. This stops you parsing "12.30" as a float, which shows up later as a reconciliation off by a cent.
import { toMinorUnits, addDecimal, formatDecimal } from './parity-sdk'; // the client Parity provides
const debit = order.operatorMoney!.actualDebit; // Decimal, "12.30"
toMinorUnits(debit); // 1230n, exact, bigint, the only way to do arithmetic
addDecimal(debit, release); // "25.00"
formatDecimal(debit); // "$12.30", display only. Never book from a formatter.
const wrong: Decimal = 12.30; // ✗ type error, which is the pointThe SDK checks the money contract before you see it
Both identities are asserted on every response, in exact minor units: authorizationAmount = actualDebit + releaseAmount and actualDebit = tradeAmount + platformFee + operatorFee + venueFee. A response that breaks one throws MoneyIntegrityError rather than returning.
Parity computes every figure so that both hold. If one breaks, do not book it: stop posting for that order, keep the raw response with its parity-request-id, and send both to Parity support. A changed payload or an outdated test fixture can cause it; treat it as unexplained until it is investigated.
The direction is checked too: a sell carrying an authorizationAmount throws, so a wallet cannot debit a player for selling their own position.
The standard integration, end to end
You own the customer's cash ledger. Parity prices, routes and fills, and tells you the exact amounts to apply.
// 1. Find something tradable. `executableYesCents` is the PRICE;
// `probability` is the market's reference and nobody trades at it.
const page = await parity.listEvents({ tradable: true, limit: 5 });
const outcome = page.items
.flatMap((e) => e.outcomes)
.find((o) => o.executableYesCents !== null);
// 2. Price it. Show the player `executionPrice`, and let them confirm.
const quote = await player.quoteBuy({
contractId: outcome.id, // the opaque ctr_… id from the catalogue
side: 'YES',
stake: 25,
});
// 3. Record the order. `clientOrderId` is your idempotency key. Derive it
// from your own reservation, never from a clock: it has to survive the
// crash that loses you our response.
//
// The order comes back `reserve_pending`, which has no transition to
// `submitted` in the state machine. Nothing can send an order whose
// customer funds nobody has confirmed are held.
const order = await player.submitOrder({
quoteId: quote.quoteId,
clientOrderId: reservationId,
executionIntent: 'record_intent',
});
// 4. Reserve the AUTHORITATIVE amount in YOUR OWN ledger, then say so.
try {
await wallet.reserve(order.operatorMoney!.authorizationAmount, reservationId);
} catch (err) {
// 5a. Could not hold it. Withdraw the order and release exactly what the
// instruction says, keyed on `cancellationId`, so a lost response
// cannot become a second credit.
const { cancellation } = await player.cancelOrder(order.orderId, { reason: 'insufficient funds' });
await wallet.release(cancellation.releaseAmount, cancellation.cancellationId);
throw err;
}
// 5b. Held. This is idempotent: a timeout here is resent, not investigated.
await player.confirmReserve(order.orderId, { reserveReference: reservationId });
// → status `pending_venue_execution`. The order is cleared to execute, under
// these same state names.
// In the sandbox this same call fills it instead, so it comes back `filled`.An order is not a fill
pending_venue_execution is a funded, recorded order, not a trade. A position opens when a fill arrives, and simulated on the response says whether that fill was produced locally.
A fill carries operatorMoney.actualDebit to take and operatorMoney.releaseAmount to hand back. On a partial fill the release is non-zero; debiting the whole stake would keep the customer's money.
executionIntent: 'simulate' fills immediately and creates a position. That is sandbox behaviour, and so is a recorded intent filling when its reserve is confirmed. See Sandbox.
Exiting
// A sell is sized in CONTRACTS. A cash-sized exit cannot express "close out",
// because inverting the fee rounding either oversells or strands a fraction.
const [held] = (await player.listPositions({ status: 'open' })).items;
const exitQuote = await player.quoteSell({
contractId: held.contractId,
side: held.side,
contracts: held.quantity / 2, // a partial exit
});
const exit = await player.submitOrder({
quoteId: exitQuote.quoteId,
clientOrderId: `exit-${reservationId}`,
});
// An exit CREDITS. `sellProceeds` is already net of the fees reported beside
// it. Subtracting them again is a double charge. `operatorMoney` is null.
// Credit it once the sale is final: at once in the sandbox, later on a live account.
const sold = await player.getOrder(exit.orderId);
if (sold.settlementState === 'settled') {
await wallet.credit(sold.operatorExitMoney!.sellProceeds, sold.orderId);
}Settling
// Resume from where the last run stopped. undefined on the first run.
let cursor = await store.readSettlementCursor();
for await (const s of parity.iterateSettlements({ cursor })) {
// Exactly one is non-zero; a loss zeroes both. They are different
// instructions to book: winnings against a wager, versus a refund that
// reverses one.
if (s.outcome === 'won') await wallet.credit(s.operatorMoney.settlementCredit, s.id);
if (s.outcome === 'void') await wallet.refund(s.operatorMoney.voidCredit, s.id);
cursor = s.cursor;
await store.writeSettlementCursor(cursor); // only once it is applied
}s.id is stable, so keying your credit on it makes the consumer safe to run twice. Resume from the stored cursor, not from a time: settledFrom is a report filter, and a settlement that commits late can carry a settledAt earlier than your last run.
Typed errors, and the one that is not a failure
Every refusal is a class, so the compiler knows the branch that decides whether money is released.
| Class | When | What to do |
|---|---|---|
ReconciliationRequiredError | 409 reconciliation_required | Hold the authorization. Not a rejection. |
TimeoutError | Your deadline elapsed | Hold. The order may have been accepted after you stopped listening. |
ConflictError | Any other 409, such as quote_expired / price_stale / price_moved / price_unverified | On those four, re-quote and let the player confirm the new number. Any other code is not a price change: read err.code before acting. |
QuoteAlreadyUsedError | 409 quote_already_used, a subclass of ConflictError, carrying orderId | The quote was spent by a different order. Read orderId with getOrder, then quote afresh for whatever is still unfilled. Your own clientOrderId finds nothing. |
SandboxOnlyError | 403 sandbox_only | A sandbox-only route. Live integrations use the instructions on quotes, orders and settlements. |
InsufficientScopeError | 403, carries required | Provision a key with that scope. Retrying never helps. |
RateLimitError | 429, carries retryAfterSeconds | Wait the time the server gives. |
AuthenticationError | 401 | The key is absent, unrecognised or revoked. |
NotFoundError | 404 | Also covers “not yours”; the two look the same. |
InvalidRequestError | 400 / 422 | Fix the payload or the stake. |
MoneyIntegrityError | An amount did not decompose | Do not book it. Keep the response and its parity-request-id, and contact Parity support. |
Swipe the table sideways for more columns.
import {
ConflictError,
OrderInProgressError,
QuoteAlreadyUsedError,
ReconciliationRequiredError,
TimeoutError,
} from './parity-sdk'; // the client Parity provides
// The 409s that mean the price moved, and only those, re-quote.
const REQUOTE = new Set(['quote_expired', 'price_stale', 'price_moved', 'price_unverified']);
try {
await player.submitOrder({ quoteId, clientOrderId, reserveReference: clientOrderId });
// Book nothing here: apply the money when the order reads settled (below).
} catch (err) {
if (err instanceof ReconciliationRequiredError || err instanceof TimeoutError) {
// Unknown, not refused: releasing here can strand a live position with no cash.
await wallet.hold(clientOrderId);
return;
}
// Still being placed: resend the same quoteId and clientOrderId later.
if (err instanceof OrderInProgressError) return resendLater(err);
// The quote was spent by another order: read that order first.
if (err instanceof QuoteAlreadyUsedError) return inspect(err.orderId);
if (err instanceof ConflictError && REQUOTE.has(err.code)) return requote();
throw err; // any other code: keep the hold, log err.code, and investigate
}Resolving an unknown
findOrderByClientOrderId reads GET /api/v1/orders, which returns settlementState and transmissionState on every order, computed by the same serializer as GET /api/v1/orders/{id}, and the clientOrderId lookup also carries the order's intent. One call tells you whether to act.
// 1. Find it with the id YOU chose. Ours only ever existed in a response you
// may not have received; yours was chosen before the request was sent.
const order = await player.findOrderByClientOrderId(clientOrderId);
if (!order) return schedulePoll(); // not visible yet: keep holding
// 2. The row carries settlementState, from the same serializer as getOrder.
if (order.settlementState === 'settled') {
await wallet.settle(order.operatorMoney ?? order.operatorExitMoney);
}
// 'pending', which includes status 'submitted', means keep holding.Retries, timeouts and pagination
- Reads retry; writes do not.
clientOrderIdmakes a retry safe, but whether to retry an order depends on your ledger (you may already have released the hold), so the SDK leaves it to you. - A 429 is retried after the server's reset window, not an invented backoff.
- Every cursored feed has an
iterate*async generator, though not always on the same object.listEvents/iterateEvents,listSettlements/iterateSettlementsandreadFeed/iterateFeedpair up on the client.listOrders/iterateOrdersandlistPositions/iteratePositionspair up onforUser(id): the client-levellistOrdersandlistPositionshave no iterator, andforUser(id).listSettlementshas none either. hasMore: falseis the end, even on the first page. On/settlementsand/reconciliation/feedthe cursor stays set at the tail, so never loop onnextCursorthere, and a short page does not mean nothing more, so never loop onitems.lengtheither.- The iterators stop on
hasMore, start from thecursoryou pass, and throw if a cursor comes back twice with more to come, which a caching proxy can cause, so they cannot loop forever.
The public surface
| Call | Endpoint |
|---|---|
listEvents / iterateEvents | GET /api/v1/events |
getEvent | GET /api/v1/events/{id} |
listCategories | GET /api/v1/categories |
imageUrl | GET /api/v1/images/{id} |
forUser().quoteBuy / quoteSell | POST /api/v1/quotes |
forUser().submitOrder | POST /api/v1/orders |
forUser().confirmReserve | POST /api/v1/orders/{id}/confirm-reserve |
forUser().cancelOrder | POST /api/v1/orders/{id}/cancel |
forUser().getOrder | GET /api/v1/orders/{id} |
listOrders / findOrderByClientOrderId | GET /api/v1/orders |
listPositions / iteratePositions | GET /api/v1/positions |
forUser().getPosition | GET /api/v1/positions/{id} |
listSettlements / iterateSettlements | GET /api/v1/settlements |
reconciliationReport | GET /api/v1/reconciliation |
readFeed / iterateFeed | GET /api/v1/reconciliation/feed |
sandbox.balance / sandbox.movements | GET /api/v1/users/{id}/… |
sandbox.supportedAssets / createDepositAddress / deposit | /api/v1/funding/… |
Swipe the table sideways for more columns.
Why the sandbox calls are namespaced
Those endpoints answer 403 sandbox_only in live mode, so the parity.sandbox.* prefix makes a live integration that uses them stand out in review.
Every settlement record addresses the contract by the opaque contractId (ctr_…) and carries no source identifier, on the wire as well as in the SDK.
Including the deprecated feed
GET /api/v1/settlements/positions carries no venue field either. The SDK does not expose it; use listSettlements, which is keyset-paged and gap-free.
The machine-readable contract
An OpenAPI 3.1 document covering the whole /api/v1 surface is at /openapi.json. CI checks it against the app router, including every endpoint and scope.
Parity also provides a black-box conformance runner on request. You run it with --base <url> --key <apiKey>, and it walks the whole lifecycle over HTTP with only a key, including the path on this page: an order recorded with record_intent, its reserve confirmed, its fill, and its settlement read from a cursor. Run it against your sandbox key before you start building.
Do not run the full suite against a live key
It is a sandbox tool. It places a real order at step 4, and from step 15 it uses the sandbox controls, which answer 403 sandbox_only for a live tenant, so against a live key it fails after having traded.
--read-only is safe for a live account: it covers the catalogue, reads and refusals without writing anything.
Next: the quickstart runs this flow against a sandbox key in about ten minutes.