Skip to content

Streams

Describes github.com/stxapp/stx-go v0.3.1, the current release.

type Stream struct {
// contains filtered or unexported fields
}

Stream is one WebSocket connection to the exchange, carrying every topic you subscribe to. Get one with Client.Stream.

The stream signs the handshake afresh on every connect, sends the socket heartbeat, pings each joined topic (at a third of the granted timeout on orders with cancel-on-disconnect, so two pings can be lost before it fires), reconnects with backoff after a drop and rejoins every topic with its current filters, and rejoins a topic the exchange closes while the socket stays up. The account channels send their snapshots again on every rejoin.

A Stream is safe for concurrent use. Close it when you are done.

func (s *Stream) AccountView(ctx context.Context, opts AccountViewOptions) (*AccountView, error)

AccountView subscribes to your account and returns once the four join snapshots have arrived. ctx bounds that wait and the view’s life.

Example

A live view of your account.

ctx := context.Background()
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
stream, err := client.Stream(ctx)
if err != nil {
log.Fatal(err)
}
defer stream.Close()
view, err := stream.AccountView(ctx, stx.AccountViewOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Println(view.Snapshot().Balance.AvailableBalance) // "746.8600"
for change := range view.Changes() {
fmt.Println(change.Kind, len(view.Snapshot().OpenOrders))
}
func (s *Stream) ChannelRejoins() int

ChannelRejoins returns how many topics were rejoined after the exchange closed them while the socket stayed up.

func (s *Stream) Close() error

Close leaves every topic, closes the socket and ends every subscription. It waits for the stream’s goroutines to finish. Calling it again does nothing.

func (s *Stream) ComboMaker(ctx context.Context) (*ComboMaker, error)

ComboMaker joins combo_quote:<user_id>. Where combos are not available it returns a *NotAvailableError. ctx bounds the join and the maker’s life.

func (s *Stream) ComboPlayer(ctx context.Context) (*ComboPlayer, error)

ComboPlayer joins rfq:<user_id>. Where combos are not available it returns a *NotAvailableError (errors.Is(err, ErrNotAvailable)); other refusals, such as a read-only key, are a *ComboRefusedError. ctx bounds the join and the player’s life.

func (s *Stream) Connected() bool

Connected reports whether the socket is up right now.

func (s *Stream) Done() <-chan struct{}

Done is closed when the stream ends: after Close, or when it gives up reconnecting.

func (s *Stream) Err() error

Err returns why the stream ended on its own (credentials that cannot recover, reconnect attempts used up), or nil while it runs and after Close.

func (s *Stream) OrderSlip(ctx context.Context) (*OrderSlip, error)

OrderSlip joins order_slip:<user_id>. ctx bounds the join and the slip’s life.

func (s *Stream) Reconnects() int

Reconnects returns how many times the socket has reconnected.

func (s *Stream) Subscribe(ctx context.Context, ch Channel) (*Subscription, error)

Subscribe joins ch and returns the subscription. Messages arrive on Subscription.Messages until ctx is done, the subscription is closed, or the stream ends; then the channel is closed. ctx bounds the join and the subscription’s whole life.

A refused join returns a *ChannelError with the exchange’s reason, such as “unauthorized”. The account channels need a signed stream.

type AccountChange struct {
Kind AccountChangeKind
// Event is the wire event, for example "update" or "new_open_order".
Event string
// Snapshot is true for a join snapshot (the first seed, or after a
// rejoin): that part was replaced, not patched.
Snapshot bool
// Data is the message's typed payload, as on [Message].
Data any
}

AccountChange is one message an AccountView applied.

type AccountChangeKind string

AccountChangeKind says which part of an AccountView a message touched.

const (
AccountBalance AccountChangeKind = "balance"
AccountOrders AccountChangeKind = "orders"
AccountFills AccountChangeKind = "fills"
AccountPositions AccountChangeKind = "positions"
AccountPayment AccountChangeKind = "payment"
)

The parts of an account view.

type AccountState struct {
// Balance is the latest balance summary, or nil before the first.
Balance *Balance
// OpenOrders are your open orders, newest first.
OpenOrders []Order
// Fills are your fills, newest first.
Fills []Fill
// Positions are your positions, one per market.
Positions []Position
}

AccountState is an AccountView’s state at one moment.

type AccountView struct {
// contains filtered or unexported fields
}

AccountView is a live copy of your account, kept by the stream. It subscribes to balances, orders, fills and positions, seeds each part from the topic’s join snapshot, and applies every update the exchange sends. After a reconnect the snapshots arrive again and replace each part. No REST call is made to keep it current.

Read it with Snapshot whenever you like, or wait on Changes.

func (v *AccountView) Changes() <-chan AccountChange

Changes returns the channel every applied message is announced on, closed when the view ends. When you fall behind, the oldest change is dropped; Snapshot is always current.

func (v *AccountView) Close() error

Close leaves the four topics. The stream stays open.

func (v *AccountView) Done() <-chan struct{}

Done is closed when the view ends.

func (v *AccountView) Err() error

Err returns why the view ended, when one of its subscriptions ended with an error.

func (v *AccountView) MarshalJSON() ([]byte, error)

MarshalJSON writes the current AccountState.

func (v *AccountView) Ready() bool

Ready reports whether every part has had its join snapshot.

func (v *AccountView) Snapshot() AccountState

Snapshot returns the view’s state now. The slices are yours to keep.

type AccountViewOptions struct {
// MarketIDs keeps orders, fills and positions to these markets. The
// balance is always the whole account.
MarketIDs []string
// AccountID picks one of your accounts for the balance; empty means the
// account the stream signed in as.
AccountID string
// KeepFlatPositions keeps positions whose quantity is zero.
KeepFlatPositions bool
// MaxFills is the most fills kept; the oldest go first. Default 1000.
MaxFills int
// SnapshotTimeout bounds the wait for the four join snapshots. Default
// 15s.
SnapshotTimeout time.Duration
}

AccountViewOptions configures Stream.AccountView.

type Channel struct {
// contains filtered or unexported fields
}

Channel is a topic to subscribe to, with its join filters. Build one with a constructor such as OrderbookChannel or OrdersChannel and pass it to Stream.Subscribe. Each channel’s events and payloads are documented at https://docs.stxapp.io/websockets/.

func AccountChannel(marketIDs_ ...string) Channel

AccountChannel carries everything the orders, fills, positions, settlements and balances channels carry, on one topic. Do not also subscribe to one of those (you would get every message twice), and use OrdersChannel if you need cancel-on-disconnect.

func BalancesChannel(accountID string) Channel

BalancesChannel sends your balance on join (“balances”, a Balance), the same summary on every change (“update”), and “payment_update” (PaymentUpdate) as payments move. An empty accountID means the account the socket signed in as.

func EventsChannel(eventIDs ...string) Channel

EventsChannel sends each named event’s traded volume as an “event” message whenever it changes. The join reply carries the current values. At least one event id is required.

func FillsChannel(marketIDs_ ...string) Channel

FillsChannel sends the fills behind your open positions on join (“all_trades”, a FillsSnapshot), then one “trade” (Fill) per execution or status change. Empty marketIDs means all markets.

func MarketChannel(marketIDOrSymbol string) Channel

MarketChannel is one market in full, by id or symbol. The join reply is the market’s current state with its book (read it with Subscription.Reply into a MarketChange); then “market_update” carries the fields that changed and “order_book_update” a fresh book. A resulted or voided market sends its last update, the exchange closes the topic, and the subscription ends. Prices are converted from cents to dollar strings.

func MarketStatsChannel(r StatsRange, marketIDs ...string) Channel

MarketStatsChannel is the price series of each market named. The join reply holds the history (read it with Subscription.Reply into a MarketStatsReply); “market_stats” then sends changed buckets to upsert by timestamp, and “market_stats_snapshot” a series to replace. An empty range means StatsAll. At least one market id is required.

func MarketUpdatesChannel(watch ...string) Channel

MarketUpdatesChannel sends “created” and “updated” for the markets you watch: these, and any added with Subscription.Watch. Watches are sent again after every rejoin. Prices are converted from cents to dollar strings.

func MarketsChannel(f MarketsFilter) Channel

MarketsChannel sends “market_created” and “market_updated” for every market. Each message maps market id to a MarketChange; an update carries only the fields that changed. The exchange sends prices on this channel in cents; the stream converts them to dollar strings like the rest of the API.

func OrderbookChannel(marketIDs ...string) Channel

OrderbookChannel is the aggregated book of each market named: one “book” message per market on the exchange’s publish cadence, each a full snapshot of that market’s book to replace what you hold. At least one market id is required.

func OrdersChannel(f OrdersFilter) Channel

OrdersChannel sends your open orders on join (“all_orders”, an OrdersSnapshot), then each order whenever it changes (“new_open_order”, an Order).

Example

Your orders, with cancel-on-disconnect: the stream pings at a third of the granted timeout for as long as the topic is joined.

ctx := context.Background()
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
stream, err := client.Stream(ctx)
if err != nil {
log.Fatal(err)
}
defer stream.Close()
sub, err := stream.Subscribe(ctx, stx.OrdersChannel(stx.OrdersFilter{CancelOnDisconnect: true}))
if err != nil {
log.Fatal(err)
}
for msg := range sub.Messages() {
switch d := msg.Data.(type) {
case *stx.OrdersSnapshot:
fmt.Println(len(d.Orders), "open orders")
case *stx.Order:
fmt.Println(d.ID, d.Status, d.Filled)
}
}
func PositionsChannel(marketIDs_ ...string) Channel

PositionsChannel sends your positions on join (“all_positions”, a PositionsSnapshot), then “updated_positions” (PositionsUpdate) with only the positions that changed.

func SettlementsChannel(marketIDs_ ...string) Channel

SettlementsChannel sends “new_settlements” (SettlementsUpdate) as they are recorded. There is no snapshot; read history over REST.

func TickerChannel(f TickerFilter) Channel

TickerChannel sends a “ticker” message for each market whose price, top of book, volume or open interest moves. Nothing is sent on join.

func TradesChannel(f TradesFilter) Channel

TradesChannel sends every execution on the exchange as a “trade” message, anonymized. Action is the taker’s side. Your own executions are on FillsChannel.

func UserInfoChannel() Channel

UserInfoChannel sends your profile right after joining, then on every change (“user_updated”, a UserInfo).

func (c Channel) Name() string

Name returns the channel’s name, for example “orderbook” or “orders”.

type MarketFilter struct {
// Top-level category, e.g. a sport or a promotional section.
Category string `json:"category,omitempty"`
// Grouping within the section.
Grouping string `json:"grouping,omitempty"`
// Whether the categorization was assigned by hand.
Manual bool `json:"manual,omitempty"`
// Section heading this market groups under.
Section string `json:"section,omitempty"`
// Category within `category`, e.g. a competition.
Subcategory string `json:"subcategory,omitempty"`
// Grouping within `grouping`.
Subgrouping string `json:"subgrouping,omitempty"`
}

MarketFilter: One categorization this market appears under.

type MarketsFilter struct {
// RuleFilters keeps only markets whose rules match one of these.
RuleFilters []string
// MessageTypes picks "market_created", "market_updated" or both.
MessageTypes []string
}

MarketsFilter narrows MarketsChannel.

type Message struct {
// Topic is the wire topic, for example "orders:7fb55544-3a7e-4f6b-bd66-fc89bd3a1087".
Topic string
// Event is the event name, for example "all_orders", "new_open_order"
// or "book".
Event string
// Payload is the event's JSON. Money and quantities are strings; on the
// markets, market_updates and market:<id> channels the stream has already
// converted the exchange's cents to dollar strings.
Payload json.RawMessage
// Snapshot is true for the state sent on join, again after every rejoin:
// "all_orders", "all_trades", "all_positions", "balances" and
// "user_updated". Replace what you hold rather than merging.
Snapshot bool
// Data is the payload decoded into the type documented for the event,
// or nil for an event the SDK does not know. Switch on its type:
//
// orderbook book *OrderbookUpdate
// ticker ticker *Ticker
// trades trade *PublicTrade
// events event *EventVolume
// markets market_created/_updated MarketChanges
// market_updates created/updated *MarketChange
// market:<id> market_update/order_book_update *MarketChange
// market_stats market_stats(_snapshot) *MarketSeries
// orders all_orders / new_open_order *OrdersSnapshot / *Order
// fills all_trades / trade *FillsSnapshot / *Fill (TradeID is the channel's "id")
// positions all_positions / updated_positions *PositionsSnapshot / *PositionsUpdate
// settlements new_settlements *SettlementsUpdate
// balances balances, update / payment_update *Balance / *PaymentUpdate
// user_info user_updated *UserInfo
// order_slip order_numbers_batch / self_match_batch *OrderNumbersBatch / *SelfMatchBatch
//
// The account channel carries the orders, fills, positions, settlements
// and balances events with the same types.
Data any
}

Message is one event pushed on a subscription.

func (m Message) Channel() string

Channel returns the topic without the user id, for example “orders”.

func (m Message) Decode(v any) error

Decode decodes the payload into v.

type OrderSlip struct {
// contains filtered or unexported fields
}

OrderSlip costs orders before you place them, on order_slip:<user_id>. Register an order with Add and the exchange sends what it would cost (risk, fee, how much would fill now and at which prices) as an “order_numbers_batch”, then again every time the book moves. Nothing is placed. Get one with Stream.OrderSlip.

Entries live as long as the topic: after a reconnect the stream rejoins, but you add your entries again. The protocol is at https://docs.stxapp.io/websockets/channels/order-slip/.

func (o *OrderSlip) Add(ctx context.Context, e OrderSlipEntry) (OrderSlipRef, error)

Add registers an entry and returns its ref. Its first numbers arrive on OrderSlip.Messages at once.

func (o *OrderSlip) Close() error

Close leaves the topic; every entry goes with it.

func (o *OrderSlip) Done() <-chan struct{}

Done is closed when the slip ends.

func (o *OrderSlip) Err() error

Err returns why the slip ended, like Subscription.Err.

func (o *OrderSlip) Messages() <-chan Message

Messages returns the channel the projections arrive on, with Data a *OrderNumbersBatch or a *SelfMatchBatch.

func (o *OrderSlip) Remove(ctx context.Context, ref string) error

Remove unregisters an entry by its ref.

func (o *OrderSlip) Topic() string

Topic returns the wire topic.

type OrderSlipEntry struct {
MarketID string `json:"market_id"`
// Side is "buy" or "sell".
Side string `json:"side"`
// Quantity is the contracts you are considering.
Quantity Decimal `json:"qty"`
// MaxPrice is the market's max price in dollars, for example "1".
MaxPrice Decimal `json:"max_price"`
// LimitPrice is your limit in dollars; leave it empty for a market order.
LimitPrice Decimal `json:"limit_price,omitempty"`
}

OrderSlipEntry is an order to cost.

type OrderSlipFill struct {
Price Decimal `json:"price"`
Quantity Decimal `json:"qty"`
Fee Decimal `json:"fee"`
}

OrderSlipFill is one price level of an entry’s immediate fill.

type OrderSlipRef struct {
Ref string `json:"ref"`
SelfMatch bool `json:"self_match"`
}

OrderSlipRef identifies a registered entry. SelfMatch is true when one of your own open orders is in the way, so placing it would be refused.

type OrdersFilter struct {
// MarketIDs keeps only orders on these markets; empty means all.
MarketIDs []string
// CancelOnDisconnect arms cancel-on-disconnect for the orders you place
// with it. The stream then pings at a third of the timeout the exchange
// grants for as long as the topic is joined.
CancelOnDisconnect bool
// PingTimeout is the cancel-on-disconnect deadline to ask for. The
// exchange clamps it to 5s to 20s. Default 5s.
PingTimeout time.Duration
}

OrdersFilter configures OrdersChannel.

type ReconnectPolicy struct {
// InitialBackoff is the wait before the first attempt. Default 500ms.
InitialBackoff time.Duration
// MaxBackoff caps the wait. Default 30s.
MaxBackoff time.Duration
// MaxAttempts is how many attempts to make before giving up; 0 never
// gives up.
MaxAttempts int
// NoJitter uses the exact doubling waits.
NoJitter bool
}

ReconnectPolicy is the backoff between reconnect attempts: the wait doubles from InitialBackoff up to MaxBackoff, each wait drawn between 50% and 100% of its value unless NoJitter is set.

type StatsRange string

StatsRange is how far back a price series reaches.

const (
StatsDay StatsRange = "day"
StatsWeek StatsRange = "week"
StatsMonth StatsRange = "month"
StatsAll StatsRange = "all"
)

The ranges MarketStatsChannel and Subscription.RequestSeries take.

type StreamOption func(*streamConfig)

StreamOption configures a Stream.

func WithBufferSize(n int) StreamOption

WithBufferSize sets how many messages each subscription buffers for you. When you fall behind and the buffer is full, the oldest message is dropped and a warning is logged. Default 10000.

func WithChannelPingInterval(d time.Duration) StreamOption

WithChannelPingInterval sets the time between channel pings on every joined topic that answers them; 0 turns them off. The orders channel with cancel-on-disconnect always pings at a third of the timeout the exchange granted, whatever this is. Default 30s.

func WithHeartbeatInterval(d time.Duration) StreamOption

WithHeartbeatInterval sets the time between socket heartbeats. The exchange closes a socket silent for 60 seconds. Default 25s.

func WithJoinTimeout(d time.Duration) StreamOption

WithJoinTimeout sets how long to wait for the reply to a join or a channel command. Default 10s.

func WithOnReconnect(fn func()) StreamOption

WithOnReconnect sets a function called after every reconnect and rejoin, and after a topic the exchange closed is rejoined while the socket stayed up. It is the moment to reload over REST what you cannot rebuild from the snapshots the account channels send again on rejoin, such as history. It runs on its own goroutine.

func WithReconnectPolicy(p ReconnectPolicy) StreamOption

WithReconnectPolicy sets the backoff between reconnect attempts.

func WithStreamLogger(l *slog.Logger) StreamOption

WithStreamLogger sets where the stream logs reconnects, rejoins and dropped messages. Default: the client’s logger.

func WithUserID(id string) StreamOption

WithUserID gives the stream your user id, which the account topics are named by, so it does not ask GET /api/v1/me for it.

func WithoutReconnect() StreamOption

WithoutReconnect ends the stream, and every subscription on it, when the socket drops, instead of reconnecting.

type Subscription struct {
// contains filtered or unexported fields
}

Subscription is one joined topic on a Stream.

func (sub *Subscription) Close() error

Close leaves the topic and ends the subscription. Messages already buffered stay readable until the channel closes.

func (sub *Subscription) DecodeReply(v any) error

DecodeReply decodes the latest join reply into v.

func (sub *Subscription) Done() <-chan struct{}

Done is closed when the subscription ends.

func (sub *Subscription) Err() error

Err returns why the subscription ended: the context’s error, the stream’s error, or a *ChannelError when a rejoin was refused for good. It is nil while the subscription runs, after Close, and after the exchange closed a finished market.

func (sub *Subscription) Joined() bool

Joined reports whether the topic is joined right now. It is false while the stream reconnects.

func (sub *Subscription) Messages() <-chan Message

Messages returns the channel messages arrive on. It is closed when the subscription ends; Subscription.Err then says why.

func (sub *Subscription) Ping(ctx context.Context) error

Ping sends the channel ping. On orders with cancel-on-disconnect it resets the deadline; the stream already pings on a timer.

func (sub *Subscription) Push(ctx context.Context, event string, payload any) (json.RawMessage, error)

Push sends event on the topic and returns the reply’s response. A refusal is a *ChannelError.

func (sub *Subscription) Reply() json.RawMessage

Reply returns the latest join reply’s response: the applied filters, and on some channels the state, such as the series on market_stats or the whole market on market:<id> (prices in dollar strings).

func (sub *Subscription) RequestSeries(ctx context.Context, r StatsRange, marketIDs ...string) (*MarketStatsReply, error)

RequestSeries fetches price history at r for these markets on a market_stats subscription, without changing what streams.

func (sub *Subscription) RequestSnapshot(ctx context.Context) error

RequestSnapshot asks a market:<id> subscription to send the market’s current “market_update” and “order_book_update” again now.

func (sub *Subscription) SelectEventIDs(ctx context.Context, eventIDs []string) (json.RawMessage, error)

SelectEventIDs changes which events stream on the events channel. At least one id is required.

func (sub *Subscription) SelectFilters(ctx context.Context, filters map[string][]string) (json.RawMessage, error)

SelectFilters changes the filters on ticker (“sports”, “competitions”) and trades (“market_ids”, “event_ids”) without rejoining. A nil list clears that filter.

func (sub *Subscription) SelectMarketIDs(ctx context.Context, marketIDs []string) (json.RawMessage, error)

SelectMarketIDs changes the market filter without rejoining, on orderbook, market_stats and the account channels. nil clears it on the account channels; orderbook and market_stats need at least one id.

func (sub *Subscription) SelectMessageTypes(ctx context.Context, types []string) (json.RawMessage, error)

SelectMessageTypes picks “market_created”, “market_updated” or both on markets; nil means both.

func (sub *Subscription) SelectRuleFilters(ctx context.Context, rules []string) (json.RawMessage, error)

SelectRuleFilters changes the rules filter on markets; nil turns it off.

func (sub *Subscription) Topic() string

Topic returns the wire topic, for example “orders:7fb55544-3a7e-4f6b-bd66-fc89bd3a1087”.

func (sub *Subscription) Watch(ctx context.Context, marketIDs ...string) (json.RawMessage, error)

Watch adds markets to a market_updates subscription. Watches are sent again after every rejoin.

type TickerFilter struct {
Sports []string
Competitions []string
}

TickerFilter narrows TickerChannel. Values match exactly, so “Football” and “football” differ.

type TradesFilter struct {
MarketIDs []string
EventIDs []string
}

TradesFilter narrows TradesChannel.

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