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:
curl -s -X POST "$API_BASE/perps/me/api-keys" \
  -b cookies.txt \
  -H 'Content-Type: application/json' \
  -d '{"name":"demo-agent","scope":"trade","allowedIps":["203.0.113.7"],"expiresInDays":90}'
# → { "id":"01H…", "secret":"ocx_sk_…", "message":"Copy this secret now — it will not be shown again." }
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.
# List perp/futures markets
curl -s "$API_BASE/perps/markets"

# Order book snapshot
curl -s "$API_BASE/perps/orderbook/BTC-PERP?depth=25"

# 24h stats (mark, funding context, open interest)
curl -s "$API_BASE/perps/market-stats?marketId=BTC-PERP"

# Fee tiers (query live rather than hardcoding)
curl -s "$API_BASE/perps/fees"
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.
curl -s -X POST "$API_BASE/perps/orders/preview" \
  -H "x-api-key: $OCX_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"marketId":"BTC-PERP","side":"buy","type":"limit","price":"64000","quantity":"0.25"}'
approved
boolean
Whether the order would pass the margin gate. If false, read reason and resize or fund — do not retry the same order.
marginRequired
string
Collateral the order would lock. Compare against your free balance.
estFee
string
Estimated fee for this fill, with feeBps and feeRole (maker/taker).
notional
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.
curl -s -X POST "$API_BASE/perps/orders" \
  -H "x-api-key: $OCX_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "marketId":"BTC-PERP","side":"buy","type":"limit",
    "price":"64000","quantity":"0.25","timeInForce":"gtc",
    "postOnly":false,"reduceOnly":false,"marginMode":"cross",
    "clientOrderId":"demo-agent-0001"
  }'
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.
curl -N "$API_BASE/perps/stream/events?marketId=BTC-PERP" \
  -H "x-api-key: $OCX_KEY"
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:
curl -s "$API_BASE/perps/positions"    -H "x-api-key: $OCX_KEY"
curl -s "$API_BASE/perps/orders/open"  -H "x-api-key: $OCX_KEY"
curl -s "$API_BASE/perps/trades"       -H "x-api-key: $OCX_KEY"
curl -s "$API_BASE/perps/balances"     -H "x-api-key: $OCX_KEY"

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.
# Flatten a position
curl -s -X POST "$API_BASE/perps/positions/close" \
  -H "x-api-key: $OCX_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"marketId":"BTC-PERP"}'   # omit quantity to close fully

# Emergency kill switch — pull all orders (optionally scoped)
curl -s -X POST "$API_BASE/perps/orders/cancel-all" \
  -H "x-api-key: $OCX_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
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.