# Client

> Creating a client, its options, environments and retries.

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

## Constants and variables

```go
const DefaultProfile = "default"
```

DefaultProfile is the profile read when none is named.

```go
const Version = "0.3.1"
```

Version is the SDK version.

```go
var (
	// USDemo is the United States demo, shared by every integrator. No real money.
	USDemo = Environment{Name: "us-demo", Region: "us", Env: "demo", Host: "demo.stxapp.io"}
	// OntarioDemo is the Ontario demo, shared. No real money.
	OntarioDemo = Environment{Name: "ontario-demo", Region: "ontario", Env: "demo", Host: "demo.stxapp.ca"}
	// OntarioProduction is Ontario production. Real money: exercise your
	// integration against OntarioDemo first.
	OntarioProduction = Environment{Name: "ontario-production", Region: "ontario", Env: "production", Host: "api.on.stxapp.ca", RealMoney: true}
)
```

The published environments. Any other host (a local server, a host added after this version shipped) is reachable with [WithHost](/sdks/go/reference/client/#withhost). API keys do not carry across exchanges: an Ontario key does not authenticate in the United States.

```go
var DefaultRetryPolicy = RetryPolicy{MaxAttempts: 3, InitialBackoff: 500 * time.Millisecond, MaxBackoff: 30 * time.Second}
```

DefaultRetryPolicy is 3 attempts, 500 ms initial backoff doubling to a 30 s cap, with jitter.

```go
var NoRetry = RetryPolicy{MaxAttempts: 1}
```

NoRetry tries every call once.

## Client

```go
type Client struct {
	// Account: identity, balance, positions, profile and terms.
	Account *AccountService
	// Markets: listing markets, market types and creating markets.
	Markets *MarketsService
	// Events: listing events and their players.
	Events *EventsService
	// Orders: placing, listing and cancelling orders.
	Orders *OrdersService
	// Portfolio: fills, settlements, per-market stats and money movements.
	Portfolio *PortfolioService
	// Leaderboard: public rankings and your own standing.
	Leaderboard *LeaderboardService
	// Combos: combo requests for quote and quotes.
	Combos *CombosService
	// contains filtered or unexported fields
}
```

Client calls the STX API. Create one with [New](/sdks/go/reference/client/#new); it is safe for concurrent use and should be reused.

### New

```go
func New(opts ...Option) (*Client, error)
```

New returns a client configured from opts, then environment variables, then a profile in ~/.stx/credentials. A client without credentials is allowed (the public market data channels accept an unsigned socket), but REST calls then fail with [ErrConfig](/sdks/go/reference/errors/#constants-and-variables).

**Example**

A client for the United States demo, with an API key from a PEM file.

```go
client, err := stx.New(
	stx.WithEnvironment(stx.USDemo),
	stx.WithKey("3f1c9a52-7d4e-4b8a-9c21-5e6f7a8b9c0d", "~/.stx/us-demo.pem"),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(client.BaseURL())
```

### Client.APIKey

```go
func (c *Client) APIKey() *APIKey
```

APIKey returns the configured API key, or nil when the client uses another [Auth](/sdks/go/reference/auth/#auth) or none.

### Client.Auth

```go
func (c *Client) Auth() Auth
```

Auth returns what authenticates requests, or nil.

### Client.BaseURL

```go
func (c *Client) BaseURL() string
```

BaseURL returns the API base URL, such as "[https://demo.stxapp.io](https://demo.stxapp.io)".

### Client.Capabilities

```go
func (c *Client) Capabilities(ctx context.Context, refresh bool) (*Capabilities, error)
```

Capabilities reports which features this exchange has, from what it publishes: its OAuth discovery document, /api\_version, GETs (signed when the client has credentials) of the routes not every exchange has yet, and a join of a combos topic nobody owns. Nothing is created or changed. The answer is cached per client; pass refresh to check again.

A missing feature never fails here; the call that needs it returns an error matching [ErrNotAvailable](/sdks/go/reference/errors/#constants-and-variables).

### Client.HTTPClient

```go
func (c *Client) HTTPClient() *http.Client
```

HTTPClient returns the HTTP client in use.

### Client.Host

```go
func (c *Client) Host() string
```

Host returns the exchange host, such as "demo.stxapp.io": the name [NotAvailableError](/sdks/go/reference/errors/#notavailableerror) reports.

### Client.Logger

```go
func (c *Client) Logger() *slog.Logger
```

Logger returns the client's logger (a discarding one when none was set).

### Client.Profile

```go
func (c *Client) Profile() string
```

Profile returns the name of the credentials profile in use.

### Client.SocketURL

```go
func (c *Client) SocketURL() string
```

SocketURL returns the WebSocket URL.

### Client.Stream

```go
func (c *Client) Stream(ctx context.Context, opts ...StreamOption) (*Stream, error)
```

Stream opens a WebSocket stream to the exchange: one connection that carries every topic you subscribe to. The handshake is signed with the client's credentials when they can sign it; without credentials the stream carries the market data channels only. A refused handshake returns a \*[HandshakeError](/sdks/go/reference/errors/#handshakeerror).

ctx bounds the first connect only; the stream runs until you Close it.

**Example**

Stream the book of one market and print the best bid.

```go
ctx := context.Background()
client, err := stx.New(stx.WithEnvironment(stx.USDemo))
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.OrderbookChannel("e00651a3-10cb-4bc1-9e1f-c5ea1796c83b"))
if err != nil {
	log.Fatal(err)
}
for msg := range sub.Messages() {
	if book, ok := msg.Data.(*stx.OrderbookUpdate); ok && len(book.Bids) > 0 {
		fmt.Println(book.MarketID, book.Bids[0].Price)
	}
}
```

### Client.SupportsFillMode

```go
func (c *Client) SupportsFillMode(ctx context.Context, mode string, refresh bool) (bool, error)
```

SupportsFillMode no longer checks anything and always returns true and a nil error, without a request.

Deprecated: the exchange no longer publishes which fill modes it takes. Send the order with the mode and handle the answer: where the mode is not enabled the exchange rejects the order and the call returns an error matching [ErrNotAvailable](/sdks/go/reference/errors/#constants-and-variables). An exchange on a release from before fill modes may instead place the order as a normal limit order; check [Order.FillMode](/sdks/go/reference/types/#order) on the placed order. mode and refresh are ignored.

### Client.UserAgent

```go
func (c *Client) UserAgent() string
```

UserAgent returns the User-Agent header the client sends.

## Environment

```go
type Environment struct {
	// Name is a short name for logs and configuration, such as "ontario-demo".
	Name string
	// Region is "us" or "ontario".
	Region string
	// Env is "demo" or "production".
	Env string
	// Host is the API hostname.
	Host string
	// RealMoney is true where orders settle against live balances.
	RealMoney bool
}
```

Environment is a published STX environment. The list lives at [https://docs.stxapp.io/environments/](https://docs.stxapp.io/environments/).

### EnvironmentNamed

```go
func EnvironmentNamed(name string) (Environment, error)
```

EnvironmentNamed returns the environment called name, such as "us-demo".

### Environments

```go
func Environments() []Environment
```

Environments returns every published environment.

## Option

```go
type Option func(*options) error
```

Option configures a [Client](/sdks/go/reference/client/#client).

### WithAuth

```go
func WithAuth(a Auth) Option
```

WithAuth authenticates with any [Auth](/sdks/go/reference/auth/#auth) instead of an API key, such as an OAuth bearer token from the oauth package.

### WithCredentialsFile

```go
func WithCredentialsFile(path string) Option
```

WithCredentialsFile reads profiles from path instead of ~/.stx/credentials.

### WithEnvironment

```go
func WithEnvironment(e Environment) Option
```

WithEnvironment selects a published environment, such as [USDemo](/sdks/go/reference/client/#constants-and-variables). [WithHost](/sdks/go/reference/client/#withhost) still wins over it.

### WithEnvironmentName

```go
func WithEnvironmentName(name string) Option
```

WithEnvironmentName selects a published environment by name, such as "us-demo" or "ontario-production".

### WithHTTPClient

```go
func WithHTTPClient(hc *http.Client) Option
```

WithHTTPClient sets the HTTP client, for proxies, custom TLS or tests. The default is a client with sensible connection pooling and no overall timeout (each request has its own, see [WithTimeout](/sdks/go/reference/client/#withtimeout)).

### WithHost

```go
func WithHost(host string) Option
```

WithHost sets the API host: a hostname ("demo.stxapp.io"), which gets https, or a URL ("[http://localhost:4000](http://localhost:4000)") whose scheme is kept.

### WithInsecureSkipVerify

```go
func WithInsecureSkipVerify() Option
```

WithInsecureSkipVerify turns off TLS certificate checks. Use it only for a local server. It is ignored when WithHTTPClient is given.

### WithKey

```go
func WithKey(id, privateKey string) Option
```

WithKey sets the API key: its id and the Ed25519 private key as PKCS#8 PEM text or a path to a PEM file.

### WithLogger

```go
func WithLogger(l *slog.Logger) Option
```

WithLogger logs requests, retries and stream events at debug level.

### WithProfile

```go
func WithProfile(name string) Option
```

WithProfile reads the named section of ~/.stx/credentials.

**Example**

A client from the "us-demo" section of ~/.stx/credentials.

```go
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
	log.Fatal(err)
}
fmt.Println(client.Host())
```

### WithRegion

```go
func WithRegion(region, env string) Option
```

WithRegion selects the host by region ("us" or "ontario") and env ("demo" or "production"; "prod" and "live" are accepted).

### WithResponseHook

```go
func WithResponseHook(fn func(ResponseEvent)) Option
```

WithResponseHook calls fn once per HTTP attempt, after it completes or fails: an audit or activity log hook. A panic in fn is recovered.

### WithRetry

```go
func WithRetry(p RetryPolicy) Option
```

WithRetry sets the retry policy; [NoRetry](/sdks/go/reference/client/#constants-and-variables) turns retries off.

### WithSigner

```go
func WithSigner(id string, signer crypto.Signer) Option
```

WithSigner sets the API key id and a [crypto.Signer](https://pkg.go.dev/crypto#Signer) producing pure Ed25519 signatures, for keys held in an HSM or a cloud KMS.

### WithTimeout

```go
func WithTimeout(d time.Duration) Option
```

WithTimeout sets the time limit for each HTTP attempt. Default 30 s.

### WithUserAgent

```go
func WithUserAgent(product string) Option
```

WithUserAgent appends product to the User-Agent header, for example "my-app/1.2".

## ResponseEvent

```go
type ResponseEvent struct {
	// OperationID is the spec's operation id, such as "orders_post".
	OperationID string
	Method      string
	// Path includes the query string, as sent.
	Path string
	// StatusCode is the HTTP status, or 0 when no response arrived.
	StatusCode int
	// Attempt is 1 for the first try, higher after a retry or a token refresh.
	Attempt  int
	Duration time.Duration
	// AuthKind is the [Auth] kind, such as "api_key".
	AuthKind string
	// RequestBody and ResponseBody are passed through unredacted. They can
	// carry order details, balances and account data: redact before storing
	// or displaying them.
	RequestBody  []byte
	ResponseBody []byte
	// Err is the error this attempt ended with, if any.
	Err error
}
```

ResponseEvent describes one HTTP attempt, for [WithResponseHook](/sdks/go/reference/client/#withresponsehook).

## RetryPolicy

```go
type RetryPolicy struct {
	// MaxAttempts is the total number of tries, including the first. Values
	// below 1 mean 1.
	MaxAttempts int
	// InitialBackoff is the wait before the first retry.
	InitialBackoff time.Duration
	// MaxBackoff caps any one backoff. A Retry-After longer than this is not
	// waited out: the 429 is returned instead.
	MaxBackoff time.Duration
	// NoJitter turns off the randomization of each wait (between 50% and
	// 100% of its value).
	NoJitter bool
}
```

RetryPolicy decides how often a REST call is tried and how long to wait between tries.

A 429 is retried on every method: the server refused the request before acting on it. A 5xx or a transport failure is retried on GET and DELETE only. POST and PATCH are never repeated after a 5xx or a dropped connection, because the order may already be on the book; set OrderRequest.ClientOrderID and look the order up instead. Nothing else is retried: a 403, including one from the edge firewall ([ErrBlocked](/sdks/go/reference/errors/#constants-and-variables)), fails the same way the second time. Backoff is exponential with jitter, capped at MaxBackoff. A Retry-After header on a 429 sets the wait in full; when it asks for longer than MaxBackoff, the call is not retried and the error, with APIError.RetryAfter, is returned rather than retrying before the rate-limit window ends.
