Skip to main content
A market maker uses two planes: the MCP server (or SDK) to command the exchange and take point-in-time snapshots, and the Core SDK WebSocket to track fills, cancels, risk, and book movement between commands. The MCP server has no streaming tools, so a maker driven by MCP snapshots alone ends up with stale quotes and one-sided exposure. 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-maker to 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 only retryAfter on a 429. Use batch create, replace, and cancel, and back off for retryAfter.
The examples use the TypeScript SDK; each command notes its MCP equivalent.

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 needs onResync 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, and ws.trades are public; the rest require authentication. ws.userOrders covers all pairs.
  • ws.positions and ws.liquidations take an optional trailing tradingPairId filter.
  • magnitude is one of 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000; quotationMode is "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 on ws.balances. ws.movements carries deposits, withdrawals, funding, and cancelled/expired-order unlocks, never fills or fees (read those from movement history).
  • Reprice off ws.orderbook and ws.trades. Track perp position and risk-bucket changes off ws.positions and treat ws.liquidations as a hard risk signal. sdk.positions.getPositionRisk(positionId) (MCP get_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 default CANCEL_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 selfTradePreventionMode on create, replace, or batch items overrides it. A replacement is a new order, so restate the field.
  • STP cancels arrive as OrderCancelled with terminalReason: "SELF_TRADE_PREVENTION" and stpCounterpartyOrderId. If they recur, change the mode.
  • Your quote is not swept when a crossing postOnly order is refused at admission (that check ignores ownership and runs before STP), or when a zero-fill MARKET taker whose only in-band depth was your quote is rejected for insufficient liquidity. A rejected taker does not mean your quote was pulled; check the orders channel.
  • 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:
Use >=: 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.
2. Cancels and expiries. A locally resting order missing from the snapshot may have left the book, or the snapshot may lag. Fetch it with getOrder(id) and apply the version rule; do not delete it.
Re-derive intended quotes from reconciled state after every resync. An order rejected before acceptance never rested and has no history row; one rejected after acceptance is stored as 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

Higher version 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:
  1. clientOrderId on 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 and 409 CLIENT_ORDER_ID_CONFLICT rules: Client Order IDs.
  2. Exchange orderId (replace). terminalReason: "REPLACED" on the original via get_order proves the replacement landed. A still-resting original is inconclusive, since persistence is asynchronous.
  3. 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.
The calls are not atomic: an order can fill between them and a close can partially fill. Re-check orders and positions against the state plane and repeat until flat. Trigger it from risk limits (drawdown, unrecoverable connectivity loss, manual halt). Your kill switch runs only while your process does. Against a crash, hang, or partition, also arm the exchange’s dead man’s switch and refresh it from your main loop:
It cancels resting orders only, never positions, and a fired timer is spent: re-arm after recovery. See Cancel All After.

Shut down

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 an ipAllowlist 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.

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.