Describes github.com/stxapp/stx-go v0.3.1, the current release.
Constants and variables
Section titled “Constants and variables”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.
Client
Section titled “Client”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())Client.APIKey
Section titled “Client.APIKey”func (c *Client) APIKey() *APIKeyAPIKey returns the configured API key, or nil when the client uses another Auth or none.
Client.Auth
Section titled “Client.Auth”func (c *Client) Auth() AuthAuth returns what authenticates requests, or nil.
Client.BaseURL
Section titled “Client.BaseURL”func (c *Client) BaseURL() stringBaseURL returns the API base URL, such as “https://demo.stxapp.io”.
Client.Capabilities
Section titled “Client.Capabilities”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.
Client.HTTPClient
Section titled “Client.HTTPClient”func (c *Client) HTTPClient() *http.ClientHTTPClient returns the HTTP client in use.
Client.Host
Section titled “Client.Host”func (c *Client) Host() stringHost returns the exchange host, such as “demo.stxapp.io”: the name NotAvailableError reports.
Client.Logger
Section titled “Client.Logger”func (c *Client) Logger() *slog.LoggerLogger returns the client’s logger (a discarding one when none was set).
Client.Profile
Section titled “Client.Profile”func (c *Client) Profile() stringProfile returns the name of the credentials profile in use.
Client.SocketURL
Section titled “Client.SocketURL”func (c *Client) SocketURL() stringSocketURL returns the WebSocket URL.
Client.Stream
Section titled “Client.Stream”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) }}Client.SupportsFillMode
Section titled “Client.SupportsFillMode”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.
Client.UserAgent
Section titled “Client.UserAgent”func (c *Client) UserAgent() stringUserAgent returns the User-Agent header the client sends.
Environment
Section titled “Environment”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/.
EnvironmentNamed
Section titled “EnvironmentNamed”func EnvironmentNamed(name string) (Environment, error)EnvironmentNamed returns the environment called name, such as “us-demo”.
Environments
Section titled “Environments”func Environments() []EnvironmentEnvironments returns every published environment.
Option
Section titled “Option”type Option func(*options) errorOption configures a Client.
WithAuth
Section titled “WithAuth”func WithAuth(a Auth) OptionWithAuth authenticates with any Auth instead of an API key, such as an OAuth bearer token from the oauth package.
WithCredentialsFile
Section titled “WithCredentialsFile”func WithCredentialsFile(path string) OptionWithCredentialsFile reads profiles from path instead of ~/.stx/credentials.
WithEnvironment
Section titled “WithEnvironment”func WithEnvironment(e Environment) OptionWithEnvironment selects a published environment, such as USDemo. WithHost still wins over it.
WithEnvironmentName
Section titled “WithEnvironmentName”func WithEnvironmentName(name string) OptionWithEnvironmentName selects a published environment by name, such as “us-demo” or “ontario-production”.
WithHTTPClient
Section titled “WithHTTPClient”func WithHTTPClient(hc *http.Client) OptionWithHTTPClient 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).
WithHost
Section titled “WithHost”func WithHost(host string) OptionWithHost sets the API host: a hostname (“demo.stxapp.io”), which gets https, or a URL (“http://localhost:4000”) whose scheme is kept.
WithInsecureSkipVerify
Section titled “WithInsecureSkipVerify”func WithInsecureSkipVerify() OptionWithInsecureSkipVerify turns off TLS certificate checks. Use it only for a local server. It is ignored when WithHTTPClient is given.
WithKey
Section titled “WithKey”func WithKey(id, privateKey string) OptionWithKey sets the API key: its id and the Ed25519 private key as PKCS#8 PEM text or a path to a PEM file.
WithLogger
Section titled “WithLogger”func WithLogger(l *slog.Logger) OptionWithLogger logs requests, retries and stream events at debug level.
WithProfile
Section titled “WithProfile”func WithProfile(name string) OptionWithProfile 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())WithRegion
Section titled “WithRegion”func WithRegion(region, env string) OptionWithRegion selects the host by region (“us” or “ontario”) and env (“demo” or “production”; “prod” and “live” are accepted).
WithResponseHook
Section titled “WithResponseHook”func WithResponseHook(fn func(ResponseEvent)) OptionWithResponseHook calls fn once per HTTP attempt, after it completes or fails: an audit or activity log hook. A panic in fn is recovered.
WithRetry
Section titled “WithRetry”func WithRetry(p RetryPolicy) OptionWithRetry sets the retry policy; NoRetry turns retries off.
WithSigner
Section titled “WithSigner”func WithSigner(id string, signer crypto.Signer) OptionWithSigner sets the API key id and a crypto.Signer producing pure Ed25519 signatures, for keys held in an HSM or a cloud KMS.
WithTimeout
Section titled “WithTimeout”func WithTimeout(d time.Duration) OptionWithTimeout sets the time limit for each HTTP attempt. Default 30 s.
WithUserAgent
Section titled “WithUserAgent”func WithUserAgent(product string) OptionWithUserAgent appends product to the User-Agent header, for example “my-app/1.2”.
ResponseEvent
Section titled “ResponseEvent”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.
RetryPolicy
Section titled “RetryPolicy”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.

