Never poll MCP reads to discover fills: authenticated reads draw a per-account read budget (30 requests/s sustained, burst 100 by default, no headers); stream events cost none.
Before you start
- Authenticate with a Monaco session key: your wallet authorizes an ed25519 session keypair that signs every request. See Wallets & Auth.
- Run the MCP server authenticated with
MONACO_CAPABILITY=market-makerto register order tools. See MCP Server. - To quote from a signer wallet that has no custody of the funds, use a delegated agent.
- Start with a dedicated wallet and small sizes. On AWS, PrivateLink is available.
- Resolve the trading pair ID, tick size, and order-size limits up front. See Markets and Orderbooks & Trades.
- Know your order budgets: per account, in order items (a batch of N costs N), cancels on a larger budget of their own, sub-accounts sharing their master’s. Raw HTTP and gRPC clients get
x-ratelimit-*headers; the TypeScript SDK surfaces onlyretryAfteron a429. Use batch create, replace, and cancel, and back off forretryAfter.
1. Bootstrap
Authenticate, resolve the market, and snapshot open orders, positions, and balances. The state plane keeps this current from here.2. Subscribe to the state plane
Recovery needsonResync and onStatusChange (step 4). The built-in sdk.ws takes them via new MonacoSDK({ ..., ws: { onStatusChange, onResync } }); this example uses createMonacoWebSocket.
- Each subscription returns an unsubscribe function.
ws.orderbook,ws.depth,ws.bbo, andws.tradesare public; the rest require authentication.ws.userOrderscovers all pairs.ws.positionsandws.liquidationstake an optional trailingtradingPairIdfilter.magnitudeis one of0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000;quotationModeis"BASE"or"QUOTE".- Event shapes: SDK WebSockets.
Keeping a full book with depth
ws.orderbook is a display feed (at most 20 buckets per side, restated at most every 100 ms). To price off the real book, use ws.depth: a snapshot of up to 1000 levels per side, then only changed levels, each frame linked to the previous by bookSeq. ws.bbo sends a frame on every best bid/ask price or size change.
For a cross-check,
sdk.orderbook.getOrderbook(pair.id, { depth: 1000, tradingMode: mode }) returns bookSeq (MCP get_orderbook: spot only). It is a point-in-time check, never a base for the stream, and above 100 levels draws the deep orderbook read budget; the stream is free.
Pass onGap to ws.trades to learn when a trade print was lost (Sequenced trades).
3. Quote lifecycle
Send through the command plane; learn outcomes from the state plane.- Fills and cancels arrive on
ws.orders; balance changes onws.balances.ws.movementscarries deposits, withdrawals, funding, and cancelled/expired-order unlocks, never fills or fees (read those from movement history). - Reprice off
ws.orderbookandws.trades. Track perp position and risk-bucket changes offws.positionsand treatws.liquidationsas a hard risk signal.sdk.positions.getPositionRisk(positionId)(MCPget_position_risk) gives a full breakdown.
Post-only quotes
data.postOnly is true on a post-only order’s OrderPlaced, maker fills, OrderPartiallyCancelled, OrderCancelled, and OrderExpired. Record it from OrderPlaced and carry it forward: maker fills from a server predating maker-fill support omit it, as does the IOC/market-remainder OrderCancelled (which a post-only order never produces). Elsewhere data.postOnly ?? false matches get_order. A crossing post-only quote is refused at admission as a command-plane error; a missing acknowledgement is not evidence of rejection.
Quote and reprice post-only. A placement or replacement that is not post-only can be held for a short fixed time before it is queued, and cancels and post-only placements and replacements are never held. That gives a cancel a head start on a taker’s order sent at the same moment. It is extra time to cancel, not a guarantee: a cancel that arrives after the hold ends, or behind a large burst of other cancels, can still be processed after the taker’s order. postOnly is not inherited on a replace: set it on every replacement. An order does not exist while it is held, so a cancel, cancel-all or cancelAllAfter that runs during its hold does not cancel it. The hold is 50 ms on every spot and perpetual market, on mainnet and on testnet.
Self-trade prevention
When your own flow crosses your own quote, the incoming order’s mode decides. The defaultCANCEL_MAKER cancels (does not fill) your resting quote and the incoming order keeps matching. To keep quotes alive, set SKIP (trade around your orders) or CANCEL_TAKER (drop the incoming remainder). CANCEL_BOTH also exists.
- Set the default from the wallet’s own session; a delegated-agent session gets
403. - A per-order
selfTradePreventionModeon create, replace, or batch items overrides it. A replacement is a new order, so restate the field. - STP cancels arrive as
OrderCancelledwithterminalReason: "SELF_TRADE_PREVENTION"andstpCounterpartyOrderId. If they recur, change the mode. - Your quote is not swept when a crossing
postOnlyorder is refused at admission (that check ignores ownership and runs before STP), or when a zero-fillMARKETtaker whose only in-band depth was your quote is rejected for insufficient liquidity. A rejected taker does not mean your quote was pulled; check theorderschannel. - Mode outcomes, FOK edges, liquidation carve-out: Self-Trade Prevention.
4. Reconnect and resync
The WebSocket auto-reconnects with full-jitter exponential backoff (base 1s, cap 30s), unlimited retries by default. Order, balance, and position streams have no wire sequence number, so assume every reconnect missed events;ws.depth and ws.bbo carry bookSeq and rebuild from the snapshot each reconnect brings, with no REST read. onResync fires after each automatic reconnect, once auth and subscription requests are sent; it does not wait for acknowledgements or snapshots. REST recovery is yours.
Reconcile on (id, version)
Every order event and order REST row carries version, the sequencer step that wrote it, on one shared counter. Keep applying events; when a snapshot lands, merge per order:
>=: one step can emit several events for an order (OrderPlaced then its fills), and a batch shares one step, while a REST row is the step’s final state, so on a tie the snapshot is more complete. No buffering is needed; keep quoting through a reconnect.
version rules:
- Absent means unknown, not zero: orders last written before the field existed have none.
- Gaps are expected. One global sequence serves every order, so versions are sparse (
918342→918511) and not comparable across orders.
Catch what went terminal during the gap
An order that filled or cancelled while disconnected is absent from both your stream and a resting-status snapshot.getPaginatedOrders has no time filter and sorts by createdAt descending, so an old quote that just filled is deep in history. Use two bounded checks.
1. Fills. sdk.profile.getUserTrades sorts by execution time, newest first, so page back only to the disconnect. Trade rows carry no order ID; merge by tradeId.
getOrder(id) and apply the version rule; do not delete it.
REJECTED and caught by the absence check.
When version is absent: buffer and replay
For orders in needsReplay (pre-version rows or an older deployment): start buffering order events before fetching, fetch the snapshot, replace those orders from it, replay the buffer in arrival order, then resume. Events carry absolute state (filledQuantity is cumulative), so replay does not double-count. Hold quoting until replay finishes, since an older event moves the order backwards until the buffer drains.
Comparing two REST reads
Higherversion is fresher; equal REST versions mean identical state. Do not compare updatedAt: getOrder and getPaginatedOrders use different clocks that disagree by a few hundred milliseconds and more under load, the list’s value can change without a state change, and precision varies. Without version, compare all fields.
5. Mutation safety
MCP and the TypeScript SDK generate a create key when omitted, but a new one per call; supply your own when recovery crosses calls or restarts.
Never blind-retry an unkeyed or expired create, or an ambiguous replace: it can double your size. Reconcile first, using the steps in Recovering from a lost response. Each surface can prove the intent landed, never that it did not. Strongest first:
clientOrderIdon the order stream. Set it on every create and replace; it is echoed on every order event, including cancels and orders that never rested. A match proves acceptance; silence proves nothing. Uniqueness and409 CLIENT_ORDER_ID_CONFLICTrules: Client Order IDs.- Exchange
orderId(replace).terminalReason: "REPLACED"on the original viaget_orderproves the replacement landed. A still-resting original is inconclusive, since persistence is asynchronous. - Attributes and a narrow time window, as a last resort: pair, side, price, and quantity among orders from the last few seconds. Identical quotes collide, so a match is provisional.
strategyKey is not a reconciliation key: it names the margin account by its sub-account key and is echoed on the create response and TWAP orders and events, but not on get_order or get_orders rows, and the list cannot filter by it.
Include filled orders, confirm against ws.orders, and do not trust the order list alone: history is written asynchronously, so an executed order can read as absent right after a timeout. If you cannot prove the intent did not land, hold and escalate: a missed quote is recoverable, a doubled position may not be.
6. Emergency stop
Keep a kill switch: cancel all resting orders, then close all positions.Shut down
PrivateLink
AWS PrivateLink connects a market maker’s own AWS VPC privately to Monaco’s gRPC trading API, REST API and WebSocket feeds, keeping traffic on the AWS network. Orders sent over PrivateLink, by gRPC or REST, draw higher order rate limits than the public endpoints. PrivateLink carries no public client address, so two account steps stay on the public endpoints: redeem an invite code there before signing in over PrivateLink, and create delegated sessions for an agent with anipAllowlist there too. Over PrivateLink an invite redemption is refused with 503 and an IP-restricted delegated session with 403; unrestricted delegated sessions and every other call work as on the public endpoints.
PrivateLink is offered on request: contact team@0xmonaco.com, and the team shares connection details during onboarding. Until then, use the public endpoints in the Quickstart.
Related
MCP Server
Command plane tools, capability profiles, and setup.
SDK WebSockets
State plane channels, event shapes, and the resync contract.
Delegated Agents
Quote from a signer wallet without custody.
Keeping a local book
The
depth and bbo wire rules: snapshot, book_seq links, and gap handling.Rate Limits
Order and read budgets.

