Skip to content

Client

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

const DefaultProfile = "default"

DefaultProfile is the profile read when none is named.

const Version = "0.3.1"

Version is the SDK version.

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. API keys do not carry across exchanges: an Ontario key does not authenticate in the United States.

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.

var NoRetry = RetryPolicy{MaxAttempts: 1}

NoRetry tries every call once.

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; it is safe for concurrent use and should be reused.

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.

Example

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

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())
func (c *Client) APIKey() *APIKey

APIKey returns the configured API key, or nil when the client uses another Auth or none.

func (c *Client) Auth() Auth

Auth returns what authenticates requests, or nil.

func (c *Client) BaseURL() string

BaseURL returns the API base URL, such as “https://demo.stxapp.io”.

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.

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

HTTPClient returns the HTTP client in use.

func (c *Client) Host() string

Host returns the exchange host, such as “demo.stxapp.io”: the name NotAvailableError reports.

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

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

func (c *Client) Profile() string

Profile returns the name of the credentials profile in use.

func (c *Client) SocketURL() string

SocketURL returns the WebSocket URL.

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.

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.

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)
}
}
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. An exchange on a release from before fill modes may instead place the order as a normal limit order; check Order.FillMode on the placed order. mode and refresh are ignored.

func (c *Client) UserAgent() string

UserAgent returns the User-Agent header the client sends.

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/.

func EnvironmentNamed(name string) (Environment, error)

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

func Environments() []Environment

Environments returns every published environment.

type Option func(*options) error

Option configures a Client.

func WithAuth(a Auth) Option

WithAuth authenticates with any Auth instead of an API key, such as an OAuth bearer token from the oauth package.

func WithCredentialsFile(path string) Option

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

func WithEnvironment(e Environment) Option

WithEnvironment selects a published environment, such as USDemo. WithHost still wins over it.

func WithEnvironmentName(name string) Option

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

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

func WithHost(host string) Option

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

func WithInsecureSkipVerify() Option

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

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.

func WithLogger(l *slog.Logger) Option

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

func WithProfile(name string) Option

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

Example

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

client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
fmt.Println(client.Host())
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).

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.

func WithRetry(p RetryPolicy) Option

WithRetry sets the retry policy; NoRetry turns retries off.

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

WithSigner sets the API key id and a crypto.Signer producing pure Ed25519 signatures, for keys held in an HSM or a cloud KMS.

func WithTimeout(d time.Duration) Option

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

func WithUserAgent(product string) Option

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

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.

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

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