Describes github.com/stxapp/stx-go v0.3.1, the current release.
The github.com/stxapp/stx-go/oauth package runs the OAuth flows for an app registered with STX: it creates the PKCE verifier and state, exchanges the code, refreshes and rotates tokens, and revokes them. How the flow works, what each scope allows and how to handle tokens safely are covered in OAuth and Build an app; this page shows the SDK calls. Where the exchange does not offer OAuth yet, the calls return an error matching stx.ErrNotAvailable; see What you can do.
Start from where you are
Section titled “Start from where you are”Pick the guide that matches your app; each runs end to end with this package.
| Your situation | Guide | With this package | Example |
|---|---|---|---|
| You have an app with its own accounts | Connect your STX account | Begin and Complete to link, a TokenStore keyed on your user id, MemberClient to act, Unlink (this page) |
connect-account |
| You’re building a new app with no login yet | Sign in with your STX account | oauth.NewSignIn: Start, Finish (verified ID token), UserInfo (Sign in with STX) |
sign-in-with-stx |
| You use a login service like Auth0 or Clerk | Login services | Keep your login and link STX accounts as in the first row, or act for members with the STX tokens the service passes on (Sign in with STX) | login-service |
Create one *oauth.Client per registered app, on your server:
app, err := oauth.New(oauth.Config{ BaseURL: "demo.stxapp.io", ClientID: "stxapp_client_9f2c41d7", ClientSecret: os.Getenv("STX_OAUTH_CLIENT_SECRET"), RedirectURL: "https://sideline.example.com/stx/callback", Scopes: []string{oauth.ScopeBalanceRead, oauth.ScopePortfolioRead, oauth.ScopeOrdersWrite},})if err != nil { log.Fatal(err)}oauth.Discover does the same after reading the exchange’s discovery document, so a scope the exchange does not offer is reported as stx.ErrNotAvailable. oauth.ConfigFromEnv reads the settings from STX_HOST, STX_OAUTH_CLIENT_ID, STX_OAUTH_CLIENT_SECRET, STX_OAUTH_REDIRECT_URI and STX_OAUTH_SCOPE.
Connect a member’s account
Section titled “Connect a member’s account”Begin on your connect route sends the member to STX; Complete on your callback checks state, exchanges the code and stores the tokens. The pending store holds the verifier between the two, and the token store keeps each member’s tokens under your own key for them.
pending := &oauth.MemoryPendingStore{}tokens := oauth.NewFileTokenStore("/var/lib/sideline/stx-tokens.json")
http.HandleFunc("/stx/connect", func(w http.ResponseWriter, r *http.Request) { auth, err := app.Begin(r.Context(), pending, oauth.BeginParams{Data: map[string]string{"user": "u_1842"}}) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } http.Redirect(w, r, auth.URL, http.StatusFound)})
http.HandleFunc("/stx/callback", func(w http.ResponseWriter, r *http.Request) { done, err := app.Complete(r.Context(), pending, r.URL.Query(), oauth.RedeemOptions{ Store: tokens, MemberKeyFunc: func(data map[string]string) string { return data["user"] }, }) switch { case errors.Is(err, oauth.ErrAccessDenied): fmt.Fprint(w, "Not connected.") case errors.Is(err, oauth.ErrAccountPending): fmt.Fprint(w, "Your STX account is still being verified.") case err != nil: http.Error(w, err.Error(), http.StatusBadRequest) default: fmt.Fprintf(w, "Connected with %v.", done.Scopes) }})done.Scopes are the scopes the member granted, which can be fewer than you asked for. MemoryPendingStore and MemoryTokenStore suit one process; for several, implement oauth.PendingStore and oauth.TokenStore on your database, and give the token store an oauth.Locker so concurrent refreshes happen once.
Act for a member
Section titled “Act for a member”MemberClient returns an ordinary *stx.Client that acts for one connected member. Every call carries their access token, refreshed before it expires and once on a 401, with the rotated refresh token stored each time. WebSocket connections send the token too.
member, err := app.MemberClient(tokens, "u_1842", nil)if err != nil { log.Fatal(err)}balance, err := member.Account.Balance(ctx)if err != nil { log.Fatal(err)}fmt.Println(balance.AvailableBalance) // 746.8600A call the grant does not cover returns an error matching stx.ErrInsufficientScope, with the scopes it needs in APIError.RequiredScopes. When the member revokes access at STX, the next refresh deletes their stored tokens and returns an error matching oauth.ErrGrantRevoked: send them through Begin again. A write from an address the app’s IP allow-list lacks returns stx.ErrIPNotAllowed.
When STX has new terms for the member
Section titled “When STX has new terms for the member”A call can return an error matching stx.ErrTermsRequired when the member has new STX terms to accept. Send them to APIError.TermsURL, with a way back to your app:
_, err := member.Orders.Place(ctx, stx.OrderRequest{ MarketID: marketID, Action: stx.Buy, OrderType: stx.Limit, Price: stx.MustDecimal("0.01"), Quantity: stx.MustDecimal("1"),})var apiErr *stx.APIErrorif errors.Is(err, stx.ErrTermsRequired) && errors.As(err, &apiErr) { fmt.Println(oauth.TermsURLWithReturn(apiErr.TermsURL, "https://sideline.example.com/account"))}oauth.SessionOptions.OnTermsRequired tells you the same after a token refresh, before any call fails.
Disconnect
Section titled “Disconnect”confirmed, err := app.Unlink(ctx, tokens, "u_1842")if err != nil { log.Fatal(err)}fmt.Println("revoked at STX:", confirmed)Unlink revokes the grant at STX and deletes the member’s tokens from your store; the local tokens are deleted even when STX cannot be reached.
Act as your app
Section titled “Act as your app”An app token (the client credentials grant) calls the routes that belong to your app rather than a member: the market and event catalogs, the market data channels, and creating markets. AppClient returns an *stx.Client that fetches the token and renews it before it expires:
appClient, err := app.AppClient([]string{oauth.ScopeMarketData, oauth.ScopeEvents})if err != nil { log.Fatal(err)}page, err := appClient.Markets.List(ctx, &stx.MarketsQuery{Status: []string{"open"}, Limit: 5})if err != nil { log.Fatal(err)}for _, m := range page.Items { fmt.Println(m.Symbol, m.LastTradedPrice)}// STXNHL-26OCT101600EDMSJ-GAMEEDM 0.5800app.AppToken(scopes...) is the same token as an stx.Auth for stx.WithAuth, and app.ClientCredentials returns the raw token. A public client (no secret) cannot get an app token. Which scopes an app can hold is listed under App scopes.
Register a client
Section titled “Register a client”Where the exchange offers dynamic client registration, oauth.Register registers a client without a trip to the STX Apps console. The registration does nothing until a member consents:
reg, err := oauth.Register(ctx, "demo.stxapp.io", oauth.ClientRegistrationRequest{ ClientName: "Sideline", RedirectURIs: []string{"https://sideline.example.com/stx/callback"},}, nil)if err != nil { log.Fatal(err)}fmt.Println(reg.ClientID)Errors
Section titled “Errors”Errors from the OAuth endpoints are *oauth.Error values with the RFC Code (such as invalid_grant), Description, and STX’s narrower Reason. They match the package’s sentinels: oauth.ErrAccessDenied (the member said no), oauth.ErrAccountPending (their STX account is still being verified), oauth.ErrTermsNotAccepted, oauth.ErrGrantRevoked, oauth.ErrInvalidState and oauth.ErrNotConnected (no tokens stored for that member). See Discovery and errors.

