Skip to main content
This walkthrough builds a minimal but complete perpetuals agent. It authenticates with an API key, reads the market, sizes an order safely with a preview, submits it, listens for fills on the real-time stream, and holds a risk kill switch. Every endpoint used here is public and verified — nothing is invented.
All traffic goes through the single OCX API gateway at one HTTPS base URL, written below as {API_BASE}. Prices and quantities are JSON strings (fixed-decimal) — keep them as strings end to end to preserve precision.

Step 1 — Provision an API key

A human owner signs in once with SIWE, then mints a scoped key for the agent. See Authentication for the SIWE flow; the key step is:
Store secret in a secret manager immediately — it is never shown again. From here on, the agent sends x-api-key: <secret> on every request and never needs the wallet.

Step 2 — Read the market

Market data needs no auth. Discover instruments, then read the book and stats for the market you want to trade.
For anything more than a one-shot decision, subscribe to the live stream in Step 5 instead of polling these endpoints in a loop — it is lower latency and lighter on your rate-limit budget.

Step 3 — Size the order with a preview

Always dry-run before you commit. preview returns the notional, estimated fee, your fee role and rolling-volume tier, and — critically — whether the order would pass the server-side margin gate. It has no side effects.
boolean
Whether the order would pass the margin gate. If false, read reason and resize or fund — do not retry the same order.
string
Collateral the order would lock. Compare against your free balance.
string
Estimated fee for this fill, with feeBps and feeRole (maker/taker).
string
Order notional in quote currency.

Step 4 — Submit the order

With an approved preview, place the order. Set a clientOrderId so a network retry can never create a duplicate.
For multi-order strategies (grids, liquidity ladders), prefer POST /perps/quotes/bulk with cancelAll: true — it atomically replaces your whole ladder in one call and is fully API-key enabled. See the Market maker quoting guide.
Order controls you’ll reach for:
gtc rests until filled or cancelled; ioc fills what it can immediately then cancels the rest; fok fills fully or cancels entirely.
postOnly rejects an order that would take liquidity (keeps you on the maker side). reduceOnly prevents an order from ever increasing your position — use it for exits.
Attach stopPrice, takeProfitPrice, or stopLossPrice for automated conditional exits.

Step 5 — Monitor fills over the stream

Open one Server-Sent Events connection per market. On connect you receive a snapshot (order book, recent trades, and your positions); after that, delta events push incremental order-book changes, new trades, and position upserts as they happen. A fill shows up as a trade plus a position delta — that’s your signal to rebalance.
Streams diff server-side and can drop on network blips. A well-behaved agent applies the initial snapshot, folds in each delta, watches the envelope eventSeq for gaps, and reconnects (re-snapshotting) on disconnect or on a sequence gap.
Between stream events, reconcile with the pull endpoints when you need certainty:

Step 6 — Manage risk and shut down cleanly

Risk is enforced server-side, but your agent still owns its own limits. Track margin headroom, de-risk proactively, and always have a kill path.
Handle INSUFFICIENT_MARGIN rejections by resizing or funding, not by retrying. Back off on 429 and respect the X-RateLimit-* headers. Rotate the API key on your expiresInDays schedule and revoke old keys with DELETE /perps/me/api-keys/{id}.

The full loop

1

Provision

Owner signs in with SIWE, mints an IP-pinned, expiring trade key. Agent loads it from a secret store.
2

Cache & subscribe

Cache the market list and fee tiers; open one SSE stream per market.
3

Decide & size

Compute a signal, then preview to confirm margin, fee, and approval.
4

Execute

Place via /perps/orders (or /perps/quotes/bulk with cancelAll for ladders), always with a clientOrderId.
5

React

Fold in fill and position deltas from the stream; adjust inventory and skew.
6

Guard

Enforce your own margin limits; cancel-all or positions/close on breach, disconnect, or shutdown.

Back to AI agents overview

Revisit the concepts: the agent loop, scopes, and server-side risk.