Skip to content

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.

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.

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 callback
await ws.TradesAsync(marketIds: ids, onMessage: msg => Console.WriteLine($"{msg.Event} {msg.Payload}"));
// One message, with a timeout
var book = await ws.OrderbookAsync(ids);
var next = await book.NextAsync(TimeSpan.FromSeconds(5)); // TimeoutException when nothing arrives
Console.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 closes
await 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.

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);
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.

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.

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.

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.

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;

STX is operated by XV Exchange, LLC, a Designated Contract Market regulated by the U.S. Commodity Futures Trading Commission (CFTC). Contracts traded on STX are cleared by XV Clearing, LLC, a CFTC-registered Derivatives Clearing Organization. Trading involves substantial risk of loss and may not be appropriate for everyone. Members risk losing the cost to enter any transaction, including fees. Consider whether trading is appropriate for you in light of your experience and financial resources. Nothing on this site is investment advice or a recommendation to trade. Past performance is not indicative of future results.

© 2026 STX. All rights reserved.llms.txtllms-full.txtView as Markdown
Docs version v1.10.5