# WebSockets

> Stream market data and your account over one socket.

Source: https://docs.stxapp.io/sdks/go/websockets/

The client streams the channels documented under [WebSockets](/websockets/): what each channel sends, its payloads and its limits are covered there. This page shows the SDK calls.

## Open a stream and subscribe

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os/signal"
	"syscall"

	stx "github.com/stxapp/stx-go"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	client, err := stx.New()
	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.TickerChannel(stx.TickerFilter{Sports: []string{"Hockey"}}))
	if err != nil {
		log.Fatal(err)
	}
	for msg := range sub.Messages() {
		if t, ok := msg.Data.(*stx.Ticker); ok {
			fmt.Println(t.MarketSymbol, "bid", t.BestBid, "offer", t.BestOffer, "last", t.LastTradedPrice)
			// STXNHL-26OCT101600EDMSJ-GAMEEDM bid 0.5800 offer 0.6100 last 0.5800
		}
	}
	if err := sub.Err(); err != nil && ctx.Err() == nil {
		log.Fatal(err)
	}
}
```

`client.Stream` is one WebSocket connection to the client's host, signed with the client's key; every `Subscribe` on it joins one channel and returns a `*stx.Subscription`. A `Stream` is safe for concurrent use, so one connection can carry every channel your program needs. A client with no API key connects unsigned: the market data channels accept that, and the account channels refuse the join.

## Receive messages

Each `stx.Message` has `Topic`, `Event`, the raw JSON `Payload`, and `Data`, the payload decoded into the SDK's type for that event (`*stx.OrderbookUpdate` for a book, `*stx.Order` for a new order, and so on; nil for an event the SDK does not know). `Snapshot` is true for the state an account channel sends on join and again after every rejoin: replace what you hold rather than merging. `msg.Decode(&v)` decodes the payload into your own type.

`sub.Messages()` is closed when `ctx` is done, when you call `sub.Close()` or `stream.Close()`, or when the channel fails for good; `sub.Err()` then says why.

```go
stream, err := client.Stream(ctx)
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

sub, err := stream.Subscribe(ctx, stx.OrderbookChannel(marketID))
if err != nil {
	log.Fatal(err)
}
for msg := range sub.Messages() {
	book, ok := msg.Data.(*stx.OrderbookUpdate)
	if !ok || len(book.Bids) == 0 {
		continue
	}
	fmt.Println(book.MarketID, book.Bids[0].Price, book.Bids[0].Quantity)
	// e00651a3-10cb-4bc1-9e1f-c5ea1796c83b 0.5800 210.00
}
```

Money fields are dollar decimal strings on every channel, including the ones that send cents on the wire.

## Channels

| SDK call | Channel |
|---|---|
| `stx.OrderbookChannel(marketIDs...)` | [Order book, ticker and trades](/websockets/channels/market-data/) |
| `stx.TickerChannel(stx.TickerFilter{Sports, Competitions})` | [Order book, ticker and trades](/websockets/channels/market-data/) |
| `stx.TradesChannel(stx.TradesFilter{MarketIDs, EventIDs})` | [Order book, ticker and trades](/websockets/channels/market-data/) |
| `stx.MarketChannel(marketIDOrSymbol)` | [Market order book](/websockets/order-book/) |
| `stx.MarketsChannel(stx.MarketsFilter{RuleFilters, MessageTypes})` | [Markets](/websockets/channels/markets/) |
| `stx.MarketStatsChannel(stx.StatsDay, marketIDs...)` | [Market stats](/websockets/channels/market-stats/) |
| `stx.MarketUpdatesChannel(marketIDs...)` | [Market updates](/websockets/channels/market-updates/) |
| `stx.EventsChannel(eventIDs...)` | [Events](/websockets/channels/events/) |
| `stx.OrdersChannel(stx.OrdersFilter{MarketIDs, CancelOnDisconnect, PingTimeout})` | [Orders](/websockets/channels/orders/) |
| `stx.FillsChannel(marketIDs...)` | [Fills](/websockets/channels/fills/) |
| `stx.PositionsChannel(marketIDs...)` | [Positions](/websockets/channels/positions/) |
| `stx.SettlementsChannel(marketIDs...)` | [Settlements](/websockets/channels/settlements/) |
| `stx.BalancesChannel(accountID)` | [Balances](/websockets/channels/balances/) |
| `stx.AccountChannel(marketIDs...)` | [Account](/websockets/channels/account/) |
| `stx.UserInfoChannel()` | [User info](/websockets/channels/user-info/) |

The account channels find your user id for you. To change filters after joining, call `sub.SelectMarketIDs`, `SelectEventIDs`, `SelectFilters`, `SelectRuleFilters` or `SelectMessageTypes`; on market updates, `sub.Watch`. The stream remembers the new filters for the next rejoin. Combos have their own calls; see [Combos](/sdks/go/combos/).

## Live account view

`stream.AccountView` keeps your balance, open orders, fills and positions current. It subscribes to 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 the four snapshots are in.

```go
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)
}
state := view.Snapshot()
fmt.Println(state.Balance.AvailableBalance, len(state.OpenOrders), len(state.Fills), len(state.Positions))
// 746.8600 1 1 1

for change := range view.Changes() {
	state := view.Snapshot() // a copy, safe to keep
	fmt.Println(change.Kind, change.Event, "available", state.Balance.AvailableBalance)
	// orders new_open_order available 746.8500
}
```

No refetch is needed after you place or cancel an order: the change arrives on the socket. `AccountViewOptions` takes `MarketIDs`, `AccountID`, `KeepFlatPositions`, `MaxFills` (default 1000) and `SnapshotTimeout` (default 15 s). The view marshals to JSON, so you can hand `view` straight to `json.NewEncoder(w).Encode`.

## Cancel-on-disconnect

Arm cancel-on-disconnect on the orders channel, then send `CancelOnDisconnect: stx.Bool(true)` on each order that should be canceled if your process loses the exchange. While the orders channel is joined, the stream pings it at a third of the granted timeout, so two pings can be lost before the exchange cancels your orders. How it works on the exchange is described in [Risk controls](/risk-controls/#cancel-orders-on-disconnect); placing orders with it is on [Trading](/sdks/go/trading#cancel-on-disconnect).

```go
orders, err := stream.Subscribe(ctx, stx.OrdersChannel(stx.OrdersFilter{CancelOnDisconnect: true, PingTimeout: 5 * time.Second}))
```

## Reconnects

The stream sends the heartbeat and channel pings for you. After a drop it reconnects with backoff, signs again, and rejoins every subscription with its current filters; your `range` over `sub.Messages()` simply continues. If the exchange closes one channel while the socket stays up, the stream rejoins it the same way. It cannot know what you missed while offline, so reload anything you read with a client method (open orders, history) in the reconnect hook:

```go
stream, err := client.Stream(ctx,
	stx.WithReconnectPolicy(stx.ReconnectPolicy{InitialBackoff: 500 * time.Millisecond, MaxBackoff: 30 * time.Second, MaxAttempts: 20}),
	stx.WithOnReconnect(func() {
		page, err := client.Orders.List(ctx, &stx.OrdersQuery{Status: []string{"created", "requested", "accepted", "delayed", "open"}})
		if err == nil {
			fmt.Println("reconnected, open orders:", len(page.Items)) // reconnected, open orders: 1
		}
	}),
	stx.WithStreamLogger(slog.Default()),
)
```

`stx.WithoutReconnect()` turns reconnecting off. `stream.Connected()`, `stream.Reconnects()` and `stream.ChannelRejoins()` report the socket's state. [After a reconnect](/websockets/#after-a-reconnect) explains what the exchange does and does not replay.

## Errors

A refused join returns a `*stx.ChannelError` with the exchange's reason, matching `stx.ErrChannelRefused`. No reply within the join timeout (`stx.WithJoinTimeout`, default 10 s) returns an error matching `stx.ErrTimeout`, and a call on a closed stream `stx.ErrStreamClosed`.

```go
_, err := stream.Subscribe(ctx, stx.OrdersChannel(stx.OrdersFilter{}))
var chErr *stx.ChannelError
if errors.As(err, &chErr) {
	fmt.Println(chErr.Topic, chErr.Reason)
	// orders:e6528824-b4e0-4ff8-bd70-36e5904738d1 unauthorized
}
```
