WebSockets
The client streams the channels documented under WebSockets: what each channel sends, its payloads and its limits are covered there. This page shows the SDK calls.
Connect and join
Section titled “Connect and join”using STX.Sdk;
using var client = new STXClient();await using var ws = client.CreateWebSocket();
var ticker = await ws.TickerAsync();Console.WriteLine(ticker.Reply.ToJsonString());CreateWebSocket() uses the client’s host and key, and signs the handshake with the key. The first join connects; each join method returns an STXChannel. One socket carries every channel you join. Disposing the socket leaves every channel and closes it.
Receive messages
Section titled “Receive messages”Each message (STXChannelMessage) has Topic, Event and Payload, a JsonNode. Take them with a callback, one at a time, or with await foreach:
var ids = (await client.GetMarketsAsync(status: ["open"], limit: 5)).Select(m => m.MarketId!).ToList();
// A callbackawait ws.TradesAsync(marketIds: ids, onMessage: msg => Console.WriteLine($"{msg.Event} {msg.Payload}"));
// One message, with a timeoutvar book = await ws.OrderbookAsync(ids);var next = await book.NextAsync(TimeSpan.FromSeconds(5)); // TimeoutException when nothing arrivesConsole.WriteLine(next.Payload!["bids"]!.AsArray().FirstOrDefault()?.ToJsonString() ?? "no bids");// {"quantity":"702.00","price":"0.4600","total_liquidity":"322.9200","liquidity":"322.9200","total_quantity":"702.00"}
// Every message, until the channel closesawait foreach (var msg in book.ReadAllAsync()) Console.WriteLine($"{msg.Payload!["market_id"]} {msg.Payload["bids"]?.AsArray().FirstOrDefault()?["price"]}");msg.As<T>() reads the payload as a model, e.g. msg.As<Order>() on a new_open_order. Money fields are dollar strings on every channel, including the ones that send cents on the wire.
Snapshots
Section titled “Snapshots”The orders, fills, positions and balances channels send your current state right after the join, and WaitSnapshotAsync() returns it, keyed by event name. settlements sends no snapshot, only new settlements, so do not wait for one there.
var positions = await ws.PositionsAsync();var snap = await positions.WaitSnapshotAsync(TimeSpan.FromSeconds(10));Console.WriteLine(snap["all_positions"]!["positions"]!.AsArray().Count);Channels
Section titled “Channels”| SDK call | Channel |
|---|---|
OrderbookAsync(marketIds) |
Order book, ticker and trades |
TickerAsync(sports, competitions) |
Order book, ticker and trades |
TradesAsync(marketIds, eventIds) |
Order book, ticker and trades |
MarketAsync(marketId) |
Market order book |
MarketsAsync(ruleFilters, messageTypes) |
Markets |
MarketStatsAsync(marketIds, range) |
Market stats |
MarketUpdatesAsync(watch) |
Market updates |
OrdersAsync(marketIds, cancelOnDisconnect, pingTimeout) |
Orders |
FillsAsync(marketIds) |
Fills |
PositionsAsync(marketIds) |
Positions |
SettlementsAsync(marketIds) |
Settlements |
BalancesAsync(accountId) |
Balances |
AccountAsync(marketIds) |
Account |
UserInfoAsync() |
User info |
RfqAsync(), ComboQuoteAsync() |
Combo negotiation; see Combos |
Every join method also takes onMessage. To change filters after joining, call channel.SelectMarketIdsAsync([...]) (and SelectFiltersAsync, SelectRuleFiltersAsync, SelectMessageTypesAsync); on market_updates, channel.WatchAsync([...]). ws.JoinAsync(topic, payload) joins any other topic. A topic can be joined once per socket.
Live account view
Section titled “Live account view”AccountViewAsync() keeps your balance, open orders, fills and positions current. It joins the balances, orders, fills and positions channels, starts from their snapshots, applies every update, and starts over from fresh snapshots after a reconnect. It returns once all four snapshots are in.
await using var ws = client.CreateWebSocket();
var view = await ws.AccountViewAsync(onChange: change => Render(change.View.State()));// change.Kind: balance, orders, fills, positions or payment
Console.WriteLine($"{view.Balance?.AvailableBalance} {view.OpenOrders.Count} {view.Fills.Count} {view.Positions.Count}");// 10019994.0700 0 20 0
// No refetch needed: the new order and the balance change arrive on the socket.await client.PlaceOrderAsync(marketId, "buy", "limit", quantity: "1", price: "0.01");view.State() returns the whole view as JSON you can send to a browser. Options: marketIds, accountId, maxFills (default 1000), keepFlatPositions, snapshotTimeout (default 15 seconds). Disposing the view leaves the four channels and keeps the socket open. The view joins orders itself, so arm cancel-on-disconnect on a second socket.
Reconnects
Section titled “Reconnects”The socket sends the heartbeat and channel pings for you. After a drop it reconnects with backoff, signs again, and rejoins every channel with its current filters, so the snapshots arrive again. It cannot know what you missed while offline, so read again anything you loaded with a client method (open orders, history) in OnReconnect:
await using var ws = client.CreateWebSocket(new STXWebSocketOptions{ ReconnectPolicy = new STXReconnectPolicy { InitialBackoff = TimeSpan.FromSeconds(0.5), MaxBackoff = TimeSpan.FromSeconds(30), MaxAttempts = 20 }, OnReconnect = async () => { var open = await client.GetOrdersAsync(status: ["created", "requested", "accepted", "delayed", "open"]); Console.WriteLine($"reconnected, open orders: {open.Count}"); },});Reconnect = false turns reconnecting off. ws.Connected and ws.Reconnects report the socket’s state. After a reconnect explains what the exchange does and does not replay.
Errors
Section titled “Errors”A refused join throws STXChannelException, with the server’s reason in Reason and its reply in Reply. A channel the exchange does not have throws STXChannelUnavailableException. No reply within JoinTimeout (default 10 seconds) throws STXChannelException too.
Keep a worker running
Section titled “Keep a worker running”ws.Completion completes when you dispose the socket or it gives up reconnecting:
await using var ws = client.CreateWebSocket();await ws.FillsAsync(onMessage: m => Console.WriteLine($"fill {m.Payload}"));Console.CancelKeyPress += async (_, e) => { e.Cancel = true; await ws.DisposeAsync(); };await ws.Completion;
