Skip to main content
This page builds a program that reads your account over HTTP, then follows a market’s order book, its trades and your own fills over the WebSocket, printing the top of the book as it changes. It picks up from the Quickstart.

Read the Account

The account reads are methods on the client. Each takes a market, or perps.MarketAll for all of them:
The fields are those of Get Account Balances and Get Account Positions. Amounts are strings, as on the wire, so no precision is lost. Deposits, Withdrawals and Fundings return one perps.Page at a time. Pass Next back as the cursor until it comes back empty; CompletedOrders takes it in its query:
OpenOrders follows the cursor for you and returns every open order.

Subscribe to Streams

perps.WithSubscriptions adds streams beyond the Order Creation Stream when the connection opens; conn.Subscribe and conn.Unsubscribe change the set later. The set survives reconnects.

Handle Events

Everything the connection receives arrives as a typed event on conn.Events(). The channel applies backpressure instead of dropping events, so it must be read: a consumer that stops reading stalls the connection.
perps.OrderBookDelta is handled below. perps.OrderFilled and perps.OrderRejected are your orders filling or being refused after the command that placed them returned. perps.Connected and perps.Disconnected report the socket coming and going. perps.Unknown is a message this version of the SDK has no type for.

Keep an Order Book

A local book starts from a snapshot and applies each delta after it, as the Order Book guide describes. Deltas carry no sequence number, so take a new snapshot after every reconnect. perps.Connected arrives for the first socket and for each reconnect. A snapshot is a request on the connection. It is asked for off the event loop, which has to keep reading events while it waits:
Deltas keep arriving while the snapshot is on its way. Hold them back, and once the snapshot has arrived replay those not older than its Ts, dropping any older delta that is still queued; discard a snapshot that was requested before a later reconnect. The example has that bookkeeping. Snapshot levels (snapshot.Orders) and delta levels are applied the same way: each replaces the level at its price, and a quantity of 0 removes it.

After a Reconnect

perps.SessionBackfill reports how the session was recovered, on the first connection and after each reconnect. When the session could not be resumed, or a market’s backfill expired, rebuild your order state over HTTP:

Run the Example

The complete program is examples/perps-streams-and-account in the SDK repository. Run it for as long as you want to watch:
The first rebuilt line is the fresh session reporting that nothing was resumed.