# Streams

> Streams, subscriptions, channels and the live account view.

Source: https://docs.stxapp.io/sdks/go/reference/websocket/

## Stream

```go
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](/sdks/go/reference/client/#clientstream).

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.

### Stream.AccountView

```go
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.

```go
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))
}
```

### Stream.ChannelRejoins

```go
func (s *Stream) ChannelRejoins() int
```

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

### Stream.Close

```go
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.

### Stream.ComboMaker

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

ComboMaker joins combo\_quote:&lt;user\_id&gt;. Where combos are not available it returns a \*[NotAvailableError](/sdks/go/reference/errors/#notavailableerror). ctx bounds the join and the maker's life.

### Stream.ComboPlayer

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

ComboPlayer joins rfq:&lt;user\_id&gt;. Where combos are not available it returns a \*[NotAvailableError](/sdks/go/reference/errors/#notavailableerror) (errors.Is(err, ErrNotAvailable)); other refusals, such as a read-only key, are a \*[ComboRefusedError](/sdks/go/reference/errors/#comborefusederror). ctx bounds the join and the player's life.

### Stream.Connected

```go
func (s *Stream) Connected() bool
```

Connected reports whether the socket is up right now.

### Stream.Done

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

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

### Stream.Err

```go
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.

### Stream.OrderSlip

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

OrderSlip joins order\_slip:&lt;user\_id&gt;. ctx bounds the join and the slip's life.

### Stream.Reconnects

```go
func (s *Stream) Reconnects() int
```

Reconnects returns how many times the socket has reconnected.

### Stream.Subscribe

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

Subscribe joins ch and returns the subscription. Messages arrive on [Subscription.Messages](/sdks/go/reference/websocket/#subscriptionmessages) 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](/sdks/go/reference/errors/#channelerror) with the exchange's reason, such as "unauthorized". The account channels need a signed stream.

## AccountChange

```go
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](/sdks/go/reference/websocket/#accountview) applied.

## AccountChangeKind

```go
type AccountChangeKind string
```

AccountChangeKind says which part of an [AccountView](/sdks/go/reference/websocket/#accountview) a message touched.

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

The parts of an account view.

## AccountState

```go
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](/sdks/go/reference/websocket/#accountview)'s state at one moment.

## AccountView

```go
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.

### AccountView.Changes

```go
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.

### AccountView.Close

```go
func (v *AccountView) Close() error
```

Close leaves the four topics. The stream stays open.

### AccountView.Done

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

Done is closed when the view ends.

### AccountView.Err

```go
func (v *AccountView) Err() error
```

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

### AccountView.MarshalJSON

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

MarshalJSON writes the current [AccountState](/sdks/go/reference/websocket/#accountstate).

### AccountView.Ready

```go
func (v *AccountView) Ready() bool
```

Ready reports whether every part has had its join snapshot.

### AccountView.Snapshot

```go
func (v *AccountView) Snapshot() AccountState
```

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

## AccountViewOptions

```go
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](/sdks/go/reference/websocket/#streamaccountview).

## Channel

```go
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](/sdks/go/reference/websocket/#orderbookchannel) or [OrdersChannel](/sdks/go/reference/websocket/#orderschannel) and pass it to [Stream.Subscribe](/sdks/go/reference/websocket/#streamsubscribe). Each channel's events and payloads are documented at [https://docs.stxapp.io/websockets/](https://docs.stxapp.io/websockets/).

### AccountChannel

```go
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](/sdks/go/reference/websocket/#orderschannel) if you need cancel-on-disconnect.

### BalancesChannel

```go
func BalancesChannel(accountID string) Channel
```

BalancesChannel sends your balance on join ("balances", a [Balance](/sdks/go/reference/types/#balance)), the same summary on every change ("update"), and "payment\_update" ([PaymentUpdate](/sdks/go/reference/types/#paymentupdate)) as payments move. An empty accountID means the account the socket signed in as.

### EventsChannel

```go
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.

### FillsChannel

```go
func FillsChannel(marketIDs_ ...string) Channel
```

FillsChannel sends the fills behind your open positions on join ("all\_trades", a [FillsSnapshot](/sdks/go/reference/types/#fillssnapshot)), then one "trade" ([Fill](/sdks/go/reference/types/#fill)) per execution or status change. Empty marketIDs means all markets.

### MarketChannel

```go
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](/sdks/go/reference/websocket/#subscriptionreply) into a [MarketChange](/sdks/go/reference/types/#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.

### MarketStatsChannel

```go
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](/sdks/go/reference/websocket/#subscriptionreply) into a [MarketStatsReply](/sdks/go/reference/types/#marketstatsreply)); "market\_stats" then sends changed buckets to upsert by timestamp, and "market\_stats\_snapshot" a series to replace. An empty range means [StatsAll](/sdks/go/reference/websocket/#statsrange). At least one market id is required.

### MarketUpdatesChannel

```go
func MarketUpdatesChannel(watch ...string) Channel
```

MarketUpdatesChannel sends "created" and "updated" for the markets you watch: these, and any added with [Subscription.Watch](/sdks/go/reference/websocket/#subscriptionwatch). Watches are sent again after every rejoin. Prices are converted from cents to dollar strings.

### MarketsChannel

```go
func MarketsChannel(f MarketsFilter) Channel
```

MarketsChannel sends "market\_created" and "market\_updated" for every market. Each message maps market id to a [MarketChange](/sdks/go/reference/types/#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.

### OrderbookChannel

```go
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.

### OrdersChannel

```go
func OrdersChannel(f OrdersFilter) Channel
```

OrdersChannel sends your open orders on join ("all\_orders", an [OrdersSnapshot](/sdks/go/reference/types/#orderssnapshot)), then each order whenever it changes ("new\_open\_order", an [Order](/sdks/go/reference/types/#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.

```go
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)
	}
}
```

### PositionsChannel

```go
func PositionsChannel(marketIDs_ ...string) Channel
```

PositionsChannel sends your positions on join ("all\_positions", a [PositionsSnapshot](/sdks/go/reference/types/#positionssnapshot)), then "updated\_positions" ([PositionsUpdate](/sdks/go/reference/types/#positionsupdate)) with only the positions that changed.

### SettlementsChannel

```go
func SettlementsChannel(marketIDs_ ...string) Channel
```

SettlementsChannel sends "new\_settlements" ([SettlementsUpdate](/sdks/go/reference/types/#settlementsupdate)) as they are recorded. There is no snapshot; read history over REST.

### TickerChannel

```go
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.

### TradesChannel

```go
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](/sdks/go/reference/websocket/#fillschannel).

### UserInfoChannel

```go
func UserInfoChannel() Channel
```

UserInfoChannel sends your profile right after joining, then on every change ("user\_updated", a [UserInfo](/sdks/go/reference/types/#userinfo)).

### Channel.Name

```go
func (c Channel) Name() string
```

Name returns the channel's name, for example "orderbook" or "orders".

## MarketFilter

```go
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.

## MarketsFilter

```go
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](/sdks/go/reference/websocket/#marketschannel).

## Message

```go
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.

### Message.Channel

```go
func (m Message) Channel() string
```

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

### Message.Decode

```go
func (m Message) Decode(v any) error
```

Decode decodes the payload into v.

## OrderSlip

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

OrderSlip costs orders before you place them, on order\_slip:&lt;user\_id&gt;. 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](/sdks/go/reference/websocket/#streamorderslip).

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/](https://docs.stxapp.io/websockets/channels/order-slip/).

### OrderSlip.Add

```go
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](/sdks/go/reference/websocket/#orderslipmessages) at once.

### OrderSlip.Close

```go
func (o *OrderSlip) Close() error
```

Close leaves the topic; every entry goes with it.

### OrderSlip.Done

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

Done is closed when the slip ends.

### OrderSlip.Err

```go
func (o *OrderSlip) Err() error
```

Err returns why the slip ended, like [Subscription.Err](/sdks/go/reference/websocket/#subscriptionerr).

### OrderSlip.Messages

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

Messages returns the channel the projections arrive on, with Data a \*[OrderNumbersBatch](/sdks/go/reference/types/#ordernumbersbatch) or a \*[SelfMatchBatch](/sdks/go/reference/types/#selfmatchbatch).

### OrderSlip.Remove

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

Remove unregisters an entry by its ref.

### OrderSlip.Topic

```go
func (o *OrderSlip) Topic() string
```

Topic returns the wire topic.

## OrderSlipEntry

```go
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.

## OrderSlipFill

```go
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.

## OrderSlipRef

```go
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.

## OrdersFilter

```go
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](/sdks/go/reference/websocket/#orderschannel).

## ReconnectPolicy

```go
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.

## StatsRange

```go
type StatsRange string
```

StatsRange is how far back a price series reaches.

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

The ranges [MarketStatsChannel](/sdks/go/reference/websocket/#marketstatschannel) and [Subscription.RequestSeries](/sdks/go/reference/websocket/#subscriptionrequestseries) take.

## StreamOption

```go
type StreamOption func(*streamConfig)
```

StreamOption configures a [Stream](/sdks/go/reference/websocket/#stream).

### WithBufferSize

```go
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.

### WithChannelPingInterval

```go
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.

### WithHeartbeatInterval

```go
func WithHeartbeatInterval(d time.Duration) StreamOption
```

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

### WithJoinTimeout

```go
func WithJoinTimeout(d time.Duration) StreamOption
```

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

### WithOnReconnect

```go
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.

### WithReconnectPolicy

```go
func WithReconnectPolicy(p ReconnectPolicy) StreamOption
```

WithReconnectPolicy sets the backoff between reconnect attempts.

### WithStreamLogger

```go
func WithStreamLogger(l *slog.Logger) StreamOption
```

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

### WithUserID

```go
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.

### WithoutReconnect

```go
func WithoutReconnect() StreamOption
```

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

## Subscription

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

Subscription is one joined topic on a [Stream](/sdks/go/reference/websocket/#stream).

### Subscription.Close

```go
func (sub *Subscription) Close() error
```

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

### Subscription.DecodeReply

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

DecodeReply decodes the latest join reply into v.

### Subscription.Done

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

Done is closed when the subscription ends.

### Subscription.Err

```go
func (sub *Subscription) Err() error
```

Err returns why the subscription ended: the context's error, the stream's error, or a \*[ChannelError](/sdks/go/reference/errors/#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.

### Subscription.Joined

```go
func (sub *Subscription) Joined() bool
```

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

### Subscription.Messages

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

Messages returns the channel messages arrive on. It is closed when the subscription ends; [Subscription.Err](/sdks/go/reference/websocket/#subscriptionerr) then says why.

### Subscription.Ping

```go
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.

### Subscription.Push

```go
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](/sdks/go/reference/errors/#channelerror).

### Subscription.Reply

```go
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:&lt;id&gt; (prices in dollar strings).

### Subscription.RequestSeries

```go
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.

### Subscription.RequestSnapshot

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

RequestSnapshot asks a market:&lt;id&gt; subscription to send the market's current "market\_update" and "order\_book\_update" again now.

### Subscription.SelectEventIDs

```go
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.

### Subscription.SelectFilters

```go
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.

### Subscription.SelectMarketIDs

```go
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.

### Subscription.SelectMessageTypes

```go
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.

### Subscription.SelectRuleFilters

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

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

### Subscription.Topic

```go
func (sub *Subscription) Topic() string
```

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

### Subscription.Watch

```go
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.

## TickerFilter

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

TickerFilter narrows [TickerChannel](/sdks/go/reference/websocket/#tickerchannel). Values match exactly, so "Football" and "football" differ.

## TradesFilter

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

TradesFilter narrows [TradesChannel](/sdks/go/reference/websocket/#tradeschannel).
