Repository Public
1# SP Trading API — TypeScript SDK (`@sp-wallet/trading-sdk`)23Official client of the SP Trading API (`/api/v1/trading`, contract: [`docs/openapi/trading-v1.json`](../openapi/trading-v1.json),4reference: [`docs/TRADING-API-OPENAPI.md`](../TRADING-API-OPENAPI.md)). Source: `packages/trading-sdk/`.56- Zero runtime dependency: global `fetch` and WebCrypto. Node ≥ 20 and browsers. ESM + type declarations.7- Every answer is typed; the types are **generated** from the OpenAPI document (`scripts/gen-types.mts`), and a test fails8 when the committed types are not what the document gives.9- Money, prices and sizes are decimal **strings** end to end. The SDK never converts them to a `number`.10- The API key is never logged, never part of an error, never shown by `console.log(client)`.1112> **Execution requires an owner-approved mandate.** Placing an order and closing or reducing a position need — besides13> the scope — an API key **bound to a trading mandate approved by the wallet's owner**. Without one the API refuses the14> call (`403 mandate_required` → `MandateRequired`); an order outside the mandate is `MandateDenied`. A scope alone never15> lets a key execute. Managing agents and strategies needs **no** mandate on the key (research and paper sign nothing):16> an agent goes live only under its *own* mandate, approved by the owner.17>18> **State of the API in this version.** All 46 operations of the contract are implemented and answer typed results.19> **Paper** orders are simulated by the wallet's paper engine against the venue's real order book. **Live** orders20> additionally need `SPW_TRADING_API_EXECUTION=on` on the server (default off → `403 execution_disabled` →21> `ExecutionDisabled`) and the wallet's mainnet locks. Spot orders and live GMX orders are the owner's (passkey): a key is22> refused them.2324## Install (from the repository)2526The package is not published to npm. Build it, then install it from its path:2728```bash29node packages/trading-sdk/scripts/build.mts # → packages/trading-sdk/dist (index.js + *.d.ts)30npm install /path/to/sp-wallet/packages/trading-sdk # in your project31```3233Inside this monorepo, import the sources directly: `import { SPWallet } from '@sp-wallet/trading-sdk/src'`34(or a relative path, as the examples do).3536## Quick start3738```ts39import { SPWallet } from '@sp-wallet/trading-sdk';4041const client = new SPWallet({ apiKey: process.env.SP_WALLET_API_KEY }); // or just `new SPWallet()`4243const balances = await client.getBalances();44const positions = await client.getPositions();45const preview = await client.previewOrder({ exchange: 'hyperliquid', symbol: 'BTC', side: 'buy', type: 'market', notionalUsdc: 100 });46if (preview.wouldExecute) {47 const placed = await client.createOrder({ exchange: 'hyperliquid', symbol: 'BTC', side: 'buy', type: 'market', notionalUsdc: 100 }); // mode: 'paper' by default48 const { order } = await client.waitForOrder(placed.order.id); // FILLED, CANCELLED, REJECTED or FAILED49}50```5152| Option | Default | |53|---|---|---|54| `apiKey` | env `SP_WALLET_API_KEY` | `spw_live_…`, created by the owner in the Developer screen |55| `baseUrl` | env `SP_WALLET_BASE_URL`, else `https://wallet.spboucher.ai` | `http://` is accepted for `localhost` only (or with `allowInsecureHttp`) |56| `timeoutMs` | `30000` | per attempt |57| `maxRetries` | `2` | retries after the first attempt |58| `userAgent` | — | appended to `sp-wallet-typescript/<version>` |59| `sendTimestamp` | `false` | send `X-SPW-Timestamp` with mutating calls (the server refuses a call more than 300 s from its clock) |60| `maxRetryDelayMs` | `30000` | longest wait accepted before a retry; a 429 asking for more is thrown at once |61| `fetch` | `globalThis.fetch` | |6263Each method takes a last argument `{ timeoutMs, maxRetries, signal }` (and `idempotencyKey` for the mutating ones).6465## Methods6667| Method | Operation | Scope |68|---|---|---|69| `listMarkets({ venue, kind, q, limit })` | `GET /markets` | `markets:read` |70| `compareMarkets({ underlying, side, notional, leverage, horizonHours, liquidity, minNetEdgeBps })` | `GET /markets/compare` | `markets:read` |71| `getMarket(symbol)` | `GET /markets/{symbol}` | `markets:read` |72| `getOrderbook(symbol, { depth })` | `GET /markets/{symbol}/orderbook` | `markets:read` |73| `getCandles(symbol, { interval, limit })` | `GET /markets/{symbol}/candles` | `markets:read` |74| `listPrivateMarkets({ delisted, size, side })` | `GET /private-markets` | `markets:read` |75| `getPrivateMarket(id, { size, side, interval, limit })` | `GET /private-markets/{id}` | `markets:read` |76| `getPrivateMarketCompany(slug, { … })` | `GET /private-markets/companies/{slug}` | `markets:read` |77| `getPortfolio()` | `GET /portfolio` | `wallet:read` |78| `getBalances({ network })` | `GET /balances` | `wallet:read` |79| `getActivity({ limit, cursor })`, `iterateActivity({ limit }, { maxItems })` | `GET /activity` | `wallet:read` |80| `listNfts({ network, collection, status, q, sort, spam, limit, cursor })`, `iterateNfts({ … }, { maxItems })` | `GET /nfts` | `wallet:read` |81| `getNft(key)` | `GET /nfts/item` | `wallet:read` |82| `getNftActivity({ key, limit, cursor, type })` | `GET /nfts/activity` | `wallet:read` |83| `getNftMarket({ network, address, tokenId })` | `GET /nfts/market` | `markets:read` |84| `getNftMarketEvents({ network, address, tokenId, provider, type, after, before, cursor, limit })` | `GET /nfts/market/events` | `markets:read` |85| `getPositions({ mode, venue })` | `GET /positions` | `positions:read` |86| `getRisk()` | `GET /risk` | `positions:read` |87| `engageKillSwitch(reason)` | `POST /risk/kill-switch` | `positions:manage` (no mandate) |88| `listOrders({ mode, venue, open, limit, cursor })`, `iterateOrders({ … }, { maxItems })` | `GET /orders` | `orders:read` |89| `getOrder(id)` | `GET /orders/{id}` | `orders:read` |90| `waitForOrder(id, { waitTimeoutMs, pollIntervalMs, until })` | polls `GET /orders/{id}` | `orders:read` |91| `previewOrder(order)` → `OrderPreview` | `POST /orders/preview` | `orders:prepare` (a key needs a mandate bound to it) |92| `createOrder(order)` → `PlacedOrder` | `POST /orders` | `orders:execute` + mandate |93| `cancelOrder(id)` → `CancelledOrder` | `DELETE /orders/{id}` | `orders:cancel` (its own orders; no mandate) |94| `closePosition(id, { slippageBps })` → `PlacedOrder` | `POST /positions/{id}/close` | `positions:manage` + mandate |95| `reducePosition(id, { fraction, slippageBps })` → `PlacedOrder` | `POST /positions/{id}/reduce` | `positions:manage` + mandate |96| `runCommand(text, { mode, accountId, dryRun })` → `CommandResult` | `POST /commands` | the scope of what the command resolves to |97| `listStrategies({ kind })` | `GET /strategies` | `strategies:read` |98| `createStrategy({ kind, path, agentId })` → strategy · `backtestStrategy(id)` → job · `startStrategy(id, { mode })`, `stopStrategy(id)` → agent | `POST /strategies…` | `strategies:manage` |99| `listAgents()` | `GET /agents` | `agents:read` |100| `listAgentTemplates()`, `getAgent(id)` | `GET /agents/templates`, `/agents/{id}` | `agents:read` |101| `listAgentSignals(id, { mode, limit, before })`, `listAgentJournal(id, { mode, … })`, `listAgentOrders(id, { mode, open, … })`, `getAgentPerformance(id, { mode })` | `GET /agents/{id}/signals`, `journal`, `orders`, `performance` — **one mode per call** | `agents:read` |102| `getJob(id)`, `waitForJob(id, { waitTimeoutMs, pollIntervalMs })` | `GET /jobs/{id}` | `agents:read` |103| `createAgent({ template, name, … })`, `startAgent(id, { mode })`, `pauseAgent(id)`, `stopAgent(id)` → agent · `backtestAgent(id, { hours })` → job | `POST /agents…` | `agents:manage` |104| `openapi()` | `GET /openapi.json` | any valid key |105106`responseMeta(result)` gives the facts of the HTTP exchange behind any result: `status`, `requestId`, `idempotencyKey`,107`idempotentReplay`, `rateLimit { limit, remaining, resetSeconds }`, `attempts`.108109The private markets are display only: none of these contracts is tradable (`tradable: false` on every row).110111### Pagination112113`GET /orders` and `GET /activity` are paginated by cursor: a page carries `nextCursor`, which is the `cursor` of the114next (older) page; `null` at the end. The order is stable (time, then id): no row is repeated or skipped across pages.115The iterators follow the cursor for you; `limit` is the page size.116117```ts118for await (const order of client.iterateOrders({ open: true, limit: 100 })) console.log(order.id, order.status);119for await (const item of client.iterateActivity({}, { maxItems: 500 })) console.log(item.kind, item.at);120121const page = await client.listOrders({ limit: 50 }); // one page by hand122const next = page.nextCursor ? await client.listOrders({ limit: 50, cursor: page.nextCursor }) : null;123```124125`listMarkets` is not paginated: it answers `total` and `truncated` so a list cut by `limit` is visible.126127### Orders128129```ts130const order = { mode: 'paper', instrument: 'hyperliquid:BTC', side: 'buy', type: 'limit', price: '60000', size: '0.01' } as const;131const preview = await client.previewOrder(order); // nothing is created; preview.refusals says what would refuse it132const placed = await client.createOrder(order); // placed.order.status: 'SUBMITTED' while it rests133await client.cancelOrder(placed.order.id); // → { order: { status: 'CANCELLED', … }, changed: true }134```135136- `instrument` is `venue:symbol` as returned by `listMarkets`; `exchange` + `symbol` is the same thing in two parts.137- `mode` (`'paper'` | `'live'`) is required by the API; the SDK sends `'paper'` when you give none.138- Size the order with exactly one of `size` (base units) and `notional` (quote currency). Both are decimal strings; a139 JavaScript float is refused before any request (`ConfigurationError`).140- **`notional` is sized by the server**: it divides by the order's own price (limit, else trigger), else by the mark141 price it reads at that moment, and rounds **down** to the lot size. A stale mark is refused (`503 stale_data`); less142 than one lot is `422 below_min_size`. The answer carries the size that was used (`preview.resolved.size`,143 `placed.order.size`). `notionalUsdc` is the same field under the name of the quick start: the SDK sends it as144 `notional` and computes nothing.145- `getMarket(instrument).instrument` gives what an order must respect: `lotSize`, `tickSize`, `minOrderSize`,146 `minNotional`, `maxLeverage`.147- A preview says "no" in its answer, not with an exception: `wouldExecute` is false and `refusals` lists each refusal148 with its `stage` (`key`, `lock`, `mandate`, `risk`, `engine`) and `code`. `preview.account.equity` and149 `freeCollateral` are answered only to a key that also holds `wallet:read` or `positions:read`150 (`preview.account.withheld` is true otherwise). A key previews the order it could place: without a mandate bound to151 it, `previewOrder` throws `MandateRequired`.152- `previewOrder` and `engageKillSwitch` take no `Idempotency-Key` (the contract declares none): they are safe to repeat153 and are retried like a read.154155A position is closed or reduced by its `id` from `getPositions()`; both are strictly reduce-only market orders:156157```ts158const position = (await client.getPositions({ mode: 'paper' })).positions[0];159if (position) {160 await client.reducePosition(position.id, { fraction: '0.5' });161 await client.closePosition(position.id);162}163```164165### Commands and the kill switch166167```ts168import { AmbiguousCommand } from '@sp-wallet/trading-sdk';169170try {171 const r = await client.runCommand('LONG BTC-PERP 500 x2', { dryRun: true });172 // the answer is a discriminated union: narrow on `kind`, and for an order on `executed`173 if (r.kind === 'order' && !r.executed) console.log(r.order.instrument, r.order.notional, r.hash); // dry run: the CANONICAL order174 if (r.kind === 'order' && r.executed) console.log(r.order.id, r.order.status, r.canonical.instrument); // executed: the placed order175 if (r.kind === 'query') console.log(r.query, r.data); // SHOW …176 if (r.kind === 'control') console.log(r.control.type, r.executed); // CANCEL, KILL, STOP ALL AGENTS177} catch (e) {178 if (e instanceof AmbiguousCommand) console.log(e.questions.map((q) => `${q.field}: ${q.options.join(' | ')}`)); // nothing was executed179 else throw e;180}181182await client.engageKillSwitch('manual stop'); // blocks every NEW risk; cancels and exits still pass; only the owner releases it183```184185The grammar is deterministic (no model). What a command leaves open (venue, leverage, …) comes from the owner's stored186defaults and from nothing else; when they do not settle it, the API answers `409 ambiguous_command` with the questions.187188### Agents189190```ts191const { templates } = await client.listAgentTemplates(); // family, engine, the modes each can run in192const { agent } = await client.createAgent({ template: 'market-making', name: 'MM BTC', venues: ['hyperliquid'], universe: ['BTC'] });193await client.startAgent(agent.id, { mode: 'paper' }); // research and paper sign nothing194195// every per-agent read is ONE mode per call: `mode` is required, and an answer never mixes two (`all` is refused)196const signals = await client.listAgentSignals(agent.id, { mode: 'paper', limit: 50 });197const journal = await client.listAgentJournal(agent.id, { mode: 'paper' });198const orders = await client.listAgentOrders(agent.id, { mode: 'paper', open: true });199const performance = await client.getAgentPerformance(agent.id, { mode: 'paper' }); // computed from paper records only; never a backtest200201const { job } = await client.backtestAgent(agent.id, { hours: 24 }); // asynchronous202const done = await client.waitForJob(job.id, { waitTimeoutMs: 120_000 }); // done | failed | cancelled; WaitTimeout is not a failure203await client.pauseAgent(agent.id); await client.stopAgent(agent.id); // stop is always allowed204```205206- **`mode` on the reads.** On the wire `mode` is optional: the server answers the mode the agent is in now (for a stopped207 agent, the one it last ran in) and says which in `mode`. The SDK makes it a **required** argument, so that code never reads208 paper figures believing they are live ones; `open` exists on `listAgentOrders` only.209- **`createAgent({ mode })`** is `'research'` (default: created, not running) or `'paper'`: an agent from a stream or210 supervisor template starts on paper at once; a bar agent (or `kind: 'perp'`) is created and not started — register and211 backtest a strategy version, then `startAgent`. `'live'` is refused (`400 bad_request`).212- **Paper.** Starting a perp agent on paper creates its *paper trading mandate* (nothing is signed): its orders go through213 the same order service, risk engine and kill switch as every other order. The key needs `agents:manage`, and a key214 restricted to other venues or instruments gets `403 restricted`; a halted paper account answers `409 halted`.215- **Live.** `startAgent(id, { mode: 'live' })` succeeds only when a mandate the **owner** approved for that agent with the216 passkey is in force — for a perp agent a trading mandate, which only the owner activates. Otherwise `409 mandate_required`.217 A key can never approve one. Families that cannot go live answer `409 live_unavailable`.218- **Errors.** Every 409 of the agent operations is a `Conflict`; read `e.code` (`mandate_required`, `halted`, `bad_state`,219 `live_unavailable`, `no_strategy`, `no_report`, `bad_report`). `MandateRequired` (403) is about the *key's* mandate on the220 order operations, not about an agent's.221- **One kill switch.** There is no agents-side switch: `engageKillSwitch(reason)` engages the risk engine's, which stops every agent's222 new risk too. Releasing it is the owner's act, in the app. A spot agent is created in the owner's app (`403 owner_required`).223224### Spot orders (owner session only)225226A key is refused spot execution (`403`). For the owner, a spot order is a swap proposal approved with the passkey:227a SELL names `size` (the quantity sold), a BUY names `notional` — the amount of the quote asset to spend, because a swap228is exact-input: `{ instrument: 'spot:ETH-USDC', side: 'buy', type: 'market', notional: '100', mode: 'live' }`.229230### Order states and `waitForOrder`231232`order.status` is one of the twelve `ORDER_STATES` — a closed enum in the contract: `CREATED, VALIDATED,233AWAITING_APPROVAL, APPROVED, SUBMITTING, SUBMITTED, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED, FAILED, UNKNOWN`.234Final states (`FINAL_ORDER_STATES`): `FILLED, CANCELLED, REJECTED, FAILED`; `order.final` is true exactly for those.235**`UNKNOWN` is not final and is not a failure**: the venue's answer is not known yet; keep reading the order.236`order.engineStatus` is the executing engine's own word for the same moment (`open`, `filled`, a swap state…): it is237informative — decide on `status`.238239```ts240const { order, fills } = await client.waitForOrder(id, { waitTimeoutMs: 60_000, pollIntervalMs: 1_000 });241```242243`waitForOrder` returns when the status is final (or when `until(order)` is true) and throws `WaitTimeout` when the time244elapses first — that is not an order failure either; `error.last` is the last answer.245246## Errors247248Every error extends `SPWalletError` and carries `code` (the API's `error` member), `message`, `status`, `requestId`249(`X-Request-Id`: the owner finds the call in the usage log with it) and, for mutating calls, `idempotencyKey`.250251| Class | When |252|---|---|253| `ValidationError` | 400 `bad_request`, `invalid_order`, `invalid_cursor`, `parse_error`, `idempotency`, `stale_request`; 422 `no_orderbook`, `venue_rejected`, `below_min_size`, `no_position`, a refusal of the venue engine's own rules |254| `AuthenticationError` | 401 `unauthenticated` — missing, malformed, unknown, expired or revoked key (one answer for all) |255| `PermissionDenied` | 403 — `restricted`, `ip_not_allowed`, `key_limit_exceeded`, `not_your_order`… |256| ↳ `ScopeDenied` | 403 `insufficient_scope` — the key does not hold the operation's scope |257| ↳ `MandateRequired` | 403 `mandate_required` — no trading mandate is bound to the key |258| ↳ `MandateDenied` | 403 `mandate_denied` — the order is outside the mandate; `error.reasons` (`MANDATE_DENY_REASONS`: `ORDER_NOTIONAL_EXCEEDED`, `INSTRUMENT_NOT_ALLOWED`…) |259| ↳ `ExecutionDisabled` | 403 `execution_disabled` — live execution through the API is closed on this server; nothing was created |260| `RiskDenied` | 422 `risk_denied`, 423 `kill_switch_active` / `read_only_mode` — `error.failed` (ids of `RISK_CHECK_IDS`), `error.checks`, `error.killSwitch` |261| `NotFound` | 404 `unknown_order`, `unknown_instrument`, `unknown_venue`, `unknown_market`, `unknown_position`, `not_found` (a path that is not an operation)… |262| `Conflict` | 409 |263| ↳ `IdempotencyConflict` | 409 `idempotency_conflict` — the key was used with a different request |264| ↳ `AmbiguousSymbol` | 409 `ambiguous_symbol` — `error.candidates` lists the `venue:symbol` ids |265| ↳ `AmbiguousCommand` | 409 `ambiguous_command` — `error.questions`; nothing was executed |266| `RateLimited` | 429 `rate_limited`, `auth_throttled` — `error.retryAfterSeconds` |267| `NotImplementedError` ↳ `ExecutionNotWired` | 501 `execution_not_wired` — an operation this server has not connected (an owner's spot order without the swap flow); nothing was done |268| `ServerError` ↳ `ServiceUnavailable` | 5xx; 503 `signer_unreachable`, `venue_unavailable`, `markets_unavailable`, `stale_data`… |269| `NetworkError` ↳ `TimeoutError` | no answer (reads, previews) |270| `OutcomeUnknown` | a mutating call without a trustworthy answer — **not a failure**, see below |271| `WaitTimeout`, `WebhookVerificationError`, `ConfigurationError` | SDK-side |272273**`error.order`**: when the server created the order before it refused it (a mandate or risk refusal, a refusal of the274venue engine), the error carries that order — state `REJECTED` or `FAILED` — so you know its id. It is `null` when the275call was refused before any order existed (nothing was created). The codes each operation can answer are in the276contract (`x-spw-errors`) and in the SDK as `OPERATION_ERRORS[operationId]`.277278```ts279import { ExecutionDisabled, MandateDenied, MandateRequired, OutcomeUnknown, RateLimited, RiskDenied, ScopeDenied } from '@sp-wallet/trading-sdk';280281try {282 await client.createOrder({ instrument: 'hyperliquid:BTC', side: 'buy', type: 'market', notional: '100', mode: 'paper' });283} catch (e) {284 if (e instanceof OutcomeUnknown) { /* see "OutcomeUnknown" */ }285 else if (e instanceof MandateRequired) { /* the owner must bind an approved mandate to this key */ }286 else if (e instanceof MandateDenied) console.log(e.reasons, e.order?.id, e.order?.status); // ['ORDER_NOTIONAL_EXCEEDED'] … 'REJECTED'287 else if (e instanceof RiskDenied) console.log(e.killSwitch ? 'kill switch' : e.failed, e.checks.map((c) => `${c.id}: ${c.observed} / ${c.limit}`));288 else if (e instanceof ExecutionDisabled) { /* live orders are closed on this server; paper is not affected */ }289 else if (e instanceof ScopeDenied) { /* the key lacks orders:execute */ }290 else if (e instanceof RateLimited) { /* wait e.retryAfterSeconds */ }291 else throw e;292}293```294295## Retries and idempotency296297- **Reads (`GET`)** are retried on a network error, a timeout, `429` (after `Retry-After`, else `RateLimit-Reset`) and298 `502 / 503 / 504`, with exponential backoff (0.5 s × 2ⁿ, capped at 8 s) and jitter (50–100 % of the step).299- **Mutating calls (`POST`, `DELETE`)** are retried **only because they carry an `Idempotency-Key`**. The SDK creates one300 UUIDv4 per logical call when you give none, serializes the body **once** in canonical form (sorted keys — the same301 rule as the server's request hash), and sends the **same key and the same bytes** on every retry. The server then302 runs the operation at most once: the same key with the same request returns the first answer303 (`responseMeta(r).idempotentReplay`), with a different request `409 idempotency_conflict`.304- The key is exposed three ways so that you can resume after a crash: pass your own (`{ idempotencyKey }`, generate it305 with `newIdempotencyKey()` and **persist it before sending**), read it from `responseMeta(result).idempotencyKey`, or306 from `error.idempotencyKey`.307- `previewOrder` and `engageKillSwitch` are `POST`s without an `Idempotency-Key` in the contract (repeating them changes308 nothing): they are retried like a read and fail with the ordinary errors, never `OutcomeUnknown`.309- Not retried: 400, 401, 403, 404, 409 (except `idempotency_in_progress`), 422, 423, 500, 501.310311### `OutcomeUnknown`312313A mutating call that ends without a trustworthy answer — timeout, connection lost, `500/502/504`, a `503` that does not314come from the API, the first request with this key still running, or an answer decided before the server looked at the315key (401, 403, 429) after an attempt without an answer — throws `OutcomeUnknown`. **It is not a failure**: the operation316may or may not have been executed.317318```ts319try {320 await client.createOrder(order, { idempotencyKey });321} catch (e) {322 if (!(e instanceof OutcomeUnknown)) throw e;323 // 1. re-send the SAME call with the SAME key: the server returns the stored answer if it ran, or runs it once324 const result = await client.createOrder(order, { idempotencyKey: e.idempotencyKey! });325 // 2. or read the object: client.getOrder(id) / client.listOrders({ open: true })326 // Never re-send with a NEW key: that could execute the operation twice.327}328```329330## Key rotation and the trading mandate331332A trading mandate names **one principal — the key id it was approved for** — and a rotation gives the key a new id. The333rotation therefore does **not** carry the mandate: the new key keeps the scopes, limits, restrictions and expiry, and is334**unbound**. Until the owner approves a mandate for the new id and binds it, `createOrder`, `closePosition` and335`reducePosition` throw `MandateRequired` (and `previewOrder` too); reads, cancels of its own orders, the kill switch and336agent management keep working. The answer of the rotation says so:337`{ key: { mandateId: null, inertScopes: […] }, secret, revoked, mandate: { carried: false, mandateId: '<old mandate>', code: 'mandate_principal_mismatch', note } }`.338339```ts340try { await client.createOrder(order); }341catch (e) {342 if (e instanceof MandateRequired) { /* after a rotation: ask the owner for a mandate for THIS key id, then retry — nothing was created */ }343 else throw e;344}345```346347The owner's side of it (owner session and passkey — nothing a key can do):348349```bash350# 1. a mandate for the NEW key id: created, then approved (a live mandate is approved with the passkey at the signer)351POST /api/v1/mandates { "principal": { "kind": "api_key", "id": "<new key id>" }, "mode": "paper", "accountIds": ["…"], … }352POST /api/v1/mandates/<mandate id>/approve { } # live: /approve/prepare first, then the passkey assertion353# 2. bind it to the key (binding gives the key authority: passkey)354POST /api/v1/developer/keys/<new key id>/update/prepare { "changes": { "mandateId": "<mandate id>" } }355POST /api/v1/developer/keys/<new key id>/update { "intentId": "…", "assertion": { … } }356```357358In the app: Developer → the key → *Trading mandate* → *New mandate*.359360## Streaming361362Live market data over one websocket: quotes, order books, trades, candles and venue statuses. Read-only (scope363`markets:read`), same key, same restrictions (a channel of a venue or instrument outside the key's restrictions is refused,364per subscription). `SPWalletStream` is exported by the package next to `SPWallet`; it needs a global `WebSocket` (Node >= 22,365browsers) or the `WebSocket` option (the `ws` package).366367```ts368import { SPWalletStream, OrderBook, StreamError } from '@sp-wallet/trading-sdk';369370const stream = new SPWalletStream({ baseUrl: 'https://wallet.example' }); // the key: SP_WALLET_API_KEY, in the Authorization header371stream.on('close', (c) => console.log(`closed (${c.code}); ${c.willReconnect ? 'reconnecting' : 'stopped'}`));372stream.on('error', (e) => console.log(`stream error: ${e.code}`));373374await stream.subscribe([{ type: 'quote', id: 'hyperliquid:BTC' }, { type: 'status', id: 'hyperliquid' }]);375for await (const m of stream) { // or stream.on('quote', …)376 if (m.type === 'quote') console.log(m.id, m.bid, m.ask, m.mark, m.stale); // decimal strings; `stale` is the server's verdict377}378```379380- **Channels**: `quote`, `book` (`depth`), `trades`, `candles` (`interval`), `status` (`id: '<venue>'` or `'*'`). Ids are381 `<venue>:<instrument>` (`hyperliquid:BTC`, `dydx:BTC-USD`, `spot:BTC`).382- **Reconnection** is on by default (`reconnect: false` to turn it off): exponential backoff with jitter between383 `backoffMinMs` (500) and `backoffMaxMs` (30 000); after a reconnection the client subscribes again to everything and the384 server sends fresh snapshots — a handler never has to do it. `close` events carry `willReconnect`. A refusal that a retry385 cannot fix (no `markets:read`, revoked key, unknown instrument) is a `StreamError` with the server's `code`, and is not retried.386- **Order books**: feed every `book` message to an `OrderBook`; `apply()` returns `false` on a sequence hole or a checksum387 mismatch — call `stream.resync(channel)` and the server restarts the book from a snapshot.388- **Slow consumers**: quotes are conflated and a `dropped` message says what was skipped; the iterator's own buffer is389 bounded by `bufferSize`.390- A stream connection writes **no row in the key's usage log** (the ticket request does).391392### Browsers: the ticket flow393394A browser cannot set a header on a websocket, and the key must never reach it. Your backend asks for a single-use ticket395(30 s) with the key; the browser connects with the ticket only:396397```ts398// backend (holds the key) — a route of YOUR server, behind YOUR authentication399app.post('/stream-ticket', async () => {400 const r = await fetch(`${WALLET}/api/v1/trading/stream/ticket`, { method: 'POST', headers: { authorization: `Bearer ${process.env.SP_WALLET_API_KEY}`, 'content-type': 'application/json' }, body: '{}' });401 if (!r.ok) throw new Error(`ticket refused: ${r.status}`);402 return { ticket: (await r.json()).ticket }; // { ticket, expiresAt, ttlMs, url, protocol }403});404405// browser — no key anywhere; a new ticket is asked at every (re)connection406const stream = new SPWalletStream({407 baseUrl: 'https://wallet.example',408 ticket: async () => (await (await fetch('/stream-ticket', { method: 'POST' })).json()).ticket,409});410await stream.subscribe({ type: 'quote', id: 'hyperliquid:BTC' });411```412413The ticket carries the key's scope and restrictions, works once, and is refused when mixed with another credential. In Node,414`auth: 'ticket'` makes the client ask for the ticket itself with its key (useful behind a proxy that strips headers on upgrade).415416## Webhooks417418The wallet signs every delivery: `X-SPW-Timestamp: <unix seconds>` and419`X-SPW-Signature: v1=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>`. Verify over the **raw** body, before parsing:420421```ts422import { constructWebhookEvent } from '@sp-wallet/trading-sdk';423424const event = await constructWebhookEvent({425 secret: process.env.SP_WALLET_WEBHOOK_SECRET!,426 timestamp: req.headers['x-spw-timestamp'], signature: req.headers['x-spw-signature'],427 body: rawBody, // string or Uint8Array, exactly as received428}); // throws WebhookVerificationError; tolerance 300 s; constant-time comparison429```430431`verifyWebhook(…)` returns a boolean instead. Delivery is at-least-once: deduplicate on `event.id`. Events:432`key.revoked`, `risk.kill_switch`, `agent.updated`, `order.updated` (one event per transition of an order),433`risk.proposal`. A complete receiver: `packages/trading-sdk/examples/webhook-receiver.ts`.434435## Examples436437```bash438SP_WALLET_API_KEY=spw_live_… node packages/trading-sdk/examples/read-only.ts # read-only tour439SP_WALLET_API_KEY=spw_live_… node packages/trading-sdk/examples/preview-order.ts # a preview with every outcome handled440SP_WALLET_API_KEY=spw_live_… node packages/trading-sdk/examples/paper-order.ts # PAPER: preview → place → wait → position → close441SP_WALLET_API_KEY=spw_live_… node packages/trading-sdk/examples/stream-quotes.ts # live quotes over the websocket, with reconnection442```443444The four are executed against the real API by the integration tests.445446## Development447448```bash449node packages/trading-sdk/scripts/gen-types.mts [--check] # src/generated/openapi.ts from the OpenAPI document450node_modules/.bin/vitest run packages/trading-sdk # unit tests + integration test451SPW_SDK_INTEGRATION=off node_modules/.bin/vitest run packages/trading-sdk # unit tests only452```453454The integration test starts the real API and the real signer on an own database (`scripts/test-stack.mts`), creates455keys, a paper account and paper mandates through the owner flow, calls every method and runs the whole **paper** write456path (preview → order → fill → reduce → close → resting order → cancel, replay and conflict, the refusals, the kill457switch, commands) and an agent on paper (create from a template → start → signals, journal, orders, performance → pause → backtest job → stop). No live order is sent: the live case stops at `execution_disabled`. It is **skipped** (reported as458skipped) when PostgreSQL is not reachable; a test whose venue cannot be read is skipped with that reason.459460## NFT reads461462Five read operations; **no NFT write exists in the API** (transfers are the owner's, with the passkey; no marketplace action is built). `listNfts` / `getNft` / `getNftActivity` read the wallet's own inventory. `getNftMarket` and `getNftMarketEvents` read market data of ANY item named by its chain identifiers and answer **one row per source** — a source without its key answers `status.state: 'needs_key'` with `status.unlockedBy`; nothing is filled in. Amounts are exact base-unit strings in a currency identified by network + mint / contract (`price.amount`, `price.currency`); a `tokenId` is a string (it can be as large as 2^256 − 1). NFTs carry no value: `valuation.state` / `value.state` is `'unavailable'`. A fiat `rates` entry can be `withheld` for a key (licence of the price source).463