Documentation
¶
Overview ¶
Package stx is a Go client for the STX exchange API.
It calls the documented REST API with signed requests and streams the WebSocket channels. Every method takes a context.Context first, returns errors instead of panicking, and is safe for concurrent use.
Create a client from a profile in ~/.stx/credentials, environment variables, or options:
client, err := stx.New(stx.WithEnvironment(stx.USDemo), stx.WithKey("my-key-id", "~/.stx/us-demo.pem"))
if err != nil {
log.Fatal(err)
}
page, err := client.Markets.List(ctx, &stx.MarketsQuery{Status: []string{"open"}, Limit: 10})
Money and quantities are Decimal values, exact decimal strings such as "0.5600", never float64.
Errors from the API are *APIError values; match them with errors.As, or with errors.Is against sentinels such as ErrNotFound, ErrRateLimited and ErrNotAvailable.
Authentication, environments, rate limits and error codes are described at https://docs.stxapp.io.
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func Features() []string
- func IsValidLine(line float64) bool
- func KnownStats() map[string][]string
- func LoadPrivateKey(value string) (ed25519.PrivateKey, error)
- func ParsePrivateKeyPEM(data []byte) (ed25519.PrivateKey, error)
- func SigningMessage(timestampMs int64, method, path string) string
- type APIError
- type APIKey
- func (k *APIKey) AuthHeaders(_ context.Context, method, path string) (http.Header, error)
- func (k APIKey) GoString() string
- func (k *APIKey) ID() string
- func (k *APIKey) Kind() string
- func (k *APIKey) Sign(message []byte) ([]byte, error)
- func (k *APIKey) SignedHeaders(method, path string, at time.Time) (http.Header, error)
- func (k APIKey) String() string
- func (k *APIKey) WebSocketHeaders(_ context.Context, _ bool) (http.Header, error)
- type AcceptTermsOptions
- type AccountChange
- type AccountChangeKind
- type AccountService
- func (s *AccountService) AcceptTerms(ctx context.Context, deviceID string, opts *AcceptTermsOptions) (string, error)
- func (s *AccountService) Balance(ctx context.Context) (*Balance, error)
- func (s *AccountService) Me(ctx context.Context) (*Me, error)
- func (s *AccountService) Positions(ctx context.Context, q *PositionsQuery) ([]Position, error)
- func (s *AccountService) UpdateProfile(ctx context.Context, update ProfileUpdate) (*Me, error)
- func (s *AccountService) UserID(ctx context.Context) (string, error)
- type AccountState
- type AccountView
- func (v *AccountView) Changes() <-chan AccountChange
- func (v *AccountView) Close() error
- func (v *AccountView) Done() <-chan struct{}
- func (v *AccountView) Err() error
- func (v *AccountView) MarshalJSON() ([]byte, error)
- func (v *AccountView) Ready() bool
- func (v *AccountView) Snapshot() AccountState
- type AccountViewOptions
- type Auth
- type Balance
- type BatchOrderResult
- type BookLevel
- type Cancellation
- type Capabilities
- type Channel
- func AccountChannel(marketIDs_ ...string) Channel
- func BalancesChannel(accountID string) Channel
- func EventsChannel(eventIDs ...string) Channel
- func FillsChannel(marketIDs_ ...string) Channel
- func MarketChannel(marketIDOrSymbol string) Channel
- func MarketStatsChannel(r StatsRange, marketIDs ...string) Channel
- func MarketUpdatesChannel(watch ...string) Channel
- func MarketsChannel(f MarketsFilter) Channel
- func OrderbookChannel(marketIDs ...string) Channel
- func OrdersChannel(f OrdersFilter) Channel
- func PositionsChannel(marketIDs_ ...string) Channel
- func SettlementsChannel(marketIDs_ ...string) Channel
- func TickerChannel(f TickerFilter) Channel
- func TradesChannel(f TradesFilter) Channel
- func UserInfoChannel() Channel
- type ChannelError
- type Client
- func (c *Client) APIKey() *APIKey
- func (c *Client) Auth() Auth
- func (c *Client) BaseURL() string
- func (c *Client) Capabilities(ctx context.Context, refresh bool) (*Capabilities, error)
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) Host() string
- func (c *Client) Logger() *slog.Logger
- func (c *Client) Profile() string
- func (c *Client) SocketURL() string
- func (c *Client) Stream(ctx context.Context, opts ...StreamOption) (*Stream, error)
- func (c *Client) SupportsFillMode(ctx context.Context, mode string, refresh bool) (bool, error)deprecated
- func (c *Client) UserAgent() string
- type ComboBestQuote
- type ComboBestQuoteEvent
- type ComboCashOut
- type ComboEvent
- type ComboLeg
- type ComboMaker
- func (m *ComboMaker) Close() error
- func (m *ComboMaker) Done() <-chan struct{}
- func (m *ComboMaker) Err() error
- func (m *ComboMaker) Events() <-chan ComboEvent
- func (m *ComboMaker) ExternalID() string
- func (m *ComboMaker) History() []ComboEvent
- func (m *ComboMaker) Quote(ctx context.Context, q ComboQuoteRequest) (ComboQuote, error)
- func (m *ComboMaker) Topic() string
- func (m *ComboMaker) WaitFor(ctx context.Context, w ComboWait) (ComboEvent, error)
- func (m *ComboMaker) WithdrawQuote(ctx context.Context, rfqID, quoteID string) error
- type ComboMakerPlacedEvent
- type ComboOutcome
- type ComboPlacedEvent
- type ComboPlacement
- type ComboPlayer
- func (p *ComboPlayer) Accept(ctx context.Context, rfqID, quoteID string, amount Decimal) (ComboPlacement, error)
- func (p *ComboPlayer) Cancel(ctx context.Context, rfqID string) error
- func (p *ComboPlayer) CashOut(ctx context.Context, marketID string) (ComboCashOut, error)
- func (p *ComboPlayer) Close() error
- func (p *ComboPlayer) Done() <-chan struct{}
- func (p *ComboPlayer) Err() error
- func (p *ComboPlayer) Events() <-chan ComboEvent
- func (p *ComboPlayer) ExternalID() string
- func (p *ComboPlayer) History() []ComboEvent
- func (p *ComboPlayer) RequestQuote(ctx context.Context, legs []ComboLeg, amount Decimal) (ComboRequest, error)
- func (p *ComboPlayer) Snapshot(ctx context.Context, rfqID string) (ComboSnapshot, error)
- func (p *ComboPlayer) Topic() string
- func (p *ComboPlayer) WaitFor(ctx context.Context, w ComboWait) (ComboEvent, error)
- type ComboQuote
- type ComboQuoteAcceptedEvent
- type ComboQuoteClosedEvent
- type ComboQuoteRequest
- type ComboRFQClosedEvent
- type ComboRFQLeg
- type ComboRFQOpenedEvent
- type ComboRefusedError
- type ComboRequest
- type ComboRequestClosedEvent
- type ComboSnapshot
- type ComboWait
- type CombosService
- type CreateMarketResult
- type CreateMarketsOptions
- type Decimal
- func (d Decimal) Cmp(other Decimal) int
- func (d Decimal) Float64() float64
- func (d Decimal) IsZero() bool
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) Rat() (r *big.Rat, ok bool)
- func (d Decimal) String() string
- func (d *Decimal) UnmarshalJSON(data []byte) error
- func (d Decimal) Valid() bool
- type Environment
- type Event
- type EventPlayer
- type EventPlayers
- type EventStat
- type EventTeam
- type EventVolume
- type EventsQuery
- type EventsReply
- type EventsService
- func (s *EventsService) All(ctx context.Context, q *EventsQuery) iter.Seq2[Event, error]
- func (s *EventsService) List(ctx context.Context, q *EventsQuery) (*Page[Event], error)
- func (s *EventsService) Players(ctx context.Context, eventID string) (*EventPlayers, error)
- func (s *EventsService) StatsFor(ctx context.Context, eventID string) ([]EventStat, error)
- type FeeTransaction
- type Fill
- type FillsQuery
- type FillsSnapshot
- type ForbiddenError
- type HandshakeError
- type Leaderboard
- type LeaderboardEntry
- type LeaderboardQuery
- type LeaderboardRank
- type LeaderboardService
- type LeaderboardStanding
- type Market
- type MarketBook
- type MarketBookLevel
- type MarketChange
- type MarketChanges
- type MarketFilter
- type MarketSeries
- type MarketStat
- type MarketStatsQuery
- type MarketStatsReply
- type MarketType
- type MarketTypeEventType
- type MarketTypeField
- type MarketTypes
- type MarketsFilter
- type MarketsQuery
- type MarketsService
- func (s *MarketsService) All(ctx context.Context, q *MarketsQuery) iter.Seq2[Market, error]
- func (s *MarketsService) Create(ctx context.Context, eventID string, markets []NewMarket, ...) ([]CreateMarketResult, error)
- func (s *MarketsService) Get(ctx context.Context, marketID string) (*Market, error)
- func (s *MarketsService) List(ctx context.Context, q *MarketsQuery) (*Page[Market], error)
- func (s *MarketsService) Types(ctx context.Context) (MarketTypes, error)
- type Me
- type Message
- type NewMarket
- type NotAvailableError
- type Option
- func WithAuth(a Auth) Option
- func WithCredentialsFile(path string) Option
- func WithEnvironment(e Environment) Option
- func WithEnvironmentName(name string) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithHost(host string) Option
- func WithInsecureSkipVerify() Option
- func WithKey(id, privateKey string) Option
- func WithLogger(l *slog.Logger) Option
- func WithProfile(name string) Option
- func WithRegion(region, env string) Option
- func WithResponseHook(fn func(ResponseEvent)) Option
- func WithRetry(p RetryPolicy) Option
- func WithSigner(id string, signer crypto.Signer) Option
- func WithTimeout(d time.Duration) Option
- func WithUserAgent(product string) Option
- type Order
- type OrderNumbers
- type OrderNumbersBatch
- type OrderRequest
- type OrderSlip
- func (o *OrderSlip) Add(ctx context.Context, e OrderSlipEntry) (OrderSlipRef, error)
- func (o *OrderSlip) Close() error
- func (o *OrderSlip) Done() <-chan struct{}
- func (o *OrderSlip) Err() error
- func (o *OrderSlip) Messages() <-chan Message
- func (o *OrderSlip) Remove(ctx context.Context, ref string) error
- func (o *OrderSlip) Topic() string
- type OrderSlipEntry
- type OrderSlipFill
- type OrderSlipRef
- type OrderbookLevel
- type OrderbookUpdate
- type OrdersFilter
- type OrdersQuery
- type OrdersService
- func (s *OrdersService) All(ctx context.Context, q *OrdersQuery) iter.Seq2[Order, error]
- func (s *OrdersService) Cancel(ctx context.Context, orderID string) (*Cancellation, error)
- func (s *OrdersService) CancelAll(ctx context.Context) ([]Cancellation, error)
- func (s *OrdersService) CancelBatch(ctx context.Context, orderIDs []string) ([]Cancellation, error)
- func (s *OrdersService) Get(ctx context.Context, orderID string) (*Order, error)
- func (s *OrdersService) List(ctx context.Context, q *OrdersQuery) (*Page[Order], error)
- func (s *OrdersService) Place(ctx context.Context, order OrderRequest) (*Order, error)
- func (s *OrdersService) PlaceBatch(ctx context.Context, orders []OrderRequest) ([]BatchOrderResult, error)
- type OrdersSnapshot
- type Page
- type PageQuery
- type PaymentTransaction
- type PaymentUpdate
- type PortfolioService
- func (s *PortfolioService) Adjustments(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
- func (s *PortfolioService) AllAdjustments(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
- func (s *PortfolioService) AllDeposits(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
- func (s *PortfolioService) AllFees(ctx context.Context, q *PageQuery) iter.Seq2[FeeTransaction, error]
- func (s *PortfolioService) AllFills(ctx context.Context, q *FillsQuery) iter.Seq2[Fill, error]
- func (s *PortfolioService) AllLoyalty(ctx context.Context, q *PageQuery) iter.Seq2[Transaction, error]
- func (s *PortfolioService) AllMarketStats(ctx context.Context, q *MarketStatsQuery) iter.Seq2[MarketStat, error]
- func (s *PortfolioService) AllSettlements(ctx context.Context, q *SettlementsQuery) iter.Seq2[Settlement, error]
- func (s *PortfolioService) AllWithdrawals(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
- func (s *PortfolioService) Deposits(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
- func (s *PortfolioService) Fees(ctx context.Context, q *PageQuery) (*Page[FeeTransaction], error)
- func (s *PortfolioService) Fills(ctx context.Context, q *FillsQuery) (*Page[Fill], error)
- func (s *PortfolioService) Loyalty(ctx context.Context, q *PageQuery) (*Page[Transaction], error)
- func (s *PortfolioService) MarketStats(ctx context.Context, q *MarketStatsQuery) (*Page[MarketStat], error)
- func (s *PortfolioService) Settlements(ctx context.Context, q *SettlementsQuery) (*Page[Settlement], error)
- func (s *PortfolioService) Withdrawals(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
- type Position
- type PositionsQuery
- type PositionsSnapshot
- type PositionsUpdate
- type PostOnlyWouldMatchError
- type PoweredBy
- type PricePoint
- type ProfileAvatar
- type ProfileUpdate
- type PublicTrade
- type Reauthenticator
- type RecentTrade
- type ReconnectPolicy
- type ResponseEvent
- type RetryPolicy
- type SelfMatchBatch
- type Settlement
- type SettlementsQuery
- type SettlementsUpdate
- type StatDetail
- type StatsRange
- type Stream
- func (s *Stream) AccountView(ctx context.Context, opts AccountViewOptions) (*AccountView, error)
- func (s *Stream) ChannelRejoins() int
- func (s *Stream) Close() error
- func (s *Stream) ComboMaker(ctx context.Context) (*ComboMaker, error)
- func (s *Stream) ComboPlayer(ctx context.Context) (*ComboPlayer, error)
- func (s *Stream) Connected() bool
- func (s *Stream) Done() <-chan struct{}
- func (s *Stream) Err() error
- func (s *Stream) OrderSlip(ctx context.Context) (*OrderSlip, error)
- func (s *Stream) Reconnects() int
- func (s *Stream) Subscribe(ctx context.Context, ch Channel) (*Subscription, error)
- type StreamOption
- func WithBufferSize(n int) StreamOption
- func WithChannelPingInterval(d time.Duration) StreamOption
- func WithHeartbeatInterval(d time.Duration) StreamOption
- func WithJoinTimeout(d time.Duration) StreamOption
- func WithOnReconnect(fn func()) StreamOption
- func WithReconnectPolicy(p ReconnectPolicy) StreamOption
- func WithStreamLogger(l *slog.Logger) StreamOption
- func WithUserID(id string) StreamOption
- func WithoutReconnect() StreamOption
- type Subscription
- func (sub *Subscription) Close() error
- func (sub *Subscription) DecodeReply(v any) error
- func (sub *Subscription) Done() <-chan struct{}
- func (sub *Subscription) Err() error
- func (sub *Subscription) Joined() bool
- func (sub *Subscription) Messages() <-chan Message
- func (sub *Subscription) Ping(ctx context.Context) error
- func (sub *Subscription) Push(ctx context.Context, event string, payload any) (json.RawMessage, error)
- func (sub *Subscription) Reply() json.RawMessage
- func (sub *Subscription) RequestSeries(ctx context.Context, r StatsRange, marketIDs ...string) (*MarketStatsReply, error)
- func (sub *Subscription) RequestSnapshot(ctx context.Context) error
- func (sub *Subscription) SelectEventIDs(ctx context.Context, eventIDs []string) (json.RawMessage, error)
- func (sub *Subscription) SelectFilters(ctx context.Context, filters map[string][]string) (json.RawMessage, error)
- func (sub *Subscription) SelectMarketIDs(ctx context.Context, marketIDs []string) (json.RawMessage, error)
- func (sub *Subscription) SelectMessageTypes(ctx context.Context, types []string) (json.RawMessage, error)
- func (sub *Subscription) SelectRuleFilters(ctx context.Context, rules []string) (json.RawMessage, error)
- func (sub *Subscription) Topic() string
- func (sub *Subscription) Watch(ctx context.Context, marketIDs ...string) (json.RawMessage, error)
- type Ticker
- type TickerFilter
- type TradesFilter
- type Transaction
- type TransportError
- type UserInfo
- type WebSocketAuth
Examples ¶
Constants ¶
const ( FeatureOAuth = "oauth" FeatureOAuthMember = "oauth.member" FeatureOAuthApp = "oauth.app" FeatureConnect = "connect" FeatureTermsSTXPage = "terms.stx_page" FeatureMarketsCreate = "markets.create" FeatureMarketTypes = "market_types" FeatureEventPlayers = "event_players" FeatureLeaderboard = "leaderboard" FeatureCombos = "combos" // FeatureOrdersPostOnly is the id of post-only orders. // // Deprecated: the exchange no longer publishes whether it takes // post-only orders, so [Client.Capabilities] always reports this id as // nil (not known). Send the order with [PostOnly] and handle an error // matching [ErrNotAvailable]. An exchange on a release from before fill // modes may place the order as a normal limit order. FeatureOrdersPostOnly = "orders.post_only" // FeatureOrdersFillOrKill is the id of fill-or-kill orders. // // Deprecated: reported as nil (not known), as [FeatureOrdersPostOnly]. // Send the order with [FillOrKill] and handle an error matching // [ErrNotAvailable]. FeatureOrdersFillOrKill = "orders.fill_or_kill" )
Feature ids reported by Client.Capabilities and named by NotAvailableError.
const ( // FillNormal matches what it can and rests the rest. The default. FillNormal = "normal" // PostOnly rests only as a maker. When it would match on arrival the // exchange does not place it and [OrdersService.Place] returns a // *[PostOnlyWouldMatchError]. PostOnly = "post_only" // FillOrKill fills in full or not at all. The placement answers // "accepted" (or "delayed"); the order then ends "filled", or "cancelled" // with nothing filled. FillOrKill = "fill_or_kill" )
Fill modes for a limit order; see OrderRequest.FillMode.
const ( // MarketCreated: the market was created. MarketCreated = "created" // MarketExists: the market was already listed; MarketID is that market. MarketExists = "exists" // MarketValid: a dry run found nothing wrong; nothing was created. MarketValid = "valid" // MarketRejected: the market was not created; see Reason. MarketRejected = "rejected" )
Statuses of a CreateMarketResult.
const ( RejectInvalidMarket = "invalid_market" RejectUnsupportedRule = "unsupported_rule" RejectUnsupportedStat = "unsupported_stat" RejectInvalidLine = "invalid_line" RejectUnknownPlayer = "unknown_player" RejectEventNotOpen = "event_not_open" // RejectNotCreated: the answer had no result for the market. RejectNotCreated = "not_created" )
Reasons a market is rejected. The exchange may send reasons added after this version; compare with these constants and treat others as rejected.
const ( Buy = "buy" Sell = "sell" Limit = "limit" MarketOrder = "market" GoodTillStart = "good_till_start" GoodTillTime = "good_till_time" )
Order actions, types and expirations.
const ( HeaderAccessKey = "X-STX-ACCESS-KEY" HeaderAccessTimestamp = "X-STX-ACCESS-TIMESTAMP" HeaderAccessSignature = "X-STX-ACCESS-SIGNATURE" )
Headers carried by every signed request. See https://docs.stxapp.io for the signing scheme.
const DefaultProfile = "default"
DefaultProfile is the profile read when none is named.
const MaxMarketsPerRequest = 25
MaxMarketsPerRequest is the most markets one MarketsService.Create call takes.
const RulePlayerStatLine = "player_stat_line"
RulePlayerStatLine is the market rule for over/under one player's stat in one event, the only rule an app can create today.
const Version = "0.3.1"
Version is the SDK version.
Variables ¶
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 ( // ErrConfig: the client is misconfigured (unknown environment, missing key, // bad PEM, unreadable credentials file). ErrConfig = errors.New("stx: configuration error") // ErrBadRequest: 400, a parameter or body field was refused. ErrBadRequest = errors.New("stx: bad request") // accepted. A machine clock more than 30 seconds off also lands here. ErrUnauthorized = errors.New("stx: unauthorized") // ErrInvalidToken: 401 on an OAuth bearer request whose access token is // missing, expired or revoked. Also matches ErrUnauthorized. ErrInvalidToken = errors.New("stx: invalid token") // ErrForbidden: 403, the key is read-only or the account may not do this. ErrForbidden = errors.New("stx: forbidden") // ErrInsufficientScope: 403 on an OAuth bearer request whose grant lacks a // scope; see APIError.RequiredScopes. Also matches ErrForbidden. ErrInsufficientScope = errors.New("stx: insufficient scope") // ErrTermsRequired: 403, the member has not accepted the current terms; // see APIError.TermsURL. Also matches ErrForbidden. ErrTermsRequired = errors.New("stx: terms not accepted") // ErrIPNotAllowed: 403, the write came from an address the app's IP // allow-list lacks. Also matches ErrForbidden. ErrIPNotAllowed = errors.New("stx: ip address not allowed") // ErrNotFound: 404, the resource does not exist or belongs to another // account. ErrNotFound = errors.New("stx: not found") // ErrRejected: 422, the exchange refused the request, for example // insufficient funds or a closed market. ErrRejected = errors.New("stx: rejected") // ErrRateLimited: 429, too many requests; see APIError.RetryAfter. ErrRateLimited = errors.New("stx: rate limited") // ErrServer: 5xx, the server failed. ErrServer = errors.New("stx: server error") // ErrTransport: the request got no answer (connection, DNS, TLS or // timeout). The error also wraps the underlying network error. ErrTransport = errors.New("stx: transport error") // ErrBlocked: 403 from the edge firewall in front of the API, before the // request reached the exchange; see APIError.Code and // APIError.Reference. Never retried. Also matches ErrForbidden. ErrBlocked = errors.New("stx: blocked") // ErrRestrictedJurisdiction: blocked because the request came from a // location the exchange does not serve. Also matches ErrBlocked. ErrRestrictedJurisdiction = errors.New("stx: restricted jurisdiction") // ErrUnusualNetwork: blocked because the request came through a network // the exchange does not accept traffic from, such as an anonymizing // proxy. Also matches ErrBlocked. ErrUnusualNetwork = errors.New("stx: unusual network") // ErrFillModeNotAllowed: 422, the market does not take the order's fill // mode. Combination markets take neither post_only nor fill_or_kill. // Also matches ErrRejected. ErrFillModeNotAllowed = errors.New("stx: fill mode not allowed on this market") // ErrPostOnlyWouldMatch: a post-only order would have matched on arrival, // so the exchange did not rest it; see *PostOnlyWouldMatchError. ErrPostOnlyWouldMatch = errors.New("stx: post-only order would match") // ErrNotAvailable: this exchange does not have the feature yet, for // example combos where they are not switched on. Nothing is wrong with the // request or the credentials; see *NotAvailableError for the feature. ErrNotAvailable = errors.New("stx: not available") )
Sentinel errors. Match them with errors.Is; an *APIError matches the sentinel for its status, and the more specific ones listed below.
var ( // ErrStreamClosed: the stream was closed, or gave up reconnecting. ErrStreamClosed = errors.New("stx: stream closed") // ErrAlreadySubscribed: the stream already holds a subscription to this // topic. Close it first, or read from the one you have. ErrAlreadySubscribed = errors.New("stx: already subscribed") // ErrNotJoined: a channel command was sent while the topic is not joined, // for example during a reconnect. ErrNotJoined = errors.New("stx: channel not joined") // ErrChannelRefused: the exchange refused a join or a channel command; // see *ChannelError for its reason. ErrChannelRefused = errors.New("stx: channel refused") // ErrTimeout: no reply to a join or a channel command in time. The error // also matches context.DeadlineExceeded. ErrTimeout = errors.New("stx: no reply in time") )
Sentinel errors for streams.
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 ErrComboPriceMoved = errors.New("stx: combo price moved")
ErrComboPriceMoved: an accept found nothing live at least as good as the amount; the request stays open. See ComboRefusedError.Best for the live quote.
var NoRetry = RetryPolicy{MaxAttempts: 1}
NoRetry tries every call once.
Functions ¶
func Bool ¶
Bool returns a pointer to v, for the tri-state filters and fields such as MarketsQuery.Trading and OrderRequest.CancelOnDisconnect.
func Features ¶
func Features() []string
Features returns every feature id Client.Capabilities reports.
func IsValidLine ¶
IsValidLine reports whether line is a valid line: positive and ending in .5.
func KnownStats ¶
KnownStats returns the player stats by sport, as the exchange names them, for autocomplete. The stats an event accepts are the ones EventsService.Players returns for it.
func LoadPrivateKey ¶
func LoadPrivateKey(value string) (ed25519.PrivateKey, error)
LoadPrivateKey parses a PKCS#8 Ed25519 private key from PEM text or from a path to a PEM file (a leading ~ is expanded).
func ParsePrivateKeyPEM ¶
func ParsePrivateKeyPEM(data []byte) (ed25519.PrivateKey, error)
ParsePrivateKeyPEM parses a PKCS#8 Ed25519 private key from PEM bytes.
func SigningMessage ¶
SigningMessage returns the string an API key signs: the Unix time in milliseconds, the uppercase HTTP method and the request path (including any query string), concatenated without separators.
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status, for example 422.
StatusCode int
// Code is the machine-readable error code when the API sends one, such as
// "terms_required" or "not_found"; otherwise empty.
Code string
// Message is the API's human-readable message, kept verbatim.
Message string
// RequestID is the X-Request-Id response header, when present. Quote it
// when you contact support.
RequestID string
// Method and Path are the request that failed; Path includes the query.
Method string
Path string
// Body is the raw response body.
Body []byte
// RetryAfter is the server's Retry-After on a 429, or zero.
RetryAfter time.Duration
// RequiredScopes names the OAuth scopes that would satisfy a 403
// insufficient-scope answer.
RequiredScopes []string
// TermsURL is the page where the member accepts the terms, on a
// terms-required answer.
TermsURL string
// Reference identifies a block by the edge firewall in front of the API
// (a 403 matching ErrBlocked, or a 429 with Code "rate_limited"): the
// request's CloudFront id, from the x-amz-cf-id response header. Quote it
// when you contact support.
Reference string
// contains filtered or unexported fields
}
APIError is an error status answered by the API.
Example ¶
Matching API errors.
package main
import (
"errors"
"fmt"
stx "github.com/stxapp/stx-go"
)
func main() {
err := error(&stx.APIError{StatusCode: 422, Message: "Insufficient assets.", Method: "POST", Path: "/api/v1/orders"})
var apiErr *stx.APIError
if errors.As(err, &apiErr) {
fmt.Println(apiErr.StatusCode, apiErr.Message)
}
fmt.Println(errors.Is(err, stx.ErrRejected))
}
Output: 422 Insufficient assets. true
type APIKey ¶
type APIKey struct {
// contains filtered or unexported fields
}
APIKey is an STX API key: the key id sent with every request, and an Ed25519 signer. The private key never leaves the process; only signatures are sent. It implements Auth.
func NewAPIKey ¶
NewAPIKey builds an API key from its id and an Ed25519 private key given as PKCS#8 PEM text or as a path to a PEM file (a leading ~ is expanded).
func NewAPIKeyWithSigner ¶
NewAPIKeyWithSigner builds an API key around any crypto.Signer that produces pure Ed25519 signatures, for keys held in an HSM or a cloud KMS. An ed25519.PrivateKey works as is.
func (*APIKey) AuthHeaders ¶
AuthHeaders signs one HTTP request.
func (*APIKey) SignedHeaders ¶
SignedHeaders returns the three access headers for method and path at the given time. The server rejects a timestamp more than 30 seconds from its clock, so sign every request afresh.
type AcceptTermsOptions ¶
AcceptTermsOptions sets which consents AccountService.AcceptTerms records. Nil fields default to true for terms and privacy, and are left out for house rules (the exchange then derives it).
type AccountChange ¶
type AccountChange struct {
Kind AccountChangeKind
// Event is the wire event, for example "update" or "new_open_order".
Event string
// Snapshot is true for a join snapshot (the first seed, or after a
// rejoin): that part was replaced, not patched.
Snapshot bool
// Data is the message's typed payload, as on [Message].
Data any
}
AccountChange is one message an AccountView applied.
type AccountChangeKind ¶
type AccountChangeKind string
AccountChangeKind says which part of an AccountView a message touched.
const ( AccountBalance AccountChangeKind = "balance" AccountOrders AccountChangeKind = "orders" AccountFills AccountChangeKind = "fills" AccountPositions AccountChangeKind = "positions" AccountPayment AccountChangeKind = "payment" )
The parts of an account view.
type AccountService ¶
type AccountService struct {
// contains filtered or unexported fields
}
AccountService covers identity, balance, positions, the public profile and terms acceptance. Use it through Client.Account.
func (*AccountService) AcceptTerms ¶
func (s *AccountService) AcceptTerms(ctx context.Context, deviceID string, opts *AcceptTermsOptions) (string, error)
AcceptTerms accepts the current terms for your own account (POST /api/v1/tnc/accept) and returns the server's message. An app cannot accept terms for a member: with a member's OAuth token the exchange answers 403, and the member accepts on an STX page instead.
func (*AccountService) Balance ¶
func (s *AccountService) Balance(ctx context.Context) (*Balance, error)
Balance returns the balance, liabilities and fee schedule (GET /api/v1/account/balance), the same object the balances channel pushes.
func (*AccountService) Me ¶
func (s *AccountService) Me(ctx context.Context) (*Me, error)
Me returns who this key belongs to (GET /api/v1/me): the user id the account channels are keyed by, the account id, and the key's scope ("read_only" or "read_write").
func (*AccountService) Positions ¶
func (s *AccountService) Positions(ctx context.Context, q *PositionsQuery) ([]Position, error)
Positions returns your open positions (GET /api/v1/positions), the same objects the positions channel sends on join. Position is positive when long, negative when short.
func (*AccountService) UpdateProfile ¶
func (s *AccountService) UpdateProfile(ctx context.Context, update ProfileUpdate) (*Me, error)
UpdateProfile changes your public handle, avatar or leaderboard opt-in (PATCH /api/v1/me/profile) and returns the updated identity. Where the exchange has no leaderboard it returns an error matching ErrNotAvailable.
func (*AccountService) UserID ¶
func (s *AccountService) UserID(ctx context.Context) (string, error)
UserID returns the user id from AccountService.Me, fetched once and cached. When Me is forbidden for this credential, the id comes from AccountService.Balance, which carries the same user id.
type AccountState ¶
type AccountState struct {
// Balance is the latest balance summary, or nil before the first.
Balance *Balance
// OpenOrders are your open orders, newest first.
OpenOrders []Order
// Fills are your fills, newest first.
Fills []Fill
// Positions are your positions, one per market.
Positions []Position
}
AccountState is an AccountView's state at one moment.
type AccountView ¶
type AccountView struct {
// contains filtered or unexported fields
}
AccountView is a live copy of your account, kept by the stream. It subscribes to balances, orders, fills and positions, seeds each part from the topic's join snapshot, and applies every update the exchange sends. After a reconnect the snapshots arrive again and replace each part. No REST call is made to keep it current.
Read it with Snapshot whenever you like, or wait on Changes.
func (*AccountView) Changes ¶
func (v *AccountView) Changes() <-chan AccountChange
Changes returns the channel every applied message is announced on, closed when the view ends. When you fall behind, the oldest change is dropped; Snapshot is always current.
func (*AccountView) Close ¶
func (v *AccountView) Close() error
Close leaves the four topics. The stream stays open.
func (*AccountView) Done ¶
func (v *AccountView) Done() <-chan struct{}
Done is closed when the view ends.
func (*AccountView) Err ¶
func (v *AccountView) Err() error
Err returns why the view ended, when one of its subscriptions ended with an error.
func (*AccountView) MarshalJSON ¶
func (v *AccountView) MarshalJSON() ([]byte, error)
MarshalJSON writes the current AccountState.
func (*AccountView) Ready ¶
func (v *AccountView) Ready() bool
Ready reports whether every part has had its join snapshot.
func (*AccountView) Snapshot ¶
func (v *AccountView) Snapshot() AccountState
Snapshot returns the view's state now. The slices are yours to keep.
type AccountViewOptions ¶
type AccountViewOptions struct {
// MarketIDs keeps orders, fills and positions to these markets. The
// balance is always the whole account.
MarketIDs []string
// AccountID picks one of your accounts for the balance; empty means the
// account the stream signed in as.
AccountID string
// KeepFlatPositions keeps positions whose quantity is zero.
KeepFlatPositions bool
// MaxFills is the most fills kept; the oldest go first. Default 1000.
MaxFills int
// SnapshotTimeout bounds the wait for the four join snapshots. Default
// 15s.
SnapshotTimeout time.Duration
}
AccountViewOptions configures Stream.AccountView.
type Auth ¶
type Auth interface {
// Kind is a stable label for logs, such as "api_key" or "oauth".
Kind() string
// AuthHeaders returns the headers for one HTTP request. It is called
// afresh for every attempt. path includes the query string, exactly as
// sent.
AuthHeaders(ctx context.Context, method, path string) (http.Header, error)
}
Auth authenticates requests. *APIKey (Ed25519 request signing) is the usual one; the oauth package provides bearer-token implementations for apps acting on a member's behalf. Pass one with WithAuth.
type Balance ¶
type Balance struct {
// The account's cash balance. Unaffected by placing an order, but not all of
// it may be available. In dollars. Money as a decimal string, exactly as sent
// by the API.
AccountBalance Decimal `json:"account_balance,omitempty"`
// The account this balance is for.
AccountID string `json:"account_id,omitempty"`
// The balance available to withdraw or place further orders with. Rounded
// **down** to the cent, so it never overstates what is spendable. In dollars.
// Money as a decimal string, exactly as sent by the API.
AvailableBalance Decimal `json:"available_balance,omitempty"`
// The fee percentage on the `fixed_percent` schedule; `null` for any other
// schedule. A number, not a money string.
BaseFeePercent float64 `json:"base_fee_percent,omitempty"`
// Total liability from buy orders, including the potential trade-fee reserve.
// Rounded **up** to the cent. In dollars. Money as a decimal string, exactly
// as sent by the API.
BuyOrderLiability Decimal `json:"buy_order_liability,omitempty"`
// The account's escrow balance. In dollars. Money as a decimal string, exactly
// as sent by the API.
Escrow Decimal `json:"escrow,omitempty"`
// The account's fee schedule. One of: "fixed_percent", "revenue_share",
// "loyalty_tier", "fixed_percent_market_group", "fixed_percent_event",
// "on_trade", "loyalty_tier_on_trade".
FeeSchedule string `json:"fee_schedule,omitempty"`
// The account's loyalty tier. Every account has one; new accounts start at
// `rookie`. One of: "rookie", "veteran", "all_star", "mvp", "hall_of_fame".
LoyaltyTier string `json:"loyalty_tier,omitempty"`
// Per-trade maker fee factor, present only on the `on_trade` and
// `loyalty_tier_on_trade` schedules; `null` otherwise. A number, not a money
// string.
MakerFactor float64 `json:"maker_factor,omitempty"`
// Loyalty points the account has accumulated. A whole number, not a money
// string.
Points int64 `json:"points,omitempty"`
// Total liability from position premiums. Routinely negative. Rounded **up**
// to the cent in both signs. In dollars. Money as a decimal string, exactly as
// sent by the API.
PositionPremiumLiability Decimal `json:"position_premium_liability,omitempty"`
// Total liability from sell orders, including the potential trade-fee reserve.
// Rounded **up** to the cent. In dollars. Money as a decimal string, exactly
// as sent by the API.
SellOrderLiability Decimal `json:"sell_order_liability,omitempty"`
// Per-trade taker fee factor, present only on the `on_trade` and
// `loyalty_tier_on_trade` schedules; `null` otherwise. A number, not a money
// string.
TakerFactor float64 `json:"taker_factor,omitempty"`
// Lifetime total balance adjustments. In dollars. Money as a decimal string,
// exactly as sent by the API.
TotalAdjustments Decimal `json:"total_adjustments,omitempty"`
// Lifetime total deposits. In dollars. Money as a decimal string, exactly as
// sent by the API.
TotalDeposits Decimal `json:"total_deposits,omitempty"`
// Total fees from all settlements and other fees. In dollars. Money as a
// decimal string, exactly as sent by the API.
TotalFees Decimal `json:"total_fees,omitempty"`
// Total gross profit and loss from all settlements. In dollars. Money as a
// decimal string, exactly as sent by the API.
TotalSettlementPnL Decimal `json:"total_settlement_pnl,omitempty"`
// The number of trades the account has made across every market.
TotalTradeCount int64 `json:"total_trade_count,omitempty"`
// The risk the account has committed across every market. In dollars. Money as
// a decimal string, exactly as sent by the API.
TotalTraded Decimal `json:"total_traded,omitempty"`
// Lifetime total withdrawals. In dollars. Money as a decimal string, exactly
// as sent by the API.
TotalWithdrawals Decimal `json:"total_withdrawals,omitempty"`
// The user that owns the account.
UserID string `json:"user_id,omitempty"`
}
Balance: One account's balance and fee summary, in the dollar wire format.
type BatchOrderResult ¶
type BatchOrderResult struct {
Order *Order `json:"order,omitempty"`
Errors []string `json:"errors,omitempty"`
}
BatchOrderResult is one entry of OrdersService.PlaceBatch: the placed order, or why it was not placed.
func (BatchOrderResult) OK ¶
func (r BatchOrderResult) OK() bool
OK reports whether the order was placed.
type BookLevel ¶
type BookLevel struct {
// The price of this level. In dollars. Money as a decimal string, exactly as
// sent by the API.
Price Decimal `json:"price,omitempty"`
// Contracts resting at this price. Quantity as a decimal string, exactly as
// sent by the API.
Quantity Decimal `json:"quantity,omitempty"`
}
BookLevel: One price level of resting size on the book.
type Cancellation ¶
type Cancellation struct {
// The order this outcome relates to.
OrderID string `json:"order_id,omitempty"`
// The order status after cancelling, or a reason it was not cancelled, such as
// "Order not found" for an unknown id.
Status string `json:"status,omitempty"`
}
Cancellation: The outcome of cancelling one order.
type Capabilities ¶
type Capabilities struct {
// Host is the exchange host, such as "demo.stxapp.io".
Host string
// APIVersion is GET /api_version, or "" when it did not answer.
APIVersion string
// CheckedAt is when the checks ran.
CheckedAt time.Time
// ScopesSupported are the scopes the exchange's OAuth discovery document
// lists; empty without OAuth.
ScopesSupported []string
// Features maps every feature id to true (the exchange has it), false
// (it does not) or nil (not known: the check needs credentials this
// client lacks, or the exchange did not answer).
Features map[string]*bool
}
Capabilities is what an exchange showed it has.
func (*Capabilities) Has ¶
func (c *Capabilities) Has(feature string) bool
Has reports whether the exchange is known to have feature.
func (*Capabilities) Known ¶
func (c *Capabilities) Known(feature string) bool
Known reports whether the check for feature had an answer.
func (*Capabilities) Require ¶
func (c *Capabilities) Require(feature string) error
Require returns a *NotAvailableError when the exchange is known to lack feature, and nil otherwise. A feature that could not be checked does not fail here: the call that needs it will say.
type Channel ¶
type Channel struct {
// contains filtered or unexported fields
}
Channel is a topic to subscribe to, with its join filters. Build one with a constructor such as OrderbookChannel or OrdersChannel and pass it to Stream.Subscribe. Each channel's events and payloads are documented at https://docs.stxapp.io/websockets/.
func AccountChannel ¶
AccountChannel carries everything the orders, fills, positions, settlements and balances channels carry, on one topic. Do not also subscribe to one of those (you would get every message twice), and use OrdersChannel if you need cancel-on-disconnect.
func BalancesChannel ¶
BalancesChannel sends your balance on join ("balances", a Balance), the same summary on every change ("update"), and "payment_update" (PaymentUpdate) as payments move. An empty accountID means the account the socket signed in as.
func EventsChannel ¶
EventsChannel sends each named event's traded volume as an "event" message whenever it changes. The join reply carries the current values. At least one event id is required.
func FillsChannel ¶
FillsChannel sends the fills behind your open positions on join ("all_trades", a FillsSnapshot), then one "trade" (Fill) per execution or status change. Empty marketIDs means all markets.
func MarketChannel ¶
MarketChannel is one market in full, by id or symbol. The join reply is the market's current state with its book (read it with Subscription.Reply into a MarketChange); then "market_update" carries the fields that changed and "order_book_update" a fresh book. A resulted or voided market sends its last update, the exchange closes the topic, and the subscription ends. Prices are converted from cents to dollar strings.
func MarketStatsChannel ¶
func MarketStatsChannel(r StatsRange, marketIDs ...string) Channel
MarketStatsChannel is the price series of each market named. The join reply holds the history (read it with Subscription.Reply into a MarketStatsReply); "market_stats" then sends changed buckets to upsert by timestamp, and "market_stats_snapshot" a series to replace. An empty range means StatsAll. At least one market id is required.
func MarketUpdatesChannel ¶
MarketUpdatesChannel sends "created" and "updated" for the markets you watch: these, and any added with Subscription.Watch. Watches are sent again after every rejoin. Prices are converted from cents to dollar strings.
func MarketsChannel ¶
func MarketsChannel(f MarketsFilter) Channel
MarketsChannel sends "market_created" and "market_updated" for every market. Each message maps market id to a MarketChange; an update carries only the fields that changed. The exchange sends prices on this channel in cents; the stream converts them to dollar strings like the rest of the API.
func OrderbookChannel ¶
OrderbookChannel is the aggregated book of each market named: one "book" message per market on the exchange's publish cadence, each a full snapshot of that market's book to replace what you hold. At least one market id is required.
func OrdersChannel ¶
func OrdersChannel(f OrdersFilter) Channel
OrdersChannel sends your open orders on join ("all_orders", an OrdersSnapshot), then each order whenever it changes ("new_open_order", an Order).
Example ¶
Your orders, with cancel-on-disconnect: the stream pings at a third of the granted timeout for as long as the topic is joined.
package main
import (
"context"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
ctx := context.Background()
client, err := stx.New(stx.WithProfile("us-demo"))
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.OrdersChannel(stx.OrdersFilter{CancelOnDisconnect: true}))
if err != nil {
log.Fatal(err)
}
for msg := range sub.Messages() {
switch d := msg.Data.(type) {
case *stx.OrdersSnapshot:
fmt.Println(len(d.Orders), "open orders")
case *stx.Order:
fmt.Println(d.ID, d.Status, d.Filled)
}
}
}
Output:
func PositionsChannel ¶
PositionsChannel sends your positions on join ("all_positions", a PositionsSnapshot), then "updated_positions" (PositionsUpdate) with only the positions that changed.
func SettlementsChannel ¶
SettlementsChannel sends "new_settlements" (SettlementsUpdate) as they are recorded. There is no snapshot; read history over REST.
func TickerChannel ¶
func TickerChannel(f TickerFilter) Channel
TickerChannel sends a "ticker" message for each market whose price, top of book, volume or open interest moves. Nothing is sent on join.
func TradesChannel ¶
func TradesChannel(f TradesFilter) Channel
TradesChannel sends every execution on the exchange as a "trade" message, anonymized. Action is the taker's side. Your own executions are on FillsChannel.
func UserInfoChannel ¶
func UserInfoChannel() Channel
UserInfoChannel sends your profile right after joining, then on every change ("user_updated", a UserInfo).
type ChannelError ¶
type ChannelError struct {
// Topic is the wire topic, for example "orders:7fb55544-3a7e-4f6b-bd66-fc89bd3a1087".
Topic string
// Event is what was sent: "phx_join", "select_market_ids", ...
Event string
// Reason is the reply's "reason", or the server event ("phx_close",
// "phx_error") that ended a join before it was answered.
Reason string
// Reply is the reply's raw "response" object.
Reply json.RawMessage
// contains filtered or unexported fields
}
ChannelError is the exchange refusing a join or a channel command, with the reason it gave, such as "market_ids_required" or "unauthorized".
func (*ChannelError) Error ¶
func (e *ChannelError) Error() string
Error returns "stx: EVENT on TOPIC refused: REASON".
func (*ChannelError) Is ¶
func (e *ChannelError) Is(target error) bool
Is matches ErrChannelRefused for a refusal, and ErrUnauthorized and ErrInsufficientScope for those reasons.
type 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 ¶
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.
package main
import (
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
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())
}
Output:
func (*Client) APIKey ¶
APIKey returns the configured API key, or nil when the client uses another Auth or none.
func (*Client) BaseURL ¶
BaseURL returns the API base URL, such as "https://demo.stxapp.io".
func (*Client) Capabilities ¶
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 (*Client) HTTPClient ¶
HTTPClient returns the HTTP client in use.
func (*Client) Host ¶
Host returns the exchange host, such as "demo.stxapp.io": the name NotAvailableError reports.
func (*Client) Stream ¶
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.
package main
import (
"context"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
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)
}
}
}
Output:
func (*Client) SupportsFillMode
deprecated
added in
v0.2.1
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.
type ComboBestQuote ¶
type ComboBestQuote struct {
QuoteID string `json:"quote_id"`
Amount Decimal `json:"amount"`
ExpiresAt int64 `json:"expires_at"`
}
ComboBestQuote is the best live quote. Every field is empty when nothing is live. ExpiresAt is in Unix microseconds.
type ComboBestQuoteEvent ¶
type ComboBestQuoteEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
ComboBestQuote
}
ComboBestQuoteEvent is "best_quote" to the player: the best quote changed.
type ComboCashOut ¶
type ComboCashOut struct {
RFQID string `json:"rfq_id"`
// MarketID is the combination being sold.
MarketID string `json:"market_id"`
// Quantity is set by the exchange: what you hold less your resting sells.
Quantity Decimal `json:"quantity"`
}
ComboCashOut is the reply to ComboPlayer.CashOut.
type ComboEvent ¶
type ComboEvent struct {
// Event is the event name, for example "best_quote" or "rfq_opened".
Event string
// RFQID is the request it is about; QuoteID the quote, on maker events
// that name one.
RFQID string
QuoteID string
Payload json.RawMessage
// Data is the typed payload. To the player: *ComboBestQuoteEvent,
// *ComboPlacedEvent or *ComboRequestClosedEvent. To the maker:
// *ComboRFQOpenedEvent, *ComboRFQClosedEvent, *ComboQuoteAcceptedEvent,
// *ComboMakerPlacedEvent or *ComboQuoteClosedEvent.
Data any
}
ComboEvent is one push on a combo topic.
type ComboLeg ¶
type ComboLeg struct {
MarketID string `json:"market_id"`
Outcome ComboOutcome `json:"outcome"`
}
ComboLeg is one leg of a quote request: an open, ordinary market and the outcome the combination needs of it.
type ComboMaker ¶
type ComboMaker struct {
// contains filtered or unexported fields
}
ComboMaker is the maker's side of combos, on combo_quote:<user_id>. Get one with Stream.ComboMaker. Joining subscribes to every request opened from then on ("rfq_opened"); earlier requests are not replayed.
A quote belongs to this topic: closing it or a dropped socket withdraws it. Every refusal is a *ComboRefusedError with the exchange's reason in Code.
func (*ComboMaker) Close ¶
func (m *ComboMaker) Close() error
Close leaves the topic, which withdraws every quote placed on it.
func (*ComboMaker) Done ¶
func (m *ComboMaker) Done() <-chan struct{}
Done is closed when the maker ends.
func (*ComboMaker) Err ¶
func (m *ComboMaker) Err() error
Err returns why the maker ended, like Subscription.Err.
func (*ComboMaker) Events ¶
func (m *ComboMaker) Events() <-chan ComboEvent
Events returns the channel typed events arrive on, closed when the maker ends.
func (*ComboMaker) ExternalID ¶
func (m *ComboMaker) ExternalID() string
ExternalID returns your pseudonym. Makers' pseudonyms are shown to no one.
func (*ComboMaker) History ¶
func (m *ComboMaker) History() []ComboEvent
History returns the events received so far (the latest 1000), oldest first.
func (*ComboMaker) Quote ¶
func (m *ComboMaker) Quote(ctx context.Context, q ComboQuoteRequest) (ComboQuote, error)
Quote offers an amount on a request. Price it against the request's MaxPrice and TickSize.
func (*ComboMaker) WaitFor ¶
func (m *ComboMaker) WaitFor(ctx context.Context, w ComboWait) (ComboEvent, error)
WaitFor returns the first event that matches w, looking first at the events already received. It takes nothing from ComboMaker.Events.
func (*ComboMaker) WithdrawQuote ¶
func (m *ComboMaker) WithdrawQuote(ctx context.Context, rfqID, quoteID string) error
WithdrawQuote removes one of your quotes.
type ComboMakerPlacedEvent ¶
type ComboMakerPlacedEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
ExternalID string `json:"external_id"`
QuoteID string `json:"quote_id"`
OrderID string `json:"order_id"`
Quantity Decimal `json:"quantity"`
Price Decimal `json:"price"`
}
ComboMakerPlacedEvent is "placed" to the maker: the quote bound and your order was placed, at the same size and price as the player's.
type ComboOutcome ¶
type ComboOutcome string
ComboOutcome is what the combination needs of a leg: "won" or "lost".
const ( ComboWon ComboOutcome = "won" ComboLost ComboOutcome = "lost" )
The outcomes of a leg.
type ComboPlacedEvent ¶
type ComboPlacedEvent struct {
RFQID string `json:"rfq_id"`
ComboPlacement
}
ComboPlacedEvent is "placed" to the player: the bind placed your order.
type ComboPlacement ¶
type ComboPlacement struct {
MarketID string `json:"market_id"`
OrderID string `json:"order_id"`
Quantity Decimal `json:"quantity"`
Price Decimal `json:"price"`
}
ComboPlacement is what an accept placed for you: your order on the combination's market. Its fills arrive on the fills channel.
type ComboPlayer ¶
type ComboPlayer struct {
// contains filtered or unexported fields
}
ComboPlayer is the player's side of combos, on rfq:<user_id>. Get one with Stream.ComboPlayer.
A request belongs to this topic: closing it or a dropped socket ends the request "cancelled", and the stream's rejoin does not bring it back. Every refusal is a *ComboRefusedError with the exchange's reason in Code.
Example ¶
Ask for quotes on a combination and accept the best one.
package main
import (
"context"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
ctx := context.Background()
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
player, err := client.Combos.Player(ctx)
if err != nil {
log.Fatal(err)
}
defer player.Close()
req, err := player.RequestQuote(ctx, []stx.ComboLeg{
{MarketID: "71692895-2991-440b-923d-7dfb6783cb17", Outcome: stx.ComboWon},
{MarketID: "e00651a3-10cb-4bc1-9e1f-c5ea1796c83b", Outcome: stx.ComboWon},
}, "250.00")
if err != nil {
log.Fatal(err)
}
ev, err := player.WaitFor(ctx, stx.ComboWait{Events: []string{"best_quote"}, RFQID: req.RFQID})
if err != nil {
log.Fatal(err)
}
best := ev.Data.(*stx.ComboBestQuoteEvent)
placed, err := player.Accept(ctx, req.RFQID, best.QuoteID, best.Amount)
if err != nil {
log.Fatal(err)
}
fmt.Println(placed.MarketID, placed.Quantity, placed.Price)
}
Output:
func (*ComboPlayer) Accept ¶
func (p *ComboPlayer) Accept(ctx context.Context, rfqID, quoteID string, amount Decimal) (ComboPlacement, error)
Accept binds the request at amount or better, normally the amount "best_quote" showed; the best live quote binds, so the placement can be better than amount. It waits up to 35 seconds unless ctx ends first.
When nothing at least as good is live it returns a *ComboRefusedError matching ErrComboPriceMoved, with the live quote in Best; the request stays open and you can accept again. The reply says what was placed; fills arrive on the fills channel.
func (*ComboPlayer) Cancel ¶
func (p *ComboPlayer) Cancel(ctx context.Context, rfqID string) error
Cancel ends the request and drops every quote on it.
func (*ComboPlayer) CashOut ¶
func (p *ComboPlayer) CashOut(ctx context.Context, marketID string) (ComboCashOut, error)
CashOut asks makers to quote for what you hold of a combination, by the market id from "placed". The exchange sets the size.
func (*ComboPlayer) Close ¶
func (p *ComboPlayer) Close() error
Close leaves the topic. Every request still open on it ends "cancelled". To see each request's own close first, cancel it and wait for its "negotiation_closed" before closing.
func (*ComboPlayer) Done ¶
func (p *ComboPlayer) Done() <-chan struct{}
Done is closed when the player ends.
func (*ComboPlayer) Err ¶
func (p *ComboPlayer) Err() error
Err returns why the player ended, like Subscription.Err.
func (*ComboPlayer) Events ¶
func (p *ComboPlayer) Events() <-chan ComboEvent
Events returns the channel typed events arrive on, closed when the player ends.
func (*ComboPlayer) ExternalID ¶
func (p *ComboPlayer) ExternalID() string
ExternalID returns your pseudonym, which makers see on your requests.
func (*ComboPlayer) History ¶
func (p *ComboPlayer) History() []ComboEvent
History returns the events received so far (the latest 1000), oldest first.
func (*ComboPlayer) RequestQuote ¶
func (p *ComboPlayer) RequestQuote(ctx context.Context, legs []ComboLeg, amount Decimal) (ComboRequest, error)
RequestQuote asks makers to quote on these legs for a stake in dollars, such as "250.00" (whole cents). Makers quote what you win; quotes arrive as "best_quote" events.
func (*ComboPlayer) Snapshot ¶
func (p *ComboPlayer) Snapshot(ctx context.Context, rfqID string) (ComboSnapshot, error)
Snapshot returns the request now, with the live best quote.
func (*ComboPlayer) WaitFor ¶
func (p *ComboPlayer) WaitFor(ctx context.Context, w ComboWait) (ComboEvent, error)
WaitFor returns the first event that matches w, looking first at the events already received. It takes nothing from ComboPlayer.Events.
type ComboQuote ¶
type ComboQuote struct {
QuoteID string `json:"quote_id"`
Amount Decimal `json:"amount"`
// ExternalID is the player's pseudonym.
ExternalID string `json:"external_id"`
}
ComboQuote is the reply to ComboMaker.Quote. It carries no price or size: the bind sets those.
type ComboQuoteAcceptedEvent ¶
type ComboQuoteAcceptedEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
ExternalID string `json:"external_id"`
QuoteID string `json:"quote_id"`
}
ComboQuoteAcceptedEvent is "quote_accepted" to the maker: this quote is about to be bound.
type ComboQuoteClosedEvent ¶
type ComboQuoteClosedEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
ExternalID string `json:"external_id"`
QuoteID string `json:"quote_id"`
Reason string `json:"reason"`
}
ComboQuoteClosedEvent is "negotiation_closed" to the maker: this quote stopped standing. Reason is "placed_elsewhere", "maker_refused", "cancelled", "expired", "leg_not_quotable", "unknown_leg" or "player_refused".
type ComboQuoteRequest ¶
type ComboQuoteRequest struct {
// RFQID is the request, from "rfq_opened".
RFQID string
// Amount, in dollars: on a buy what the player wins, on a cash out what
// you pay for the whole size.
Amount Decimal
// ExpiresIn is how long the quote stands, counted from receipt, in whole
// milliseconds. The quote ends no later than its request.
ExpiresIn time.Duration
// ClientOrderID (at most 255 bytes) is copied onto your order if the
// quote binds.
ClientOrderID string
}
ComboQuoteRequest is a maker's quote.
type ComboRFQClosedEvent ¶
type ComboRFQClosedEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
Reason string `json:"reason"`
}
ComboRFQClosedEvent is "rfq_closed" to makers: a request ended. Reason is "placed", "cancelled", "expired", "leg_not_quotable", "unknown_leg", "player_refused", "maker_refused" or "ended".
type ComboRFQLeg ¶
type ComboRFQLeg struct {
MarketID string `json:"market_id"`
Outcome ComboOutcome `json:"outcome"`
ShortName string `json:"short_name"`
}
ComboRFQLeg is one leg as makers see it. ShortName is the leg market's display name, when the exchange has one.
type ComboRFQOpenedEvent ¶
type ComboRFQOpenedEvent struct {
RFQID string `json:"rfq_id"`
// MarketID is empty on a buy and the combination on a cash out.
MarketID string `json:"market_id"`
// ExternalID is the player's pseudonym.
ExternalID string `json:"external_id"`
// Side is the player's side; you take the other.
Side string `json:"side"`
Amount Decimal `json:"amount"`
Quantity Decimal `json:"quantity"`
MaxPrice Decimal `json:"max_price"`
TickSize Decimal `json:"tick_size"`
ExpiresAt int64 `json:"expires_at"`
Legs []ComboRFQLeg `json:"legs"`
}
ComboRFQOpenedEvent is "rfq_opened" to makers: a player opened a request. Price it against MaxPrice and TickSize, not constants.
type ComboRefusedError ¶
type ComboRefusedError struct {
// Command is what was sent: "request_quote", "accept", "phx_join", ...
Command string
// Topic is the wire topic.
Topic string
// Code is the refusal reason, such as "not_found" or "price_moved". A
// "player_refused:<detail>" reason has Code "player_refused" and the rest
// in Detail.
Code string
Detail string
// Reason is the reason exactly as sent.
Reason string
// Reply is the raw reply.
Reply json.RawMessage
// Best is the live best quote on "price_moved", or nil.
Best *ComboBestQuote
}
ComboRefusedError is a combo command or join the exchange refused.
func (*ComboRefusedError) Error ¶
func (e *ComboRefusedError) Error() string
Error returns "stx: COMMAND on TOPIC refused: REASON".
func (*ComboRefusedError) Is ¶
func (e *ComboRefusedError) Is(target error) bool
Is matches ErrComboPriceMoved, ErrNotFound for "not_found", ErrUnauthorized for "unauthorized" and ErrInsufficientScope for "insufficient_scope".
type ComboRequest ¶
type ComboRequest struct {
RFQID string `json:"rfq_id"`
}
ComboRequest is the reply to ComboPlayer.RequestQuote.
type ComboRequestClosedEvent ¶
type ComboRequestClosedEvent struct {
RFQID string `json:"rfq_id"`
MarketID string `json:"market_id"`
Reason string `json:"reason"`
}
ComboRequestClosedEvent is "negotiation_closed" to the player: the request ended without placing. Reason is "cancelled", "expired", "leg_not_quotable", "unknown_leg", "player_refused" or "maker_refused".
type ComboSnapshot ¶
type ComboSnapshot struct {
RFQID string `json:"rfq_id"`
// MarketID is empty on a buy until a bind places, and the combination on
// a cash out.
MarketID string `json:"market_id"`
// Status is "open", or "binding" while an acceptance waits for its next
// bind attempt.
Status string `json:"status"`
// Side is "buy" for a request, "sell" for a cash out.
Side string `json:"side"`
// Amount is the stake on a buy; Quantity the size on a cash out.
Amount Decimal `json:"amount"`
Quantity Decimal `json:"quantity"`
ExpiresAt int64 `json:"expires_at"`
BestQuote ComboBestQuote `json:"best_quote"`
}
ComboSnapshot is the reply to ComboPlayer.Snapshot: the request now.
type ComboWait ¶
type ComboWait struct {
// Events are the event names to match, for example "best_quote".
Events []string
RFQID string
QuoteID string
}
ComboWait selects the event ComboPlayer.WaitFor and ComboMaker.WaitFor wait for. Empty fields match anything.
type CombosService ¶
type CombosService struct {
// contains filtered or unexported fields
}
CombosService trades combos: requests for quote as a player (taker), and quotes as a maker. Use it through Client.Combos. Its Player and Maker open a stream of their own; to share one socket with other subscriptions, use Stream.ComboPlayer and Stream.ComboMaker.
Where an exchange does not offer combos, joining returns an error matching ErrNotAvailable.
func (*CombosService) Available ¶
func (s *CombosService) Available(ctx context.Context) (bool, error)
Available reports whether this exchange offers combos, by joining a player topic nobody owns: the exchange answers "unmatched topic" where it has no combos, and refuses the join for another reason where it does. Nothing is created.
func (*CombosService) Maker ¶
func (s *CombosService) Maker(ctx context.Context, opts ...StreamOption) (*ComboMaker, error)
Maker opens a stream and joins the maker topic. Closing the maker closes that stream.
func (*CombosService) Player ¶
func (s *CombosService) Player(ctx context.Context, opts ...StreamOption) (*ComboPlayer, error)
Player opens a stream and joins the player topic. Closing the player closes that stream.
type CreateMarketResult ¶
type CreateMarketResult struct {
// Index is the market's position in the list given to Create.
Index int
// Status is MarketCreated, MarketExists, MarketValid or MarketRejected.
Status string
// MarketID is set when Status is MarketCreated or MarketExists.
MarketID string
// Reason is set when Status is MarketRejected, such as
// RejectInvalidLine.
Reason string
// Market is the market as requested.
Market NewMarket
}
CreateMarketResult is the outcome for one requested market.
type CreateMarketsOptions ¶
type CreateMarketsOptions struct {
// Validate checks each market against the event's players and stats and
// the line rule before sending. Failing markets come back rejected
// without a request, and the rest are sent with the event's own stat key.
// It reads the event's players, so an app token also needs the events
// scope.
Validate bool
// DryRun runs every check on the exchange and creates nothing; a market
// that would be created, or one already listed, comes back valid.
DryRun bool
}
CreateMarketsOptions tune MarketsService.Create.
type Decimal ¶
type Decimal string
Decimal is an exact decimal number carried as its text, such as "0.5600" for a price in dollars or "100.00" for a quantity of contracts.
It round-trips through JSON unchanged: it is written as a JSON string, and read from a JSON string or a JSON number (keeping the number's digits). Arithmetic is left to you; Decimal.Rat gives an exact big.Rat.
Example ¶
Decimals keep the exact digits the API sends.
package main
import (
"fmt"
stx "github.com/stxapp/stx-go"
)
func main() {
price := stx.MustDecimal("0.5600")
fmt.Println(price, price.Cmp(stx.MustDecimal("0.56")) == 0)
}
Output: 0.5600 true
func MustDecimal ¶
MustDecimal is ParseDecimal for constants: it panics when s is not a decimal number.
func ParseDecimal ¶
ParseDecimal checks that s is a decimal number and returns it unchanged.
func (Decimal) Cmp ¶
Cmp compares d and other numerically: -1 if d < other, 0 if equal, +1 if d > other. An empty or malformed value compares as zero.
func (Decimal) Float64 ¶
Float64 returns the nearest float64. It is lossy; use it for display and statistics, never to build a price or quantity you send back.
func (Decimal) MarshalJSON ¶
MarshalJSON writes d as a JSON string, or null when d is empty.
func (Decimal) Rat ¶
Rat returns d as an exact rational number. ok is false when d is empty or not a decimal number.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string, a JSON number (its literal digits are kept), or null.
type 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/.
func EnvironmentNamed ¶
func EnvironmentNamed(name string) (Environment, error)
EnvironmentNamed returns the environment called name, such as "us-demo".
func Environments ¶
func Environments() []Environment
Environments returns every published environment.
type Event ¶
type Event struct {
// Whether this event is archived.
Archived bool `json:"archived,omitempty"`
// The competition for this event
Competition string `json:"competition,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The type of this event, e.g. `ad_hoc`, `baseball_game`, `basketball_game`.
EventType string `json:"event_type,omitempty"`
// The event's participants, as an array of `{name, role, short_name,
// abbreviation}`.
Participants []map[string]any `json:"participants,omitempty"`
// Whether this event is promoted.
Promoted bool `json:"promoted,omitempty"`
// The short title for this event
ShortTitle string `json:"short_title,omitempty"`
// The sport for this event
Sport string `json:"sport,omitempty"`
// Start time of this event UNIX microseconds.
StartTime int64 `json:"start_time,omitempty"`
// Start time of this event
StartTimeISO time.Time `json:"start_time_iso,omitzero"`
// The status of this event One of: "scheduled", "in_progress", "completed",
// "cancelled".
Status string `json:"status,omitempty"`
// The STX symbol for this event
Symbol string `json:"symbol,omitempty"`
// The title of this event
Title string `json:"title,omitempty"`
}
Event: A sporting event that markets hang off.
type EventPlayer ¶
type EventPlayer struct {
// PlayerID is what a new market names the player by.
PlayerID string `json:"player_id"`
Name string `json:"name"`
Jersey string `json:"jersey,omitempty"`
Position string `json:"position,omitempty"`
}
EventPlayer is one player on an event's roster.
type EventPlayers ¶
type EventPlayers struct {
EventID string `json:"event_id"`
// Teams is empty until the rosters are published.
Teams []EventTeam `json:"teams"`
// Stats are the stats this event accepts.
Stats []EventStat `json:"stats"`
}
EventPlayers are an event's rosters and the stats a market on it can use.
type EventStat ¶
type EventStat struct {
// Stat is the key to send, such as "POINTS".
Stat string `json:"stat"`
// Name is the display name, such as "Points".
Name string `json:"name"`
}
EventStat is a stat a market can be created on.
type EventTeam ¶
type EventTeam struct {
Team string `json:"team"`
Players []EventPlayer `json:"players"`
}
EventTeam is one team's roster, sorted by player name.
type EventVolume ¶
EventVolume is an "event" message: an event's lifetime traded volume in dollars across its markets. It is the whole value, not a delta.
type EventsQuery ¶
type EventsQuery struct {
EventIDs []string
Sports []string
Competitions []string
EventTypes []string
Title string
// Status is "scheduled", "in_progress", "completed" or "cancelled".
Status string
Promoted *bool
// SortBy is "start_time"; SortDirection is "asc" or "desc".
SortBy string
SortDirection string
Limit int
Cursor string
}
EventsQuery filters EventsService.List.
type EventsReply ¶
type EventsReply struct {
SelectedEventIDs []string `json:"selected_event_ids"`
Events []EventVolume `json:"events"`
}
EventsReply is the events channel's join reply, and the reply to Subscription.SelectEventIDs. An event with nothing traded is left out of Events.
type EventsService ¶
type EventsService struct {
// contains filtered or unexported fields
}
EventsService lists events and their players. Use it through Client.Events.
func (*EventsService) All ¶
func (s *EventsService) All(ctx context.Context, q *EventsQuery) iter.Seq2[Event, error]
All returns every event matching q, following the cursor.
func (*EventsService) List ¶
func (s *EventsService) List(ctx context.Context, q *EventsQuery) (*Page[Event], error)
List returns one page of events (GET /api/v1/events).
func (*EventsService) Players ¶
func (s *EventsService) Players(ctx context.Context, eventID string) (*EventPlayers, error)
Players returns the event's team rosters and the stats a market on it can use (GET /api/v1/events/{event_id}/players). It needs an API key or an OAuth app token with the events scope, and returns an error matching ErrNotAvailable where the exchange does not have it.
type FeeTransaction ¶
type FeeTransaction struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// The monetary value the entry was calculated from. In dollars. Money as a
// decimal string, exactly as sent by the API.
Amount Decimal `json:"amount,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The fee that generated this entry, when it came from one.
FeeID string `json:"fee_id,omitempty"`
// Unique identifier for the record.
ID string `json:"id,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// The payment that generated this entry, when it came from one.
PaymentID string `json:"payment_id,omitempty"`
// Points added by this entry. Negative when points were spent.
Points float64 `json:"points,omitempty"`
// The settlement that generated this entry, when it came from one.
SettlementID string `json:"settlement_id,omitempty"`
// When the entry was recorded.
Time time.Time `json:"time,omitzero"`
// What moved the money or the points, for example a deposit, a trade fee, a
// referral, or a manual adjustment. Each endpoint returns only its own subset
// of these. One of: "deposit", "withdrawal", "settlement", "fee",
// "fee_refund", "maker_rebate", "casino", "adjustment", "loyalty",
// "loyalty_points_rollup", "loyalty_points_referral".
Type string `json:"type,omitempty"`
}
FeeTransaction: One fee charged against the account, or a refund of one.
type Fill ¶
type Fill struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// The action of the trade relative to the user. One of: "buy", "sell".
Action string `json:"action,omitempty"`
// Internal. Operator audit trail, not part of the supported contract; do not
// depend on it.
AdminLog map[string]any `json:"admin_log,omitempty"`
// True if STX has amended this trade. When true, compare `original_price` and
// `original_filled` against the current values.
Amended bool `json:"amended,omitempty"`
// The client order id of the order that produced this trade, when one was
// supplied.
ClientOrderID string `json:"client_order_id,omitempty"`
// The number of contracts closed on this trade. Quantity as a decimal string,
// exactly as sent by the API.
ClosedContracts Decimal `json:"closed_contracts,omitempty"`
// The fee the user paid when closing the trade. In dollars. Money as a decimal
// string, exactly as sent by the API.
ClosedFee Decimal `json:"closed_fee,omitempty"`
// Realized profit or loss on the closed portion. Negative for a loss. In
// dollars. Money as a decimal string, exactly as sent by the API.
ClosedNetPnL Decimal `json:"closed_net_pnl,omitempty"`
// The profit or loss the user made by closing the trade. In dollars. Money as
// a decimal string, exactly as sent by the API.
ClosedPnL Decimal `json:"closed_pnl,omitempty"`
// The amount of contracts (in position) that the trade is closing. Quantity as
// a decimal string, exactly as sent by the API.
Closing Decimal `json:"closing,omitempty"`
// The device associated with this trade.
DeviceID string `json:"device_id,omitempty"`
// Number of contracts settled when market expired. Quantity as a decimal
// string, exactly as sent by the API.
ExpiredContracts Decimal `json:"expired_contracts,omitempty"`
// The fee paid by the user when the market expired. In dollars. Money as a
// decimal string, exactly as sent by the API.
ExpiredFee Decimal `json:"expired_fee,omitempty"`
// Realized profit or loss on the expired portion. In dollars. Money as a
// decimal string, exactly as sent by the API.
ExpiredNetPnL Decimal `json:"expired_net_pnl,omitempty"`
// The profit or loss on the trade when the market expired. In dollars. Money
// as a decimal string, exactly as sent by the API.
ExpiredPnL Decimal `json:"expired_pnl,omitempty"`
// When the trade expires if the market has not settled, as UNIX microseconds.
ExpiresAt int64 `json:"expires_at,omitempty"`
// The number of contracts that were traded. Quantity as a decimal string,
// exactly as sent by the API.
Filled Decimal `json:"filled,omitempty"`
// The gross PNL as a result of the trade. In dollars. Money as a decimal
// string, exactly as sent by the API.
GrossPnL Decimal `json:"gross_pnl,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The IP address associated with this trade
IPAddress string `json:"ip_address,omitempty"`
// When STX last amended this trade, as UNIX microseconds. Null unless
// `amended` is true.
LastModifiedAt int64 `json:"last_modified_at,omitempty"`
// Internal. Operator audit field, not part of the supported contract; do not
// depend on it.
LastModifiedByAdminID string `json:"last_modified_by_admin_id,omitempty"`
// Whether the associated order was the `provider` or the `taker` of the
// liquidity. One of: "provider", "taker".
LiquidityAction string `json:"liquidity_action,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// When the position opened, as UNIX microseconds.
OpenedAt int64 `json:"opened_at,omitempty"`
// The ID of the order that caused the trade.
OrderID string `json:"order_id,omitempty"`
// Contracts filled at execution, before any amendment. Quantity as a decimal
// string, exactly as sent by the API.
OriginalFilled Decimal `json:"original_filled,omitempty"`
// The amount of premium received for the original trade. In dollars. Money as
// a decimal string, exactly as sent by the API.
OriginalPremium Decimal `json:"original_premium,omitempty"`
// Fill price at execution. Unchanged by later amendments. In dollars. Money as
// a decimal string, exactly as sent by the API.
OriginalPrice Decimal `json:"original_price,omitempty"`
// The original risk introduced for the original trade excluding `closed`. In
// dollars. Money as a decimal string, exactly as sent by the API.
OriginalRisk Decimal `json:"original_risk,omitempty"`
// The original gain if the position wins, for the trade excluding `closed`. In
// dollars. Money as a decimal string, exactly as sent by the API.
OriginalToWin Decimal `json:"original_to_win,omitempty"`
// The amount of premium per contract. In dollars. Money as a decimal string,
// exactly as sent by the API.
PcPremium Decimal `json:"pc_premium,omitempty"`
// The amount of risk per contract. In dollars. Money as a decimal string,
// exactly as sent by the API.
PcRisk Decimal `json:"pc_risk,omitempty"`
// What each contract gains if the position wins: `max_price - price` on a buy,
// `price` on a sell. In dollars. Money as a decimal string, exactly as sent by
// the API.
PcToWin Decimal `json:"pc_to_win,omitempty"`
// True if the order was placed before the event started.
PlacedPreStart bool `json:"placed_pre_start,omitempty"`
// The total number of loyalty points awarded as a result of making the trade.
Points float64 `json:"points,omitempty"`
// Whether the trade was based on pre-start activity.
PreStart bool `json:"pre_start,omitempty"`
// The price that the trade was executed at. In dollars. Money as a decimal
// string, exactly as sent by the API.
Price Decimal `json:"price,omitempty"`
// The number of unsettled contracts in the trade. Quantity as a decimal
// string, exactly as sent by the API.
Remaining Decimal `json:"remaining,omitempty"`
// The potential fee from unsettled contracts. In dollars. Money as a decimal
// string, exactly as sent by the API.
RemainingPotentialFee Decimal `json:"remaining_potential_fee,omitempty"`
// Premium as yet unsettled. In dollars. Money as a decimal string, exactly as
// sent by the API.
RemainingPremium Decimal `json:"remaining_premium,omitempty"`
// The total current risk for the trade. In dollars. Money as a decimal string,
// exactly as sent by the API.
RemainingRisk Decimal `json:"remaining_risk,omitempty"`
// What the unsettled contracts gain if the position wins. In dollars. Money as
// a decimal string, exactly as sent by the API.
RemainingToWin Decimal `json:"remaining_to_win,omitempty"`
// The timestamp when this trade's status was set to `settled`
SettledAt time.Time `json:"settled_at,omitzero"`
// Contracts already settled. Below `traded_contracts` on a partial settlement.
// Quantity as a decimal string, exactly as sent by the API.
SettledContracts Decimal `json:"settled_contracts,omitempty"`
// The number of settlements where this trade is the opening trade.
SettlementsCount int64 `json:"settlements_count,omitempty"`
// Fill state. `created` once the matching engine has written the fill, `open`
// while the position is live, `settled` once it no longer contributes to a
// position, and `cancelled` if STX reversed it. One of: "created", "open",
// "settled", "cancelled".
Status string `json:"status,omitempty"`
// The ISO-8601 Date time the trade was created.
Time time.Time `json:"time,omitzero"`
// Sum of on-trade fee plus fees paid from settlements linked with the trade.
// Negative when a maker rebate exceeds the fees paid. In dollars. Money as a
// decimal string, exactly as sent by the API.
TotalFee Decimal `json:"total_fee,omitempty"`
// Per-trade fee (on-trade fee schedule). Included in total_fee. Negative for a
// maker rebate. In dollars. Money as a decimal string, exactly as sent by the
// API.
TradeFee Decimal `json:"trade_fee,omitempty"`
// Unique identifier for the trade.
TradeID string `json:"trade_id,omitempty"`
// Number of contracts in this trade. Quantity as a decimal string, exactly as
// sent by the API.
TradedContracts Decimal `json:"traded_contracts,omitempty"`
// Fee before rounding; negative for a maker rebate. Use the rounded fee for
// reconciliation. In dollars. Carries up to 9 decimal places; parse money with
// a variable-scale decimal type, not a fixed-width one. Money as a decimal
// string, exactly as sent by the API.
UnroundedTradeFee Decimal `json:"unrounded_trade_fee,omitempty"`
// Time of the last change, as UNIX microseconds.
UpdatedAt int64 `json:"updated_at,omitempty"`
// Remaining contracts including unsettled exposure. Quantity as a decimal
// string, exactly as sent by the API.
VirtualRemaining Decimal `json:"virtual_remaining,omitempty"`
}
Fill: One fill against one of your orders.
type FillsQuery ¶
type FillsQuery struct {
MarketIDs []string
OrderIDs []string
// Status is "created", "open", "settled" or "cancelled".
Status string
Limit int
Cursor string
}
FillsQuery filters PortfolioService.Fills.
type FillsSnapshot ¶
type FillsSnapshot struct {
Trades []Fill `json:"trades"`
}
FillsSnapshot is "all_trades": the fills behind your open positions.
func (*FillsSnapshot) UnmarshalJSON ¶
func (s *FillsSnapshot) UnmarshalJSON(data []byte) error
UnmarshalJSON reads the fills, taking TradeID from the channel's "id".
type ForbiddenError ¶ added in v0.2.1
type ForbiddenError struct {
// Failure reason: `terms_required` or `terms_not_delegable` for a terms
// refusal, otherwise a human-readable message.
Error string `json:"error,omitempty"`
// Present on a terms refusal: what the app should do, in plain words.
ErrorDescription string `json:"error_description,omitempty"`
// Present on a terms refusal: the STX page where the member accepts the terms,
// e.g. `<STX host>/connect/terms?client_id=<client_id>`.
TermsURL string `json:"terms_url,omitempty"`
}
ForbiddenError: The 403 failure envelope. A refusal on the member's STX terms adds `error_description` and `terms_url` to `error`.
type HandshakeError ¶
type HandshakeError struct {
// StatusCode is the HTTP status, for example 403.
StatusCode int
// Reason is the exchange's x-stx-error header, such as
// "5300 - OAuth token auth failed", when it sent one.
Reason string
}
HandshakeError is a WebSocket handshake the exchange refused with an HTTP status, for example 403 for a bad signature or a missing User-Agent.
func (*HandshakeError) Error ¶
func (e *HandshakeError) Error() string
Error returns "stx: websocket handshake refused: HTTP STATUS (REASON)".
func (*HandshakeError) Is ¶
func (e *HandshakeError) Is(target error) bool
Is matches ErrUnauthorized on 401 and ErrForbidden on 403.
type Leaderboard ¶
type Leaderboard struct {
// `all` or a sport key.
Category string `json:"category,omitempty"`
// Ranked rows, best first, at most the number of members STX shows per board
// (never more than 100). Empty for a board STX hides.
Leaderboard []LeaderboardEntry `json:"leaderboard,omitempty"`
// The metric the rows are ranked on. One of: "volume", "profit",
// "predictions", "markets", "win_rate", "biggest_win", "return", "streak".
Metric string `json:"metric,omitempty"`
// When this period's board resets: local midnight in America/New_York on the
// next boundary, as UTC. `null` for `all`, which never resets, and before the
// first snapshot.
NextResetAt time.Time `json:"next_reset_at,omitzero"`
// The period the board covers. One of: "daily", "weekly", "monthly", "yearly",
// "all".
Period string `json:"period,omitempty"`
// When this snapshot was built. `null` before the first snapshot is published.
RefreshedAt time.Time `json:"refreshed_at,omitzero"`
// Whether STX shows this board to members. `false` means the board is hidden
// and `leaderboard` is empty, not that nobody has ranked yet.
Shown bool `json:"shown,omitempty"`
}
Leaderboard: One ranked board.
type LeaderboardEntry ¶
type LeaderboardEntry struct {
// Path of the member's avatar, `/avatars/{handle}.svg`, relative to the API
// host. `null` when `handle` is `null`.
AvatarURL string `json:"avatar_url,omitempty"`
// The member's public handle. `null` for a member who has not set one.
Handle string `json:"handle,omitempty"`
// Dense rank, 1-based. Tied values share a rank.
Rank int64 `json:"rank,omitempty"`
// The sport the member traded most in the period, as a category key. On a
// sport board it is that sport. `null` when unknown.
TopSport string `json:"top_sport,omitempty"`
// Path of the sport's icon, the same category icon the apps use, relative to
// the API host. `null` when `top_sport` is `null`.
TopSportIconURL string `json:"top_sport_icon_url,omitempty"`
// The ranked value. A dollar string on money boards, an integer on count
// boards and a number from 0 to 1 on ratio boards.
Value Decimal `json:"value,omitempty"`
}
LeaderboardEntry: One ranked member.
type LeaderboardQuery ¶
type LeaderboardQuery struct {
// Period is "daily", "weekly", "monthly", "yearly" or "all".
Period string
// Category is "all" or a sport key.
Category string
// Metric is "volume", "profit", "predictions", "markets", "win_rate",
// "biggest_win", "return" or "streak". Not used by Me.
Metric string
// Limit is the number of rows. Not used by Me.
Limit int
}
LeaderboardQuery selects a board.
type LeaderboardRank ¶
type LeaderboardRank struct {
// Rank is the dense rank, 1-based.
Rank int64 `json:"rank"`
// Value is the value ranked on.
Value Decimal `json:"value"`
}
LeaderboardRank is a rank and the value ranked on, for one leaderboard metric. Value is in dollars on money metrics, a count on count metrics and a ratio between 0 and 1 on ratio metrics.
type LeaderboardService ¶
type LeaderboardService struct {
// contains filtered or unexported fields
}
LeaderboardService reads the public leaderboard and your standing. Use it through Client.Leaderboard. Where the exchange has no leaderboard, its methods return an error matching ErrNotAvailable.
func (*LeaderboardService) Get ¶
func (s *LeaderboardService) Get(ctx context.Context, q *LeaderboardQuery) (*Leaderboard, error)
Get returns ranked members for a period, sport and metric (GET /api/v1/leaderboard). Rows carry a public handle and avatar, never an account id.
func (*LeaderboardService) Me ¶
func (s *LeaderboardService) Me(ctx context.Context, q *LeaderboardQuery) (*LeaderboardStanding, error)
Me returns your own standing, including your rank outside the shown list (GET /api/v1/leaderboard/me). Only Period and Category are used.
type LeaderboardStanding ¶
type LeaderboardStanding struct {
// Your rank and biggest single-market win; `null` when unranked or the board
// is hidden.
BiggestWin *LeaderboardRank `json:"biggest_win,omitempty"`
// The category asked for.
Category string `json:"category,omitempty"`
// Your rank and markets settled; `null` when unranked or the board is hidden.
Markets *LeaderboardRank `json:"markets,omitempty"`
// Whether you appear on public boards. `false` is why every rank is `null` for
// an opted-out member.
OptedIn bool `json:"opted_in,omitempty"`
// The period asked for. One of: "daily", "weekly", "monthly", "yearly", "all".
Period string `json:"period,omitempty"`
// Your rank and contracts settled; `null` when unranked or the board is
// hidden.
Predictions *LeaderboardRank `json:"predictions,omitempty"`
// Your rank and net profit; `null` when unranked or the board is hidden.
Profit *LeaderboardRank `json:"profit,omitempty"`
// Your rank and return (profit / volume), `0.0`-`1.0`; needs $500 of volume;
// `null` when unranked or the board is hidden.
Return *LeaderboardRank `json:"return,omitempty"`
// Markets decided (won or lost) in the period. `0` when unranked.
SettledMarkets int64 `json:"settled_markets,omitempty"`
// Your rank and longest winning streak; `null` when unranked or the board is
// hidden.
Streak *LeaderboardRank `json:"streak,omitempty"`
// Your rank and notional traded; `null` when unranked or the board is hidden.
Volume *LeaderboardRank `json:"volume,omitempty"`
// Share of decided markets you won, `0.0`-`1.0`. `null` until at least 10
// markets have been decided in the period; a market settled at zero profit is
// neither a win nor a loss.
WinRate float64 `json:"win_rate,omitempty"`
// Your rank and win rate, `0.0`-`1.0`; needs 10 decided markets to rank;
// `null` when unranked or the board is hidden.
WinRateRank *LeaderboardRank `json:"win_rate_rank,omitempty"`
}
LeaderboardStanding: Your standing in one period and category.
type Market ¶
type Market struct {
// Whether the market is archived.
Archived bool `json:"archived,omitempty"`
// The top bids on the market, sorted by price descending, so the best
// (highest) bid is first.
Bids []BookLevel `json:"bids,omitempty"`
// The text to use in describing the competition, e.g. NBA.
Competition string `json:"competition,omitempty"`
// The description of the market.
Description string `json:"description,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The short title of the event associated with the market.
EventShortTitle string `json:"event_short_title,omitempty"`
// The UTC start date and time of the event.
EventStart time.Time `json:"event_start,omitzero"`
// The status of the event that the market is attached to.
EventStatus string `json:"event_status,omitempty"`
// The title of the event associated with the market.
EventTitle string `json:"event_title,omitempty"`
// The type of event associated with the market.
EventType string `json:"event_type,omitempty"`
// Whether the market is featured.
Featured bool `json:"featured,omitempty"`
// Whether the market is featured on the home page.
FeaturedHome bool `json:"featured_home,omitempty"`
// The categorizations under which the market appears. A list, not an object.
Filters []MarketFilter `json:"filters,omitempty"`
// The human readable group title for the market.
GroupTitle string `json:"group_title,omitempty"`
// Identity of the set of mutually exclusive outcomes this market prices
// against: the 30 World Series contracts, the 4 AFC East contracts, one
// fixture's moneyline pair. Opaque: compare for equality, never parse. Stable
// for the life of the market, and present in every status, so it is the field
// to map market data on. Unlike `symbol`, it does not move when a fixture is
// rescheduled.
GroupingID string `json:"grouping_id,omitempty"`
// The grouping in words, e.g. `AL East Division`, `Spread - 1st Quarter`.
// Descriptive rather than stable: for a tournament it is the event title,
// which can be renamed. Display it; join on `grouping_id`.
GroupingName string `json:"grouping_name,omitempty"`
// The category in which the market appears: `Upcoming`, `Live` or `null`.
HomeCategory string `json:"home_category,omitempty"`
// The order delay (in seconds) when the event is in progress.
InPlayDelaySec int64 `json:"in_play_delay_sec,omitempty"`
// The keywords that are set for the market.
Keywords []string `json:"keywords,omitempty"`
// The time that the last probability update was received by the server. UNIX
// microseconds.
LastProbabilityAt int64 `json:"last_probability_at,omitempty"`
// The price of the last executed trade. In dollars. Money as a decimal string,
// exactly as sent by the API.
LastTradedPrice Decimal `json:"last_traded_price,omitempty"`
// `true` when the probability was set by hand, `false` when it came from the
// pricing feed. A flag, not a probability figure.
ManualProbability bool `json:"manual_probability,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// The contract rules document for this market, as a PDF, the same version as
// `rules_version`. `null` where rules documents are not published, or before
// one takes effect.
MarketRulesPdfURL string `json:"market_rules_pdf_url,omitempty"`
// The settlement value of one winning contract, and the ceiling on order
// prices: an order must price strictly below it. Read it per market. In
// dollars. Money as a decimal string, exactly as sent by the API.
MaxPrice Decimal `json:"max_price,omitempty"`
// The top offers on the market, sorted by price descending, so the best
// (lowest) offer is last.
Offers []BookLevel `json:"offers,omitempty"`
// Current open interest in the market. In contracts. Quantity as a decimal
// string, exactly as sent by the API.
OpenInterest Decimal `json:"open_interest,omitempty"`
// The participants of the market's event, as an array.
Participants []map[string]any `json:"participants,omitempty"`
// The cost of each loyalty point for amount risked by the user.
PointsCost int64 `json:"points_cost,omitempty"`
// Text describing the position this market takes, e.g. a participant name. A
// label, not a numeric ordering.
Position string `json:"position,omitempty"`
// The provider used to result this market, or `null` when there is none.
PoweredBy map[string]any `json:"powered_by,omitempty"`
// The market price that the market is trading at. In dollars. Money as a
// decimal string, exactly as sent by the API.
Price Decimal `json:"price,omitempty"`
// The change in price over the last 24 hours, as a percentage. Not money: it
// stays a number and must not be divided by 100.
PriceChange24h int64 `json:"price_change24h,omitempty"`
// The market's probability of the outcome, between 0 and 1.
Probability float64 `json:"probability,omitempty"`
// The question that the market is asking.
Question string `json:"question,omitempty"`
// The last 15 trades on the market.
RecentTrades []RecentTrade `json:"recent_trades,omitempty"`
// The result of the market.
Result string `json:"result,omitempty"`
// The rules for this market.
Rules string `json:"rules,omitempty"`
// The version number of the contract rules document in force for this market.
// `null` where rules documents are not published, or before one takes effect.
RulesVersion int64 `json:"rules_version,omitempty"`
// When the market was resulted or voided. A raw microsecond integer, unlike
// the ISO-8601 `timestamp` and `event_start` beside it. UNIX microseconds.
SettledAt int64 `json:"settled_at,omitempty"`
// The human readable short title for the market.
ShortTitle string `json:"short_title,omitempty"`
// The specifier for the rules to properly determine the market.
Specifier string `json:"specifier,omitempty"`
// The text to use in describing the sport, e.g. Basketball.
Sport string `json:"sport,omitempty"`
// The stat line this market is derived from, or `null` for a market that is
// not a stat-line prop.
StatDetail *StatDetail `json:"stat_detail,omitempty"`
// Market state. See [Market and order status](/concepts/market-status/). Note
// that a market with `status: open` may still report as suspended when trading
// is halted. One of: "scheduled", "pre_open", "open", "suspended", "closed",
// "resulted", "cancelled", "voided".
Status string `json:"status,omitempty"`
// A unique symbol for this market.
Symbol string `json:"symbol,omitempty"`
// Server time when this payload was generated, as an ISO-8601 string. The
// `timestamp_int` sibling carries the same instant as UNIX microseconds.
Timestamp time.Time `json:"timestamp,omitzero"`
// The UNIX microseconds timestamp of when this market info was created.
TimestampInt int64 `json:"timestamp_int,omitempty"`
// The human readable title for the market.
Title string `json:"title,omitempty"`
// Contracts traded on this market across its lifetime. Quantity as a decimal
// string, exactly as sent by the API.
TotalVolume Decimal `json:"total_volume,omitempty"`
// Whether the market is accepting orders right now.
Trading bool `json:"trading,omitempty"`
// The categorizations used for organizing trades, settlements and related
// items. A list, not an object.
TradingFilters []MarketFilter `json:"trading_filters,omitempty"`
// Trade volume this market has had in the last 24 hours. In contracts.
// Quantity as a decimal string, exactly as sent by the API.
Volume24h Decimal `json:"volume24h,omitempty"`
}
Market: A market you can trade, with its book and event context.
type MarketBook ¶
type MarketBook struct {
Bids []MarketBookLevel `json:"b"`
Offers []MarketBookLevel `json:"o"`
}
MarketBook is the book on market:<id>.
type MarketBookLevel ¶
type MarketBookLevel struct {
Price Decimal `json:"p"`
Quantity Decimal `json:"q"`
Liquidity Decimal `json:"l"`
TotalQuantity Decimal `json:"tc"`
TotalLiquidity Decimal `json:"tl"`
}
MarketBookLevel is one level of the book on market:<id>: price, quantity, liquidity, and the cumulative quantity and liquidity.
type MarketChange ¶
type MarketChange struct {
MarketID string `json:"market_id"`
Symbol string `json:"symbol"`
Title string `json:"title"`
ShortTitle string `json:"short_title"`
Status string `json:"status"`
Result string `json:"result"`
Trading *bool `json:"trading"`
Rules string `json:"rules"`
EventID string `json:"event_id"`
EventStatus string `json:"event_status"`
EventBrief string `json:"event_brief"`
DetailedEventBrief string `json:"detailed_event_brief"`
EventStart int64 `json:"event_start"`
SettledAt string `json:"settled_at"`
MaxPrice Decimal `json:"max_price"`
Price Decimal `json:"price"`
LastTradedPrice Decimal `json:"last_traded_price"`
TotalVolume Decimal `json:"total_volume"`
Volume24h Decimal `json:"volume_24h"`
OpenInterest Decimal `json:"open_interest"`
Probability *float64 `json:"probability"`
Bids []BookLevel `json:"bids"`
Offers []BookLevel `json:"offers"`
Book *MarketBook `json:"ob"`
Timestamp string `json:"timestamp"`
UnixTimestamp int64 `json:"unix_timestamp"`
// Fields holds every field sent, converted, by name.
Fields map[string]json.RawMessage `json:"-"`
}
MarketChange is a market as the markets, market_updates and market:<id> channels send it: in full when a market is created (and as the market:<id> join reply), otherwise only the fields that changed. Use Has to tell a field that is absent from one that is null. Prices are dollar strings.
func (*MarketChange) Has ¶
func (m *MarketChange) Has(field string) bool
Has reports whether the message carried field.
func (*MarketChange) UnmarshalJSON ¶
func (m *MarketChange) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the known fields and keeps every field in Fields.
type MarketChanges ¶
type MarketChanges map[string]*MarketChange
MarketChanges is a markets channel message: market id to change.
type MarketFilter ¶
type MarketFilter struct {
// Top-level category, e.g. a sport or a promotional section.
Category string `json:"category,omitempty"`
// Grouping within the section.
Grouping string `json:"grouping,omitempty"`
// Whether the categorization was assigned by hand.
Manual bool `json:"manual,omitempty"`
// Section heading this market groups under.
Section string `json:"section,omitempty"`
// Category within `category`, e.g. a competition.
Subcategory string `json:"subcategory,omitempty"`
// Grouping within `grouping`.
Subgrouping string `json:"subgrouping,omitempty"`
}
MarketFilter: One categorization this market appears under.
type MarketSeries ¶
type MarketSeries struct {
MarketID string `json:"market_id"`
Points []PricePoint `json:"points"`
}
MarketSeries is one market's price series. On "market_stats" it holds the buckets that changed (upsert them by TimestampUS); on "market_stats_snapshot" the whole series (replace it).
type MarketStat ¶
type MarketStat struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// When the record was marked as archived. `null` until the market is archived.
// UNIX microseconds.
ArchivedAt int64 `json:"archived_at,omitempty"`
// The amount of the `position` that is not reserved for pending orders. In
// contracts. Quantity as a decimal string, exactly as sent by the API.
AvailablePosition Decimal `json:"available_position,omitempty"`
// The average premium of all open contracts. In dollars. Money as a decimal
// string, exactly as sent by the API.
AverageOpenPremium Decimal `json:"average_open_premium,omitempty"`
// The total number of buy contracts that were closed. Quantity as a decimal
// string, exactly as sent by the API.
BuyContractsClosed Decimal `json:"buy_contracts_closed,omitempty"`
// The total number of buy contracts that were expired. Quantity as a decimal
// string, exactly as sent by the API.
BuyContractsExpired Decimal `json:"buy_contracts_expired,omitempty"`
// The total number of buy contracts settled in the position. Quantity as a
// decimal string, exactly as sent by the API.
BuyContractsSettled Decimal `json:"buy_contracts_settled,omitempty"`
// The total number of buy contracts the account has traded. Only opening
// trade's contracts are included. Quantity as a decimal string, exactly as
// sent by the API.
BuyContractsTraded Decimal `json:"buy_contracts_traded,omitempty"`
// The order liability on this position from buy orders. In dollars. Money as a
// decimal string, exactly as sent by the API.
BuyOrderLiability Decimal `json:"buy_order_liability,omitempty"`
// Count of all buy orders.
BuyOrders int64 `json:"buy_orders,omitempty"`
// The original risk incurred by buy trades. In dollars. Money as a decimal
// string, exactly as sent by the API.
BuyOriginalRisk Decimal `json:"buy_original_risk,omitempty"`
// Count of all settlements from buy trades.
BuySettlements int64 `json:"buy_settlements,omitempty"`
// The total number of buy trades the account has made on the market.
BuyTradeCount int64 `json:"buy_trade_count,omitempty"`
// Sum of all not matched contracts in buy cancelled orders. Quantity as a
// decimal string, exactly as sent by the API.
CancelledBuyContracts Decimal `json:"cancelled_buy_contracts,omitempty"`
// Number of buy orders that were cancelled.
CancelledBuyOrders int64 `json:"cancelled_buy_orders,omitempty"`
// Sum of all not matched contracts in all cancelled orders. Quantity as a
// decimal string, exactly as sent by the API.
CancelledContracts Decimal `json:"cancelled_contracts,omitempty"`
// Number of orders that were cancelled.
CancelledOrders int64 `json:"cancelled_orders,omitempty"`
// Sum of all not matched contracts in sell cancelled orders. Quantity as a
// decimal string, exactly as sent by the API.
CancelledSellContracts Decimal `json:"cancelled_sell_contracts,omitempty"`
// Number of sell orders that were cancelled.
CancelledSellOrders int64 `json:"cancelled_sell_orders,omitempty"`
// Total premium from closed buy trade contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
ClosedBuyPremium Decimal `json:"closed_buy_premium,omitempty"`
// The total value of fees from closed settlements. In dollars. Money as a
// decimal string, exactly as sent by the API.
ClosedFees Decimal `json:"closed_fees,omitempty"`
// The profit or loss the account has made in `closed` settlements. In dollars.
// Money as a decimal string, exactly as sent by the API.
ClosedGrossPnL Decimal `json:"closed_gross_pnl,omitempty"`
// The net profit or loss after subtracting `closed_fees`. In dollars. Money as
// a decimal string, exactly as sent by the API.
ClosedNetPnL Decimal `json:"closed_net_pnl,omitempty"`
// Total premium from closed contracts. In dollars. Money as a decimal string,
// exactly as sent by the API.
ClosedPremium Decimal `json:"closed_premium,omitempty"`
// Total premium from closed sell trade contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
ClosedSellPremium Decimal `json:"closed_sell_premium,omitempty"`
// The competition of this market
Competition string `json:"competition,omitempty"`
// The total number of all contracts that were closed. Quantity as a decimal
// string, exactly as sent by the API.
ContractsClosed Decimal `json:"contracts_closed,omitempty"`
// The total number of all contracts that were expired. Quantity as a decimal
// string, exactly as sent by the API.
ContractsExpired Decimal `json:"contracts_expired,omitempty"`
// Sum of all not matched contracts in buy orders. Quantity as a decimal
// string, exactly as sent by the API.
ContractsInBuyOrders Decimal `json:"contracts_in_buy_orders,omitempty"`
// Sum of all unmatched contracts in all orders: each order's `quantity` minus
// its `filled`. Quantity as a decimal string, exactly as sent by the API.
ContractsInOrders Decimal `json:"contracts_in_orders,omitempty"`
// Sum of all not matched contracts in sell orders. Quantity as a decimal
// string, exactly as sent by the API.
ContractsInSellOrders Decimal `json:"contracts_in_sell_orders,omitempty"`
// The number of contracts that have been settled. Quantity as a decimal
// string, exactly as sent by the API.
ContractsSettled Decimal `json:"contracts_settled,omitempty"`
// The total number of contracts traded (the sum of each fill's `filled`). Only
// opening trades' contracts are counted, not contracts closing other trades.
// Quantity as a decimal string, exactly as sent by the API.
ContractsTraded Decimal `json:"contracts_traded,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The start time of the event. UNIX microseconds.
EventStartTime int64 `json:"event_start_time,omitempty"`
// Total premium from expired buy trade contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
ExpiredBuyPremium Decimal `json:"expired_buy_premium,omitempty"`
// The total value of fees from expired settlements. In dollars. Money as a
// decimal string, exactly as sent by the API.
ExpiredFees Decimal `json:"expired_fees,omitempty"`
// The profit or loss the account has made in `expired` settlements. In
// dollars. Money as a decimal string, exactly as sent by the API.
ExpiredGrossPnL Decimal `json:"expired_gross_pnl,omitempty"`
// The net profit or loss after subtracting `expired_fees`. In dollars. Money
// as a decimal string, exactly as sent by the API.
ExpiredNetPnL Decimal `json:"expired_net_pnl,omitempty"`
// Total premium from expired contracts. In dollars. Money as a decimal string,
// exactly as sent by the API.
ExpiredPremium Decimal `json:"expired_premium,omitempty"`
// Total premium from expired sell trade contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
ExpiredSellPremium Decimal `json:"expired_sell_premium,omitempty"`
// Internal. Virtual field naming the fee module in use, not part of the
// supported contract.
FeePlugin string `json:"fee_plugin,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// When the last settlement was created. UNIX microseconds.
LastSettledAt int64 `json:"last_settled_at,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// The market's maximum price: the settlement value of one winning contract. In
// dollars. Money as a decimal string, exactly as sent by the API.
MarketMaxPrice Decimal `json:"market_max_price,omitempty"`
// Worst-case loss if this market settles against the position you hold. In
// dollars. Money as a decimal string, exactly as sent by the API.
MaxLiabilityLoss Decimal `json:"max_liability_loss,omitempty"`
// Worst-case loss if this market settles in favor of the position you hold. In
// dollars. Money as a decimal string, exactly as sent by the API.
MaxLiabilityWin Decimal `json:"max_liability_win,omitempty"`
// The maximum potential fees including all actual fees paid. In dollars. Money
// as a decimal string, exactly as sent by the API.
MaxPotentialFee Decimal `json:"max_potential_fee,omitempty"`
// The maximum potential profit, including all actual profit. In dollars. Money
// as a decimal string, exactly as sent by the API.
MaxPotentialProfit Decimal `json:"max_potential_profit,omitempty"`
// The total amount of risk on unsettled contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
MaxRisk Decimal `json:"max_risk,omitempty"`
// Internal. Consistency flag used by position rebuilds, not part of the
// supported contract.
NeedsRebuild bool `json:"needs_rebuild,omitempty"`
// The number of open orders the account has on the market.
OpenOrderCount int64 `json:"open_order_count,omitempty"`
// The amount of potential fee that is related to unsettled contracts. In
// dollars. Money as a decimal string, exactly as sent by the API.
OpenPotentialFee Decimal `json:"open_potential_fee,omitempty"`
// The potential profit from the outstanding contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
OpenPotentialProfit Decimal `json:"open_potential_profit,omitempty"`
// Total premium on the user's current position in the market. In dollars.
// Money as a decimal string, exactly as sent by the API.
OpenPremium Decimal `json:"open_premium,omitempty"`
// The amount of risk associated with outstanding contracts. In dollars. Money
// as a decimal string, exactly as sent by the API.
OpenRisk Decimal `json:"open_risk,omitempty"`
// The number of open trades the account has on the market.
OpenTradeCount int64 `json:"open_trade_count,omitempty"`
// The order liability on this position from all orders. In dollars. Money as a
// decimal string, exactly as sent by the API.
OrderLiability Decimal `json:"order_liability,omitempty"`
// Count of all orders.
Orders int64 `json:"orders,omitempty"`
// The original risk incurred by all trades. In dollars. Money as a decimal
// string, exactly as sent by the API.
OriginalRisk Decimal `json:"original_risk,omitempty"`
// Fees that would be charged if the resting close orders all filled. In
// dollars. Money as a decimal string, exactly as sent by the API.
PendingCloseFee Decimal `json:"pending_close_fee,omitempty"`
// Profit or loss that would be realized if the resting close orders all
// filled. In dollars. Money as a decimal string, exactly as sent by the API.
PendingClosePnL Decimal `json:"pending_close_pnl,omitempty"`
// The numerical position of the account in the market. In contracts. Quantity
// as a decimal string, exactly as sent by the API.
Position Decimal `json:"position,omitempty"`
// Internal. Links to a position-accountability alert, not part of the
// supported contract.
PositionAccountabilityAlertID string `json:"position_accountability_alert_id,omitempty"`
// The liability of the position that affects available balance. In dollars.
// Money as a decimal string, exactly as sent by the API.
PositionPremiumLiability Decimal `json:"position_premium_liability,omitempty"`
// Fees that would be charged if every open order on this market filled. In
// dollars. Money as a decimal string, exactly as sent by the API.
PotentialOrderTradeFee Decimal `json:"potential_order_trade_fee,omitempty"`
// Number of buy orders that were rejected.
RejectedBuyOrders int64 `json:"rejected_buy_orders,omitempty"`
// Number of orders that were rejected.
RejectedOrders int64 `json:"rejected_orders,omitempty"`
// Number of sell orders that were rejected.
RejectedSellOrders int64 `json:"rejected_sell_orders,omitempty"`
// The total number of sell contracts that were closed. Quantity as a decimal
// string, exactly as sent by the API.
SellContractsClosed Decimal `json:"sell_contracts_closed,omitempty"`
// The total number of sell contracts that were expired. Quantity as a decimal
// string, exactly as sent by the API.
SellContractsExpired Decimal `json:"sell_contracts_expired,omitempty"`
// The total number of sell contracts settled in the position. Quantity as a
// decimal string, exactly as sent by the API.
SellContractsSettled Decimal `json:"sell_contracts_settled,omitempty"`
// The total number of sell contracts the account has traded in the market.
// Only opening trade's contracts are included. Quantity as a decimal string,
// exactly as sent by the API.
SellContractsTraded Decimal `json:"sell_contracts_traded,omitempty"`
// The order liability on this position from sell orders. In dollars. Money as
// a decimal string, exactly as sent by the API.
SellOrderLiability Decimal `json:"sell_order_liability,omitempty"`
// Count of all sell orders.
SellOrders int64 `json:"sell_orders,omitempty"`
// The original risk incurred by sell trades. In dollars. Money as a decimal
// string, exactly as sent by the API.
SellOriginalRisk Decimal `json:"sell_original_risk,omitempty"`
// Count of all settlements from sell trades.
SellSettlements int64 `json:"sell_settlements,omitempty"`
// The total number of sell trades the account has made on the market.
SellTradeCount int64 `json:"sell_trade_count,omitempty"`
// When the expired settlements were recorded. `null` if the market has not
// resulted or voided yet. UNIX microseconds.
SettledAt int64 `json:"settled_at,omitempty"`
// Count of all settlements from all trades.
Settlements int64 `json:"settlements,omitempty"`
// The sport of this market
Sport string `json:"sport,omitempty"`
// The status of the **market** this record covers, merged in from the live
// market index. `null` when the market is no longer held there.
Status string `json:"status,omitempty"`
// The title of the **market** this record covers, merged in from the live
// market index. `null` when the market is no longer held there.
Title string `json:"title,omitempty"`
// The total fees that have been collected on the settlements. In dollars.
// Money as a decimal string, exactly as sent by the API.
TotalFees Decimal `json:"total_fees,omitempty"`
// The liability affecting available balance from open orders and position. In
// dollars. Money as a decimal string, exactly as sent by the API.
TotalLiability Decimal `json:"total_liability,omitempty"`
// The net profit or loss after subtracting `total_fees`. In dollars. Money as
// a decimal string, exactly as sent by the API.
TotalNetPnL Decimal `json:"total_net_pnl,omitempty"`
// The total profit or loss on all settlements. In dollars. Money as a decimal
// string, exactly as sent by the API.
TotalSettlementPnL Decimal `json:"total_settlement_pnl,omitempty"`
// The total number of trades the account has made on the market.
TradeCount int64 `json:"trade_count,omitempty"`
// Time of the last change, as UNIX microseconds.
UpdatedAt int64 `json:"updated_at,omitempty"`
}
MarketStat: Your exposure and realized result in one market.
type MarketStatsQuery ¶
type MarketStatsQuery struct {
MarketIDs []string
EventIDs []string
ExcludeZeroSettlements *bool
// FromTime and ToTime bound the window, as Unix timestamps.
FromTime int64
ToTime int64
Sports []string
Competitions []string
Limit int
Cursor string
}
MarketStatsQuery filters PortfolioService.MarketStats.
type MarketStatsReply ¶
type MarketStatsReply struct {
SelectedMarketIDs []string `json:"selected_market_ids"`
Range StatsRange `json:"range"`
Markets []MarketSeries `json:"markets"`
}
MarketStatsReply is the market_stats join reply, and the reply to Subscription.RequestSeries.
type MarketType ¶
type MarketType struct {
PartnerCreate bool
// Fields are the fields an entry takes besides its rule, by wire name.
Fields map[string]MarketTypeField
// EventTypes are the event types the rule runs on, keyed by event type
// such as "NFL", with their stats.
EventTypes map[string]MarketTypeEventType
// EventTypeNames lists the event types of a rule that cannot be created.
EventTypeNames []string
}
MarketType is one market rule. PartnerCreate says whether MarketsService.Create takes it; for those, Fields and EventTypes describe an entry, and for the others EventTypeNames lists where the rule runs.
func (*MarketType) UnmarshalJSON ¶
func (m *MarketType) UnmarshalJSON(data []byte) error
UnmarshalJSON reads either shape of a market type.
type MarketTypeEventType ¶
MarketTypeEventType is the stats one event type offers.
type MarketTypeField ¶
type MarketTypeField struct {
// Type is its JSON type, such as "string" or "number".
Type string `json:"type"`
Description string `json:"description"`
}
MarketTypeField is one field a market entry takes besides its rule.
type MarketTypes ¶
type MarketTypes map[string]MarketType
MarketTypes are the market rules, keyed by rule such as "player_stat_line".
type MarketsFilter ¶
type MarketsFilter struct {
// RuleFilters keeps only markets whose rules match one of these.
RuleFilters []string
// MessageTypes picks "market_created", "market_updated" or both.
MessageTypes []string
}
MarketsFilter narrows MarketsChannel.
type MarketsQuery ¶
type MarketsQuery struct {
MarketIDs []string
EventIDs []string
// Status is one or more market statuses, such as "pre_open" and "open".
Status []string
// Trading true lists only markets accepting orders now; false only those
// that are not.
Trading *bool
Sports []string
Competitions []string
// SortBy is "event_start"; SortDirection is "asc" or "desc".
SortBy string
SortDirection string
// Limit is the page size: default 100, maximum 200.
Limit int
Cursor string
}
MarketsQuery filters MarketsService.List. Filters combine with AND; a list filter matches any of its values.
type MarketsService ¶
type MarketsService struct {
// contains filtered or unexported fields
}
MarketsService lists markets and market types, and creates markets. Use it through Client.Markets.
func (*MarketsService) All ¶
func (s *MarketsService) All(ctx context.Context, q *MarketsQuery) iter.Seq2[Market, error]
All returns every market matching q, following the cursor. q.Cursor is ignored.
Example ¶
List open markets with their best bid and offer.
package main
import (
"context"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
ctx := context.Background()
client, err := stx.New()
if err != nil {
log.Fatal(err)
}
for market, err := range client.Markets.All(ctx, &stx.MarketsQuery{Status: []string{"open"}, Trading: stx.Bool(true)}) {
if err != nil {
log.Fatal(err)
}
var bid, offer stx.Decimal
if len(market.Bids) > 0 {
bid = market.Bids[0].Price
}
if len(market.Offers) > 0 {
offer = market.Offers[len(market.Offers)-1].Price // sorted highest first
}
fmt.Printf("%s bid %s offer %s\n", market.Symbol, bid, offer)
}
}
Output:
func (*MarketsService) Create ¶
func (s *MarketsService) Create(ctx context.Context, eventID string, markets []NewMarket, opts *CreateMarketsOptions) ([]CreateMarketResult, error)
Create creates markets on a scheduled event (POST /api/v1/markets), 1 to MaxMarketsPerRequest per call. It needs an app token with markets.write, which STX grants, sent from an address on the app's IP allow-list. See https://docs.stxapp.io/apps/creating-markets/.
It returns one result per market, in order. A rejected market is a result, not an error, and resending is safe: a market already listed comes back MarketExists. A refused request is an error: a 403 without markets.write, ErrNotFound for an unknown event, ErrRejected for an event that is not open. Where the exchange cannot create markets the error matches ErrNotAvailable.
func (*MarketsService) Get ¶
Get returns one market by id. It returns an error matching ErrNotFound when there is none.
func (*MarketsService) List ¶
func (s *MarketsService) List(ctx context.Context, q *MarketsQuery) (*Page[Market], error)
List returns one page of markets (GET /api/v1/markets).
func (*MarketsService) Types ¶
func (s *MarketsService) Types(ctx context.Context) (MarketTypes, error)
Types returns the market types (GET /api/v1/types). It changes only when STX adds a rule or a stat, so read it once and keep it. It needs an API key or an OAuth app token with the events scope, and returns an error matching ErrNotAvailable where the exchange does not have it.
type Me ¶
type Me struct {
// Your account id. Trades, settlements and balances are scoped to it.
AccountID string `json:"account_id,omitempty"`
// Path of your avatar, `/avatars/{handle}.svg`, relative to the API host.
// `null` when `handle` is `null`.
AvatarURL string `json:"avatar_url,omitempty"`
// First name on the account, or `null` if no profile is loaded.
FirstName string `json:"first_name,omitempty"`
// Your public handle, shown on the leaderboard in place of your name. `null`
// until one is set.
Handle string `json:"handle,omitempty"`
// When you may next change your handle. `null` means now; otherwise the end of
// the 30-day window since the last change.
HandleChangeableAt time.Time `json:"handle_changeable_at,omitzero"`
// The id of the API key that signed this request: the value sent in the
// access-key header. `null` on a bearer request.
KeyID string `json:"key_id,omitempty"`
// Last name on the account, or `null` if no profile is loaded.
LastName string `json:"last_name,omitempty"`
// Whether you have consented to appear on public leaderboards. New accounts
// start with the jurisdiction's default; accounts from before the leaderboard
// start at `false`. Change it with `PATCH /api/v1/me/profile`.
LeaderboardOptIn bool `json:"leaderboard_opt_in,omitempty"`
// How this request authenticated: `api_key` for a signed request, `bearer` for
// a session token. One of: "api_key", "bearer".
Method string `json:"method,omitempty"`
// Access level granted to this key: `read_only`, or `read_write` for keys that
// may place and cancel orders. `null` on a bearer request. One of:
// "read_only", "read_write".
Scope string `json:"scope,omitempty"`
// Your user id. Substitute this into account channel topics such as
// `orders:{user_id}`.
UserID string `json:"user_id,omitempty"`
}
Me: The account behind the credential.
type Message ¶
type Message struct {
// Topic is the wire topic, for example "orders:7fb55544-3a7e-4f6b-bd66-fc89bd3a1087".
Topic string
// Event is the event name, for example "all_orders", "new_open_order"
// or "book".
Event string
// Payload is the event's JSON. Money and quantities are strings; on the
// markets, market_updates and market:<id> channels the stream has already
// converted the exchange's cents to dollar strings.
Payload json.RawMessage
// Snapshot is true for the state sent on join, again after every rejoin:
// "all_orders", "all_trades", "all_positions", "balances" and
// "user_updated". Replace what you hold rather than merging.
Snapshot bool
// Data is the payload decoded into the type documented for the event,
// or nil for an event the SDK does not know. Switch on its type:
//
// orderbook book *OrderbookUpdate
// ticker ticker *Ticker
// trades trade *PublicTrade
// events event *EventVolume
// markets market_created/_updated MarketChanges
// market_updates created/updated *MarketChange
// market:<id> market_update/order_book_update *MarketChange
// market_stats market_stats(_snapshot) *MarketSeries
// orders all_orders / new_open_order *OrdersSnapshot / *Order
// fills all_trades / trade *FillsSnapshot / *Fill (TradeID is the channel's "id")
// positions all_positions / updated_positions *PositionsSnapshot / *PositionsUpdate
// settlements new_settlements *SettlementsUpdate
// balances balances, update / payment_update *Balance / *PaymentUpdate
// user_info user_updated *UserInfo
// order_slip order_numbers_batch / self_match_batch *OrderNumbersBatch / *SelfMatchBatch
//
// The account channel carries the orders, fills, positions, settlements
// and balances events with the same types.
Data any
}
Message is one event pushed on a subscription.
type NewMarket ¶
type NewMarket struct {
// Rule is the market rule. Empty means RulePlayerStatLine.
Rule string `json:"rule"`
// PlayerID is from [EventsService.Players].
PlayerID string `json:"player_id"`
// Stat is one of the event's stats, such as "POINTS".
Stat string `json:"stat"`
// Line is a positive number ending in .5, such as 18.5. Whole and
// quarter lines, zero and negatives are rejected (invalid_line).
Line float64 `json:"line"`
}
NewMarket is one market to create. It is also the request echoed back in each CreateMarketResult.
type NotAvailableError ¶
type NotAvailableError struct {
// Feature is a stable id: "combos", "markets.create", "market_types",
// "event_players", "leaderboard", "oauth", "oauth.member", "oauth.app",
// "connect", "terms.stx_page", "loyalty", "orders.post_only",
// "orders.fill_or_kill", or "scope:<name>".
Feature string
// Host is the exchange that lacks it, for example "demo.stxapp.ca".
Host string
// Err is the answer the decision came from, when there was one.
Err error
}
NotAvailableError reports a feature this exchange does not have yet. It matches ErrNotAvailable.
func (*NotAvailableError) Error ¶
func (e *NotAvailableError) Error() string
Error returns a sentence such as "stx: Combos are not available on demo.stxapp.ca yet."
func (*NotAvailableError) Is ¶
func (e *NotAvailableError) Is(target error) bool
Is matches ErrNotAvailable.
func (*NotAvailableError) Unwrap ¶
func (e *NotAvailableError) Unwrap() error
Unwrap returns the underlying answer, if any.
type Option ¶
type Option func(*options) error
Option configures a Client.
func WithAuth ¶
WithAuth authenticates with any Auth instead of an API key, such as an OAuth bearer token from the oauth package.
func WithCredentialsFile ¶
WithCredentialsFile reads profiles from path instead of ~/.stx/credentials.
func WithEnvironment ¶
func WithEnvironment(e Environment) Option
WithEnvironment selects a published environment, such as USDemo. WithHost still wins over it.
func WithEnvironmentName ¶
WithEnvironmentName selects a published environment by name, such as "us-demo" or "ontario-production".
func WithHTTPClient ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithLogger logs requests, retries and stream events at debug level.
func WithProfile ¶
WithProfile reads the named section of ~/.stx/credentials.
Example ¶
A client from the "us-demo" section of ~/.stx/credentials.
package main
import (
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
fmt.Println(client.Host())
}
Output:
func WithRegion ¶
WithRegion selects the host by region ("us" or "ontario") and env ("demo" or "production"; "prod" and "live" are accepted).
func WithResponseHook ¶
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 ¶
func WithRetry(p RetryPolicy) Option
WithRetry sets the retry policy; NoRetry turns retries off.
func WithSigner ¶
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 ¶
WithTimeout sets the time limit for each HTTP attempt. Default 30 s.
func WithUserAgent ¶
WithUserAgent appends product to the User-Agent header, for example "my-app/1.2".
type Order ¶
type Order struct {
// When the matching engine accepted the order. `null` while the order is still
// pending. UNIX microseconds.
AcceptedAt int64 `json:"accepted_at,omitempty"`
// The action of the order, either `buy` or `sell`. One of: "buy", "sell".
Action string `json:"action,omitempty"`
// Order size in dollars, for an order entered by amount rather than by
// contract quantity. `null` for orders placed through this API, which always
// take a quantity. Money as a decimal string, exactly as sent by the API.
Amount Decimal `json:"amount,omitempty"`
// Volume-weighted average fill price. `null` until the order has its first
// fill. In dollars. Money as a decimal string, exactly as sent by the API.
AvgPrice Decimal `json:"avg_price,omitempty"`
// The cancellation reason, if the order was cancelled.
CancellationReason string `json:"cancellation_reason,omitempty"`
// Your own identifier, echoed back unchanged, or `null` if you sent none. A
// free-form string, not a UUID, and set by REST and FIX callers alike.
ClientOrderID string `json:"client_order_id,omitempty"`
// The extended deadline for a delayed order. UNIX microseconds.
DelayedUntil int64 `json:"delayed_until,omitempty"`
// The device from which this order was placed.
DeviceID string `json:"device_id,omitempty"`
// The expiration condition for the order. One of: "good_till_start",
// "good_till_time".
Expiration string `json:"expiration,omitempty"`
// The expiration time for time-based expiration. UNIX microseconds.
ExpirationTime int64 `json:"expiration_time,omitempty"`
// When the contracts this order trades expire, as UNIX microseconds: the
// market's expiration, copied onto the order when it is placed. `null` when
// the market has no event. Not the same as `expiration_time`.
ExpiresAt int64 `json:"expires_at,omitempty"`
// How the order matches: `normal`, `post_only` or `fill_or_kill` for a limit
// order you placed, `cancel_unfilled` for a market order, `rfq` or `quote` for
// an order of a combination bind.
FillMode string `json:"fill_mode,omitempty"`
// Contracts filled so far. Compare with `quantity` to get remaining size.
// Quantity as a decimal string, exactly as sent by the API.
Filled Decimal `json:"filled,omitempty"`
// The portion of `amount` that has been filled. In dollars. Money as a decimal
// string, exactly as sent by the API.
FilledAmount Decimal `json:"filled_amount,omitempty"`
// The percentage of the contracts on the order that have been filled. A
// percentage, not money.
FilledPercentage int64 `json:"filled_percentage,omitempty"`
// True if the order arrived over FIX rather than REST.
FixOrder bool `json:"fix_order,omitempty"`
// Unique identifier for the record.
ID string `json:"id,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The IP address from which this order was placed.
IPAddress string `json:"ip_address,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// Legacy. The odds format (`decimal` or `american`) an order was entered in on
// an STX app. `null` for orders placed through this API.
OddsType string `json:"odds_type,omitempty"`
// Legacy. The odds an order was entered at on an STX app, as a string. `null`
// for orders placed through this API.
OddsValue string `json:"odds_value,omitempty"`
// The type of order, either `limit` or `market`. One of: "limit", "market".
OrderType string `json:"order_type,omitempty"`
// Whether the order was placed before the event started.
PlacedPreStart bool `json:"placed_pre_start,omitempty"`
// Limit price, below the market's `max_price`; read that per market rather
// than assuming a ceiling. Absent for market orders. In dollars. Carries up to
// 7 decimal places; parse money with a variable-scale decimal type, not a
// fixed-width one. Money as a decimal string, exactly as sent by the API.
Price Decimal `json:"price,omitempty"`
// Order size in contracts. Quantity as a decimal string, exactly as sent by
// the API.
Quantity Decimal `json:"quantity,omitempty"`
// The rejection reason, if the order was rejected.
RejectionReason string `json:"rejection_reason,omitempty"`
// Order state, one of nine. See [Market and order
// status](/concepts/market-status/#order-statuses) for the full set and which
// are terminal. One of: "created", "requested", "accepted", "delayed", "open",
// "filled", "rejected", "cancelled", "partially_cancelled".
Status string `json:"status,omitempty"`
// The ISO-8601 timestamp of the time the order was placed.
Time time.Time `json:"time,omitzero"`
// Total premium across all fills on this order. In dollars. Money as a decimal
// string, exactly as sent by the API.
TotalValue Decimal `json:"total_value,omitempty"`
}
Order: An order resting on, or already matched against, the exchange book.
type OrderNumbers ¶
type OrderNumbers struct {
Ref string `json:"ref"`
MarketID string `json:"market_id"`
SelfMatch bool `json:"self_match"`
Risk Decimal `json:"risk"`
Fee Decimal `json:"fee"`
RiskWithFee Decimal `json:"risk_with_fee"`
FillQty Decimal `json:"fill_qty"`
UnfilledQty Decimal `json:"unfilled_qty"`
FillLevels []OrderSlipFill `json:"est_fill_at_price"`
}
OrderNumbers is one entry's projected cost.
type OrderNumbersBatch ¶
type OrderNumbersBatch struct {
Updates []OrderNumbers `json:"updates"`
}
OrderNumbersBatch is "order_numbers_batch": every entry whose numbers changed.
type OrderRequest ¶
type OrderRequest struct {
MarketID string `json:"market_id"`
// Action is [Buy] or [Sell].
Action string `json:"action"`
// OrderType is [Limit] or [MarketOrder].
OrderType string `json:"order_type"`
// Quantity is the number of contracts, such as "100". Required.
Quantity Decimal `json:"quantity"`
// Price is in dollars, such as "0.58". Required for a limit order.
Price Decimal `json:"price,omitempty"`
// ClientOrderID is your own reference, echoed back. Set it so you can
// look an order up after a timeout: a POST is never retried.
ClientOrderID string `json:"client_order_id,omitempty"`
// Expiration is [GoodTillStart] or [GoodTillTime].
Expiration string `json:"expiration,omitempty"`
// ExpirationTime is Unix microseconds, with Expiration GoodTillTime.
ExpirationTime int64 `json:"expiration_time,omitempty"`
// CancelOnDisconnect cancels the order if the orders channel stops
// heartbeating.
CancelOnDisconnect *bool `json:"cancel_on_disconnect,omitempty"`
DeviceID string `json:"device_id,omitempty"`
// FillMode is how a limit order matches: [FillNormal] (the default),
// [PostOnly] or [FillOrKill]. An exchange that has not enabled the mode
// rejects the order, and the call returns a *[NotAvailableError].
FillMode string `json:"fill_mode,omitempty"`
}
OrderRequest is one new order.
type OrderSlip ¶
type OrderSlip struct {
// contains filtered or unexported fields
}
OrderSlip costs orders before you place them, on order_slip:<user_id>. Register an order with Add and the exchange sends what it would cost (risk, fee, how much would fill now and at which prices) as an "order_numbers_batch", then again every time the book moves. Nothing is placed. Get one with Stream.OrderSlip.
Entries live as long as the topic: after a reconnect the stream rejoins, but you add your entries again. The protocol is at https://docs.stxapp.io/websockets/channels/order-slip/.
func (*OrderSlip) Add ¶
func (o *OrderSlip) Add(ctx context.Context, e OrderSlipEntry) (OrderSlipRef, error)
Add registers an entry and returns its ref. Its first numbers arrive on OrderSlip.Messages at once.
func (*OrderSlip) Done ¶
func (o *OrderSlip) Done() <-chan struct{}
Done is closed when the slip ends.
func (*OrderSlip) Err ¶
Err returns why the slip ended, like Subscription.Err.
func (*OrderSlip) Messages ¶
Messages returns the channel the projections arrive on, with Data a *OrderNumbersBatch or a *SelfMatchBatch.
type OrderSlipEntry ¶
type OrderSlipEntry struct {
MarketID string `json:"market_id"`
// Side is "buy" or "sell".
Side string `json:"side"`
// Quantity is the contracts you are considering.
Quantity Decimal `json:"qty"`
// MaxPrice is the market's max price in dollars, for example "1".
MaxPrice Decimal `json:"max_price"`
// LimitPrice is your limit in dollars; leave it empty for a market order.
LimitPrice Decimal `json:"limit_price,omitempty"`
}
OrderSlipEntry is an order to cost.
type OrderSlipFill ¶
type OrderSlipFill struct {
Price Decimal `json:"price"`
Quantity Decimal `json:"qty"`
Fee Decimal `json:"fee"`
}
OrderSlipFill is one price level of an entry's immediate fill.
type OrderSlipRef ¶
OrderSlipRef identifies a registered entry. SelfMatch is true when one of your own open orders is in the way, so placing it would be refused.
type OrderbookLevel ¶
type OrderbookLevel struct {
Price Decimal `json:"price"`
Quantity Decimal `json:"quantity"`
Liquidity Decimal `json:"liquidity"`
TotalQuantity Decimal `json:"total_quantity"`
TotalLiquidity Decimal `json:"total_liquidity"`
}
OrderbookLevel is one price level of the aggregated book. Liquidity is that level alone; the totals are cumulative through it.
type OrderbookUpdate ¶
type OrderbookUpdate struct {
MarketID string `json:"market_id"`
Bids []OrderbookLevel `json:"bids"`
Offers []OrderbookLevel `json:"offers"`
Timestamp string `json:"timestamp"`
TimestampUS int64 `json:"timestamp_us"`
}
OrderbookUpdate is a "book" message: one market's whole book, best level first. Replace the book you hold.
type OrdersFilter ¶
type OrdersFilter struct {
// MarketIDs keeps only orders on these markets; empty means all.
MarketIDs []string
// CancelOnDisconnect arms cancel-on-disconnect for the orders you place
// with it. The stream then pings at a third of the timeout the exchange
// grants for as long as the topic is joined.
CancelOnDisconnect bool
// PingTimeout is the cancel-on-disconnect deadline to ask for. The
// exchange clamps it to 5s to 20s. Default 5s.
PingTimeout time.Duration
}
OrdersFilter configures OrdersChannel.
type OrdersQuery ¶
type OrdersQuery struct {
OrderIDs []string
ClientOrderIDs []string
MarketIDs []string
// Status is one or more order statuses, such as "accepted", "delayed"
// and "open".
Status []string
Limit int
Cursor string
}
OrdersQuery filters OrdersService.List.
type OrdersService ¶
type OrdersService struct {
// contains filtered or unexported fields
}
OrdersService places, lists and cancels orders. Use it through Client.Orders.
func (*OrdersService) All ¶
func (s *OrdersService) All(ctx context.Context, q *OrdersQuery) iter.Seq2[Order, error]
All returns every order matching q, following the cursor.
func (*OrdersService) Cancel ¶
func (s *OrdersService) Cancel(ctx context.Context, orderID string) (*Cancellation, error)
Cancel requests a cancel (DELETE /api/v1/orders/{order_id}). A fill already in flight can still land.
func (*OrdersService) CancelAll ¶
func (s *OrdersService) CancelAll(ctx context.Context) ([]Cancellation, error)
CancelAll cancels every order resting on the account (DELETE /api/v1/orders/all).
func (*OrdersService) CancelBatch ¶
func (s *OrdersService) CancelBatch(ctx context.Context, orderIDs []string) ([]Cancellation, error)
CancelBatch cancels the named orders (DELETE /api/v1/orders/batched).
func (*OrdersService) List ¶
func (s *OrdersService) List(ctx context.Context, q *OrdersQuery) (*Page[Order], error)
List returns one page of your orders, newest first (GET /api/v1/orders).
func (*OrdersService) Place ¶
func (s *OrdersService) Place(ctx context.Context, order OrderRequest) (*Order, error)
Place places one order (POST /api/v1/orders). The exchange validates it: a bad price step or a fractional quantity returns an error matching ErrBadRequest or ErrRejected with the API's message.
A POST is never retried after a 5xx or a dropped connection; set ClientOrderID and look the order up with OrdersService.List if that happens.
With FillMode PostOnly or FillOrKill, Place sends the order and the exchange decides: where the mode is not enabled it rejects the order and Place returns an error matching ErrNotAvailable. A market that does not take the mode, such as a combination market, returns an error matching ErrFillModeNotAllowed; a post-only order that would have matched returns a *PostOnlyWouldMatchError.
Example ¶
Place a limit order, then cancel it.
package main
import (
"context"
"errors"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
ctx := context.Background()
client, err := stx.New()
if err != nil {
log.Fatal(err)
}
order, err := client.Orders.Place(ctx, stx.OrderRequest{
MarketID: "42b861f8-8340-4046-ae06-83a0cec93456",
Action: stx.Buy,
OrderType: stx.Limit,
Price: stx.MustDecimal("0.01"),
Quantity: stx.MustDecimal("1"),
ClientOrderID: "my-order-001",
})
if errors.Is(err, stx.ErrRejected) {
log.Fatalf("refused by the exchange: %v", err)
} else if err != nil {
log.Fatal(err)
}
fmt.Println("Placed", order.ID, order.Status)
cancel, err := client.Orders.Cancel(ctx, order.ID)
if err != nil {
log.Fatal(err)
}
fmt.Println("Cancelled:", cancel.Status)
}
Output:
func (*OrdersService) PlaceBatch ¶
func (s *OrdersService) PlaceBatch(ctx context.Context, orders []OrderRequest) ([]BatchOrderResult, error)
PlaceBatch places several orders in one call (POST /api/v1/orders/batched). It returns one result per order, in order; a rejected order carries Errors and does not stop the others.
When the exchange rejects the batch because a FillMode (PostOnly or FillOrKill) is not enabled there, PlaceBatch returns an error matching ErrNotAvailable. In a batch a post-only order that would have matched comes back as its result: a cancelled Order (CancellationReason "auto_matching") or Errors.
type OrdersSnapshot ¶
type OrdersSnapshot struct {
Orders []Order `json:"orders"`
}
OrdersSnapshot is "all_orders": your open orders on join.
type Page ¶
Page is one page of a list endpoint. Cursor is the opaque value to pass back for the next page; it is empty on the last page.
type PaymentTransaction ¶
type PaymentTransaction struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// The monetary value the entry was calculated from. In dollars. Money as a
// decimal string, exactly as sent by the API.
Amount Decimal `json:"amount,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The fee that generated this entry, when it came from one.
FeeID string `json:"fee_id,omitempty"`
// Unique identifier for the record.
ID string `json:"id,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// The payment method the provider reports for this transaction.
Method string `json:"method,omitempty"`
// The payment that generated this entry, when it came from one.
PaymentID string `json:"payment_id,omitempty"`
// Points added by this entry. Negative when points were spent.
Points float64 `json:"points,omitempty"`
// The provider's reason or description for the transaction.
Reason string `json:"reason,omitempty"`
// The settlement that generated this entry, when it came from one.
SettlementID string `json:"settlement_id,omitempty"`
// For Interac, whether the transfer was a `Send` or a `Request`.
SubMethod string `json:"sub_method,omitempty"`
// When the entry was recorded.
Time time.Time `json:"time,omitzero"`
// What moved the money or the points, for example a deposit, a trade fee, a
// referral, or a manual adjustment. Each endpoint returns only its own subset
// of these. One of: "deposit", "withdrawal", "settlement", "fee",
// "fee_refund", "maker_rebate", "casino", "adjustment", "loyalty",
// "loyalty_points_rollup", "loyalty_points_referral".
Type string `json:"type,omitempty"`
}
PaymentTransaction: One deposit, withdrawal or balance adjustment, enriched with its payment method.
type PaymentUpdate ¶
type PaymentUpdate struct {
ID string `json:"id"`
AccountID string `json:"account_id"`
Provider string `json:"provider"`
ProviderID string `json:"provider_id"`
Status string `json:"status"`
Type string `json:"type"`
Amount Decimal `json:"amount"`
Data json.RawMessage `json:"data"`
}
PaymentUpdate is "payment_update": a payment changed status. Data is the provider's own detail.
type PortfolioService ¶
type PortfolioService struct {
// contains filtered or unexported fields
}
PortfolioService reads fills, settlements, per-market stats and money movements. Use it through Client.Portfolio.
func (*PortfolioService) Adjustments ¶
func (s *PortfolioService) Adjustments(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
Adjustments returns one page of manual balance adjustments (GET /api/v1/portfolio/adjustments).
func (*PortfolioService) AllAdjustments ¶
func (s *PortfolioService) AllAdjustments(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
AllAdjustments returns every adjustment, following the cursor.
func (*PortfolioService) AllDeposits ¶
func (s *PortfolioService) AllDeposits(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
AllDeposits returns every deposit, following the cursor.
func (*PortfolioService) AllFees ¶
func (s *PortfolioService) AllFees(ctx context.Context, q *PageQuery) iter.Seq2[FeeTransaction, error]
AllFees returns every fee entry, following the cursor.
func (*PortfolioService) AllFills ¶
func (s *PortfolioService) AllFills(ctx context.Context, q *FillsQuery) iter.Seq2[Fill, error]
AllFills returns every fill matching q, following the cursor.
func (*PortfolioService) AllLoyalty ¶
func (s *PortfolioService) AllLoyalty(ctx context.Context, q *PageQuery) iter.Seq2[Transaction, error]
AllLoyalty returns every loyalty entry, following the cursor.
func (*PortfolioService) AllMarketStats ¶
func (s *PortfolioService) AllMarketStats(ctx context.Context, q *MarketStatsQuery) iter.Seq2[MarketStat, error]
AllMarketStats returns every per-market stat row matching q, following the cursor.
func (*PortfolioService) AllSettlements ¶
func (s *PortfolioService) AllSettlements(ctx context.Context, q *SettlementsQuery) iter.Seq2[Settlement, error]
AllSettlements returns every settlement matching q, following the cursor.
func (*PortfolioService) AllWithdrawals ¶
func (s *PortfolioService) AllWithdrawals(ctx context.Context, q *PageQuery) iter.Seq2[PaymentTransaction, error]
AllWithdrawals returns every withdrawal, following the cursor.
func (*PortfolioService) Deposits ¶
func (s *PortfolioService) Deposits(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
Deposits returns one page of deposits (GET /api/v1/portfolio/deposits).
func (*PortfolioService) Fees ¶
func (s *PortfolioService) Fees(ctx context.Context, q *PageQuery) (*Page[FeeTransaction], error)
Fees returns one page of fee and fee-refund entries (GET /api/v1/portfolio/fees).
func (*PortfolioService) Fills ¶
func (s *PortfolioService) Fills(ctx context.Context, q *FillsQuery) (*Page[Fill], error)
Fills returns one page of your executions (GET /api/v1/fills).
func (*PortfolioService) Loyalty ¶
func (s *PortfolioService) Loyalty(ctx context.Context, q *PageQuery) (*Page[Transaction], error)
Loyalty returns one page of loyalty entries (GET /api/v1/portfolio/loyalty). Where the exchange has no loyalty program it returns an error matching ErrNotAvailable.
func (*PortfolioService) MarketStats ¶
func (s *PortfolioService) MarketStats(ctx context.Context, q *MarketStatsQuery) (*Page[MarketStat], error)
MarketStats returns one page of your exposure and P&L per market (GET /api/v1/account/market_stats). This is not the market_stats channel, which carries price history.
func (*PortfolioService) Settlements ¶
func (s *PortfolioService) Settlements(ctx context.Context, q *SettlementsQuery) (*Page[Settlement], error)
Settlements returns one page of settlements on your account (GET /api/v1/portfolio/settlements).
func (*PortfolioService) Withdrawals ¶
func (s *PortfolioService) Withdrawals(ctx context.Context, q *PageQuery) (*Page[PaymentTransaction], error)
Withdrawals returns one page of withdrawals (GET /api/v1/portfolio/withdrawals).
type Position ¶
type Position struct {
// The account the position belongs to.
AccountID string `json:"account_id,omitempty"`
// Average premium per contract for the open portion. In dollars. Money as a
// decimal string, exactly as sent by the API.
AverageOpenPremium Decimal `json:"average_open_premium,omitempty"`
// Liability from your open buy orders on this market. In dollars. Money as a
// decimal string, exactly as sent by the API.
BuyOrderLiability Decimal `json:"buy_order_liability,omitempty"`
// Contracts settled in the position so far. Quantity as a decimal string,
// exactly as sent by the API.
ContractsSettled Decimal `json:"contracts_settled,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// `total_settlement_pnl` plus any pending-close profit or loss that has not
// settled yet. In dollars. Money as a decimal string, exactly as sent by the
// API.
GrossPnL Decimal `json:"gross_pnl,omitempty"`
// The unique id of the position record.
ID string `json:"id,omitempty"`
// The market the position is on.
MarketID string `json:"market_id,omitempty"`
// Total potential fee across the position's settlements. In dollars. Money as
// a decimal string, exactly as sent by the API.
MaxPotentialFee Decimal `json:"max_potential_fee,omitempty"`
// Total possible profit for the position if everything settles favorably. In
// dollars. Money as a decimal string, exactly as sent by the API.
MaxPotentialProfit Decimal `json:"max_potential_profit,omitempty"`
// Account-level risk on the position, netting in already settled profit and
// loss. In dollars. Money as a decimal string, exactly as sent by the API.
MaxRisk Decimal `json:"max_risk,omitempty"`
// A combination position's payout per dollar risked: max price over the
// buy-side average fill, floored to two places. `null` for any market that is
// not a combination.
Multiplier float64 `json:"multiplier,omitempty"`
// Potential fee on the open contracts when they settle. In dollars. Money as a
// decimal string, exactly as sent by the API.
OpenPotentialFee Decimal `json:"open_potential_fee,omitempty"`
// Possible profit on the position's open contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
OpenPotentialProfit Decimal `json:"open_potential_profit,omitempty"`
// Risk on the position's open (unsettled) contracts. In dollars. Money as a
// decimal string, exactly as sent by the API.
OpenRisk Decimal `json:"open_risk,omitempty"`
// Net position in the market: positive if long (bought), negative if short
// (sold). Can be `"0.00"` for a market you have traded and closed out that has
// not settled yet. In contracts. Quantity as a decimal string, exactly as sent
// by the API.
Position Decimal `json:"position,omitempty"`
// Liability from the position's premium that counts against available balance.
// Routinely negative. In dollars. Money as a decimal string, exactly as sent
// by the API.
PositionPremiumLiability Decimal `json:"position_premium_liability,omitempty"`
// Total premium paid or received for the open portion of the position. In
// dollars. Money as a decimal string, exactly as sent by the API.
Premium Decimal `json:"premium,omitempty"`
// Liability from your open sell orders on this market. In dollars. Money as a
// decimal string, exactly as sent by the API.
SellOrderLiability Decimal `json:"sell_order_liability,omitempty"`
// Total fees paid across the position's settlements. In dollars. Money as a
// decimal string, exactly as sent by the API.
TotalFee Decimal `json:"total_fee,omitempty"`
// Profit or loss realized from settlements so far. In dollars. Money as a
// decimal string, exactly as sent by the API.
TotalSettlementPnL Decimal `json:"total_settlement_pnl,omitempty"`
}
Position: Your position in one market.
type PositionsQuery ¶
type PositionsQuery struct {
MarketIDs []string
}
PositionsQuery filters AccountService.Positions.
type PositionsSnapshot ¶
type PositionsSnapshot struct {
Positions []Position `json:"positions"`
}
PositionsSnapshot is "all_positions": your positions on join.
type PositionsUpdate ¶
type PositionsUpdate struct {
Positions []Position `json:"positions"`
}
PositionsUpdate is "updated_positions": only the positions that changed.
type PostOnlyWouldMatchError ¶ added in v0.2.1
type PostOnlyWouldMatchError struct {
// Reason is "auto_matching" when it would have matched another member's
// order: the exchange cancelled it and Order is the cancelled order. It is
// "match_with_self" when the first order it would have matched is your
// own: the exchange rejected it (a 422) and Order is nil.
Reason string
// Order is the cancelled order, for "auto_matching".
Order *Order
// Err is the 422, for "match_with_self".
Err error
}
PostOnlyWouldMatchError reports a PostOnly order that would have matched on arrival, so the exchange did not rest it. Nothing traded and the book is unchanged; re-price and place again. It matches ErrPostOnlyWouldMatch and ErrRejected.
func (*PostOnlyWouldMatchError) Error ¶ added in v0.2.1
func (e *PostOnlyWouldMatchError) Error() string
Error describes the refusal.
func (*PostOnlyWouldMatchError) Is ¶ added in v0.2.1
func (e *PostOnlyWouldMatchError) Is(target error) bool
Is matches ErrPostOnlyWouldMatch and ErrRejected.
func (*PostOnlyWouldMatchError) Unwrap ¶ added in v0.2.1
func (e *PostOnlyWouldMatchError) Unwrap() error
Unwrap returns the 422, if any.
type PoweredBy ¶ added in v0.2.1
type PoweredBy struct {
// A link to the provider, or to its page for the event.
Link string `json:"link,omitempty"`
// The provider's name, e.g. `ESPN`.
Provider string `json:"provider,omitempty"`
}
PoweredBy: The data provider that results a market.
type PricePoint ¶
type PricePoint struct {
TimestampUS int64 `json:"timestamp_us"`
PricePercent float64 `json:"price_percent"`
}
PricePoint is one bucket of a price series: its start in Unix microseconds and its closing price as a percent of the market's max price.
type ProfileAvatar ¶
type ProfileAvatar struct {
// Style is one of "dots", "rings", "stripes", "grid".
Style string `json:"style"`
// Palette is one of "ember", "forest", "ocean", "grape", "slate", "mint",
// "rose", "gold".
Palette string `json:"palette"`
// Seed is 1 to 32 characters; the same seed always renders the same image.
Seed string `json:"seed"`
}
ProfileAvatar is a generated avatar. Any style and palette pair renders; the seed selects the pattern.
type ProfileUpdate ¶
type ProfileUpdate struct {
// Handle is the new public handle: 3 to 24 lowercase letters, digits and
// inner "." or "_". It may change once every 30 days.
Handle string `json:"handle,omitempty"`
// Avatar is a new avatar.
Avatar *ProfileAvatar `json:"avatar,omitempty"`
// LeaderboardOptIn joins (true) or leaves (false) the public boards.
LeaderboardOptIn *bool `json:"leaderboard_opt_in,omitempty"`
}
ProfileUpdate holds the public-profile fields to change. Leave a field unset to keep it; at least one must be set.
type PublicTrade ¶
type PublicTrade struct {
MarketID string `json:"market_id"`
MarketSymbol string `json:"market_symbol"`
EventID string `json:"event_id"`
EventSymbol string `json:"event_symbol"`
Price Decimal `json:"price"`
Quantity Decimal `json:"quantity"`
Action string `json:"action"`
Timestamp string `json:"timestamp"`
TimestampUS int64 `json:"timestamp_us"`
}
PublicTrade is a "trade" message on the trades channel: an anonymous execution. Action is the taker's side, "buy" or "sell".
type Reauthenticator ¶
Reauthenticator is an Auth that can recover from a 401, for example by refreshing an OAuth access token. After a 401 the client calls Reauthenticate once; when it returns true the request is sent again.
type RecentTrade ¶
type RecentTrade struct {
// Which side took liquidity. `Trade.liquidity_taker/1` derives this from the
// resting side, so the values are `buyer` and `seller`, not `buy`/`sell` as on
// an order's `action`. One of: "buyer", "seller".
LiquidityTaker string `json:"liquidity_taker,omitempty"`
// The price the trade executed at. In dollars. Money as a decimal string,
// exactly as sent by the API.
Price Decimal `json:"price,omitempty"`
// Contracts traded. Quantity as a decimal string, exactly as sent by the API.
Quantity Decimal `json:"quantity,omitempty"`
// When the trade executed.
Timestamp time.Time `json:"timestamp,omitzero"`
// When the trade executed, as UNIX microseconds.
TimestampUs int64 `json:"timestamp_us,omitempty"`
}
RecentTrade: One recent trade on the market.
type ReconnectPolicy ¶
type ReconnectPolicy struct {
// InitialBackoff is the wait before the first attempt. Default 500ms.
InitialBackoff time.Duration
// MaxBackoff caps the wait. Default 30s.
MaxBackoff time.Duration
// MaxAttempts is how many attempts to make before giving up; 0 never
// gives up.
MaxAttempts int
// NoJitter uses the exact doubling waits.
NoJitter bool
}
ReconnectPolicy is the backoff between reconnect attempts: the wait doubles from InitialBackoff up to MaxBackoff, each wait drawn between 50% and 100% of its value unless NoJitter is set.
type 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.
type 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.
type SelfMatchBatch ¶
type SelfMatchBatch struct {
Updates []OrderSlipRef `json:"updates"`
}
SelfMatchBatch is "self_match_batch": entries whose self-match flag flipped.
type Settlement ¶
type Settlement struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// Whether the closing trade's order was placed before the event started.
ClosingPlacedPreStart bool `json:"closing_placed_pre_start,omitempty"`
// The price of the contracts when the position was closed. In dollars. Money
// as a decimal string, exactly as sent by the API.
ClosingPrice Decimal `json:"closing_price,omitempty"`
// The id of the trade that closed this settlement, if any.
ClosingTradeID string `json:"closing_trade_id,omitempty"`
// Whether the closing trade was placed before the event started.
ClosingTradedPreStart bool `json:"closing_traded_pre_start,omitempty"`
// The fee charged for the settlement. In dollars. Money as a decimal string,
// exactly as sent by the API.
Fee Decimal `json:"fee,omitempty"`
// The profit or loss associated with the position. In dollars. Money as a
// decimal string, exactly as sent by the API.
GrossPnL Decimal `json:"gross_pnl,omitempty"`
// Unique identifier for the record.
ID string `json:"id,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// Whether the opening trade's order was placed before the event started.
OpeningPlacedPreStart bool `json:"opening_placed_pre_start,omitempty"`
// The price of the contracts when the position was opened. In dollars. Money
// as a decimal string, exactly as sent by the API.
OpeningPrice Decimal `json:"opening_price,omitempty"`
// The id of the trade that opened this settlement.
OpeningTradeID string `json:"opening_trade_id,omitempty"`
// Whether the opening trade was placed before the event started.
OpeningTradedPreStart bool `json:"opening_traded_pre_start,omitempty"`
// Whether the settlement was placed before the event started.
PreStart bool `json:"pre_start,omitempty"`
// The number of contracts that were settled. Quantity as a decimal string,
// exactly as sent by the API.
Quantity Decimal `json:"quantity,omitempty"`
// The net profit or loss minus fees. In dollars. Money as a decimal string,
// exactly as sent by the API.
RealizedPnL Decimal `json:"realized_pnl,omitempty"`
// The amount of premium that was settled by the trade. In dollars. Money as a
// decimal string, exactly as sent by the API.
SettledPremium Decimal `json:"settled_premium,omitempty"`
// The amount of risk that was settled by the trade. In dollars. Money as a
// decimal string, exactly as sent by the API.
SettledRisk Decimal `json:"settled_risk,omitempty"`
// ISO-8601 timestamp of when the settlement was created. Same instant as
// `inserted_at`, which carries it as UNIX microseconds.
Time time.Time `json:"time,omitzero"`
// The type of settlement. One of: "closed_short", "closed_long",
// "expired_short", "expired_long".
Type string `json:"type,omitempty"`
}
Settlement: One closed or expired position.
type SettlementsQuery ¶
type SettlementsQuery struct {
MarketIDs []string
// Type is "closed_short", "closed_long", "expired_short" or
// "expired_long".
Type string
Limit int
Cursor string
}
SettlementsQuery filters PortfolioService.Settlements.
type SettlementsUpdate ¶
type SettlementsUpdate struct {
Settlements []Settlement `json:"settlements"`
}
SettlementsUpdate is "new_settlements".
type StatDetail ¶
type StatDetail struct {
// The player's jersey number, when known.
Jersey string `json:"jersey,omitempty"`
// The line value the market sits at, when the prop carries one.
Line float64 `json:"line,omitempty"`
// The participant the line belongs to, when applicable.
Participant string `json:"participant,omitempty"`
// The player the line belongs to, or `null` for a team line.
Player string `json:"player,omitempty"`
// The shape of the prop. One of: "ou", "yn", "1v2", "field".
PropType string `json:"prop_type,omitempty"`
// The stat the line is on, e.g. `passingYards`.
Stat string `json:"stat,omitempty"`
// Human-readable name for `stat`.
StatDisplayName string `json:"stat_display_name,omitempty"`
}
StatDetail: The stat line a prop market is derived from.
type StatsRange ¶
type StatsRange string
StatsRange is how far back a price series reaches.
const ( StatsDay StatsRange = "day" StatsWeek StatsRange = "week" StatsMonth StatsRange = "month" StatsAll StatsRange = "all" )
The ranges MarketStatsChannel and Subscription.RequestSeries take.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is one WebSocket connection to the exchange, carrying every topic you subscribe to. Get one with Client.Stream.
The stream signs the handshake afresh on every connect, sends the socket heartbeat, pings each joined topic (at a third of the granted timeout on orders with cancel-on-disconnect, so two pings can be lost before it fires), reconnects with backoff after a drop and rejoins every topic with its current filters, and rejoins a topic the exchange closes while the socket stays up. The account channels send their snapshots again on every rejoin.
A Stream is safe for concurrent use. Close it when you are done.
func (*Stream) AccountView ¶
func (s *Stream) AccountView(ctx context.Context, opts AccountViewOptions) (*AccountView, error)
AccountView subscribes to your account and returns once the four join snapshots have arrived. ctx bounds that wait and the view's life.
Example ¶
A live view of your account.
package main
import (
"context"
"fmt"
"log"
stx "github.com/stxapp/stx-go"
)
func main() {
ctx := context.Background()
client, err := stx.New(stx.WithProfile("us-demo"))
if err != nil {
log.Fatal(err)
}
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)
}
fmt.Println(view.Snapshot().Balance.AvailableBalance) // "746.8600"
for change := range view.Changes() {
fmt.Println(change.Kind, len(view.Snapshot().OpenOrders))
}
}
Output:
func (*Stream) ChannelRejoins ¶
ChannelRejoins returns how many topics were rejoined after the exchange closed them while the socket stayed up.
func (*Stream) Close ¶
Close leaves every topic, closes the socket and ends every subscription. It waits for the stream's goroutines to finish. Calling it again does nothing.
func (*Stream) ComboMaker ¶
func (s *Stream) ComboMaker(ctx context.Context) (*ComboMaker, error)
ComboMaker joins combo_quote:<user_id>. Where combos are not available it returns a *NotAvailableError. ctx bounds the join and the maker's life.
func (*Stream) ComboPlayer ¶
func (s *Stream) ComboPlayer(ctx context.Context) (*ComboPlayer, error)
ComboPlayer joins rfq:<user_id>. Where combos are not available it returns a *NotAvailableError (errors.Is(err, ErrNotAvailable)); other refusals, such as a read-only key, are a *ComboRefusedError. ctx bounds the join and the player's life.
func (*Stream) Done ¶
func (s *Stream) Done() <-chan struct{}
Done is closed when the stream ends: after Close, or when it gives up reconnecting.
func (*Stream) Err ¶
Err returns why the stream ended on its own (credentials that cannot recover, reconnect attempts used up), or nil while it runs and after Close.
func (*Stream) OrderSlip ¶
OrderSlip joins order_slip:<user_id>. ctx bounds the join and the slip's life.
func (*Stream) Reconnects ¶
Reconnects returns how many times the socket has reconnected.
func (*Stream) Subscribe ¶
Subscribe joins ch and returns the subscription. Messages arrive on Subscription.Messages until ctx is done, the subscription is closed, or the stream ends; then the channel is closed. ctx bounds the join and the subscription's whole life.
A refused join returns a *ChannelError with the exchange's reason, such as "unauthorized". The account channels need a signed stream.
type StreamOption ¶
type StreamOption func(*streamConfig)
StreamOption configures a Stream.
func WithBufferSize ¶
func WithBufferSize(n int) StreamOption
WithBufferSize sets how many messages each subscription buffers for you. When you fall behind and the buffer is full, the oldest message is dropped and a warning is logged. Default 10000.
func WithChannelPingInterval ¶
func WithChannelPingInterval(d time.Duration) StreamOption
WithChannelPingInterval sets the time between channel pings on every joined topic that answers them; 0 turns them off. The orders channel with cancel-on-disconnect always pings at a third of the timeout the exchange granted, whatever this is. Default 30s.
func WithHeartbeatInterval ¶
func WithHeartbeatInterval(d time.Duration) StreamOption
WithHeartbeatInterval sets the time between socket heartbeats. The exchange closes a socket silent for 60 seconds. Default 25s.
func WithJoinTimeout ¶
func WithJoinTimeout(d time.Duration) StreamOption
WithJoinTimeout sets how long to wait for the reply to a join or a channel command. Default 10s.
func WithOnReconnect ¶
func WithOnReconnect(fn func()) StreamOption
WithOnReconnect sets a function called after every reconnect and rejoin, and after a topic the exchange closed is rejoined while the socket stayed up. It is the moment to reload over REST what you cannot rebuild from the snapshots the account channels send again on rejoin, such as history. It runs on its own goroutine.
func WithReconnectPolicy ¶
func WithReconnectPolicy(p ReconnectPolicy) StreamOption
WithReconnectPolicy sets the backoff between reconnect attempts.
func WithStreamLogger ¶
func WithStreamLogger(l *slog.Logger) StreamOption
WithStreamLogger sets where the stream logs reconnects, rejoins and dropped messages. Default: the client's logger.
func WithUserID ¶
func WithUserID(id string) StreamOption
WithUserID gives the stream your user id, which the account topics are named by, so it does not ask GET /api/v1/me for it.
func WithoutReconnect ¶
func WithoutReconnect() StreamOption
WithoutReconnect ends the stream, and every subscription on it, when the socket drops, instead of reconnecting.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription is one joined topic on a Stream.
func (*Subscription) Close ¶
func (sub *Subscription) Close() error
Close leaves the topic and ends the subscription. Messages already buffered stay readable until the channel closes.
func (*Subscription) DecodeReply ¶
func (sub *Subscription) DecodeReply(v any) error
DecodeReply decodes the latest join reply into v.
func (*Subscription) Done ¶
func (sub *Subscription) Done() <-chan struct{}
Done is closed when the subscription ends.
func (*Subscription) Err ¶
func (sub *Subscription) Err() error
Err returns why the subscription ended: the context's error, the stream's error, or a *ChannelError when a rejoin was refused for good. It is nil while the subscription runs, after Close, and after the exchange closed a finished market.
func (*Subscription) Joined ¶
func (sub *Subscription) Joined() bool
Joined reports whether the topic is joined right now. It is false while the stream reconnects.
func (*Subscription) Messages ¶
func (sub *Subscription) Messages() <-chan Message
Messages returns the channel messages arrive on. It is closed when the subscription ends; Subscription.Err then says why.
func (*Subscription) Ping ¶
func (sub *Subscription) Ping(ctx context.Context) error
Ping sends the channel ping. On orders with cancel-on-disconnect it resets the deadline; the stream already pings on a timer.
func (*Subscription) Push ¶
func (sub *Subscription) Push(ctx context.Context, event string, payload any) (json.RawMessage, error)
Push sends event on the topic and returns the reply's response. A refusal is a *ChannelError.
func (*Subscription) Reply ¶
func (sub *Subscription) Reply() json.RawMessage
Reply returns the latest join reply's response: the applied filters, and on some channels the state, such as the series on market_stats or the whole market on market:<id> (prices in dollar strings).
func (*Subscription) RequestSeries ¶
func (sub *Subscription) RequestSeries(ctx context.Context, r StatsRange, marketIDs ...string) (*MarketStatsReply, error)
RequestSeries fetches price history at r for these markets on a market_stats subscription, without changing what streams.
func (*Subscription) RequestSnapshot ¶
func (sub *Subscription) RequestSnapshot(ctx context.Context) error
RequestSnapshot asks a market:<id> subscription to send the market's current "market_update" and "order_book_update" again now.
func (*Subscription) SelectEventIDs ¶
func (sub *Subscription) SelectEventIDs(ctx context.Context, eventIDs []string) (json.RawMessage, error)
SelectEventIDs changes which events stream on the events channel. At least one id is required.
func (*Subscription) SelectFilters ¶
func (sub *Subscription) SelectFilters(ctx context.Context, filters map[string][]string) (json.RawMessage, error)
SelectFilters changes the filters on ticker ("sports", "competitions") and trades ("market_ids", "event_ids") without rejoining. A nil list clears that filter.
func (*Subscription) SelectMarketIDs ¶
func (sub *Subscription) SelectMarketIDs(ctx context.Context, marketIDs []string) (json.RawMessage, error)
SelectMarketIDs changes the market filter without rejoining, on orderbook, market_stats and the account channels. nil clears it on the account channels; orderbook and market_stats need at least one id.
func (*Subscription) SelectMessageTypes ¶
func (sub *Subscription) SelectMessageTypes(ctx context.Context, types []string) (json.RawMessage, error)
SelectMessageTypes picks "market_created", "market_updated" or both on markets; nil means both.
func (*Subscription) SelectRuleFilters ¶
func (sub *Subscription) SelectRuleFilters(ctx context.Context, rules []string) (json.RawMessage, error)
SelectRuleFilters changes the rules filter on markets; nil turns it off.
func (*Subscription) Topic ¶
func (sub *Subscription) Topic() string
Topic returns the wire topic, for example "orders:7fb55544-3a7e-4f6b-bd66-fc89bd3a1087".
func (*Subscription) Watch ¶
func (sub *Subscription) Watch(ctx context.Context, marketIDs ...string) (json.RawMessage, error)
Watch adds markets to a market_updates subscription. Watches are sent again after every rejoin.
type Ticker ¶
type Ticker struct {
MarketID string `json:"market_id"`
MarketSymbol string `json:"market_symbol"`
EventID string `json:"event_id"`
EventSymbol string `json:"event_symbol"`
Sport string `json:"sport"`
Competition string `json:"competition"`
LastTradedPrice Decimal `json:"last_traded_price"`
LastTradedQuantity Decimal `json:"last_traded_quantity"`
BestBid Decimal `json:"best_bid"`
BestBidQuantity Decimal `json:"best_bid_quantity"`
BestOffer Decimal `json:"best_offer"`
BestOfferQuantity Decimal `json:"best_offer_quantity"`
BidDepth int `json:"bid_depth"`
OfferDepth int `json:"offer_depth"`
OpenInterest Decimal `json:"open_interest"`
TotalVolume Decimal `json:"total_volume"`
Timestamp string `json:"timestamp"`
TimestampUS int64 `json:"timestamp_us"`
}
Ticker is a "ticker" message: one market's price summary. Any field can be empty on a market that has not traded or has an empty side.
type TickerFilter ¶
TickerFilter narrows TickerChannel. Values match exactly, so "Football" and "football" differ.
type TradesFilter ¶
TradesFilter narrows TradesChannel.
type Transaction ¶
type Transaction struct {
// The account the record belongs to.
AccountID string `json:"account_id,omitempty"`
// The monetary value the entry was calculated from. In dollars. Money as a
// decimal string, exactly as sent by the API.
Amount Decimal `json:"amount,omitempty"`
// The event the market belongs to.
EventID string `json:"event_id,omitempty"`
// The fee that generated this entry, when it came from one.
FeeID string `json:"fee_id,omitempty"`
// Unique identifier for the record.
ID string `json:"id,omitempty"`
// Creation time, as UNIX microseconds.
InsertedAt int64 `json:"inserted_at,omitempty"`
// The market this record relates to.
MarketID string `json:"market_id,omitempty"`
// The payment that generated this entry, when it came from one.
PaymentID string `json:"payment_id,omitempty"`
// Points added by this entry. Negative when points were spent.
Points float64 `json:"points,omitempty"`
// For referral entries, the account that was referred.
RefereeAccountID string `json:"referee_account_id,omitempty"`
// For referral entries, the account that referred.
ReferrerAccountID string `json:"referrer_account_id,omitempty"`
// The settlement that generated this entry, when it came from one.
SettlementID string `json:"settlement_id,omitempty"`
// When the entry was recorded.
Time time.Time `json:"time,omitzero"`
// What moved the money or the points, for example a deposit, a trade fee, a
// referral, or a manual adjustment. Each endpoint returns only its own subset
// of these. One of: "deposit", "withdrawal", "settlement", "fee",
// "fee_refund", "maker_rebate", "casino", "adjustment", "loyalty",
// "loyalty_points_rollup", "loyalty_points_referral".
Type string `json:"type,omitempty"`
}
Transaction: One ledger entry on the account.
type TransportError ¶
TransportError is a request that got no answer. It matches ErrTransport and unwraps to the network error.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
Error describes the failed request.
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
Unwrap returns the network error.
type UserInfo ¶
type UserInfo struct {
UserID string `json:"userId"`
UserUID string `json:"userUid"`
UserStatus string `json:"userStatus"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
MiddleName string `json:"middleName"`
PreferredName string `json:"preferredName"`
CountryCode string `json:"countryCode"`
PhoneNumber string `json:"phoneNumber"`
BusinessCountryCode string `json:"businessCountryCode"`
BusinessPhone string `json:"businessPhone"`
DateOfBirth string `json:"dateOfBirth"`
Address1 string `json:"address1"`
Address2 string `json:"address2"`
City string `json:"city"`
State string `json:"state"`
ZipCode string `json:"zipCode"`
Country string `json:"country"`
CitizenshipCountry string `json:"citizenshipCountry"`
JobTitle string `json:"jobTitle"`
Industry string `json:"industry"`
EmployerName string `json:"employerName"`
EmployerAddress string `json:"employerAddress"`
PasswordChanged bool `json:"password_changed"`
Logout bool `json:"logout"`
TestAccount bool `json:"test_account"`
OptInMarketing bool `json:"optInMarketing"`
AllowMultipleLogins bool `json:"allowMultipleLogins"`
WhitelistIPAddresses string `json:"whitelistIpAddresses"`
ReferralCode string `json:"referralCode"`
}
UserInfo is "user_updated": your profile and account state.
Source Files
¶
- account.go
- accountview.go
- auth.go
- capabilities.go
- client.go
- combos.go
- decimal.go
- doc.go
- environment.go
- errors.go
- events.go
- fillmode.go
- leaderboard.go
- markets.go
- markets_create.go
- models.go
- models_gen.go
- operations_gen.go
- orders.go
- paging.go
- portfolio.go
- retry.go
- services.go
- settings.go
- signing.go
- transport.go
- version.go
- ws.go
- ws_channels.go
- ws_messages.go
- ws_money.go
- ws_orderslip.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
combos-maker
command
Command combos-maker quotes on every buy request it sees: three times the stake, standing for 30 seconds.
|
Command combos-maker quotes on every buy request it sees: three times the stake, standing for 30 seconds. |
|
combos-taker
command
Command combos-taker asks for quotes on a two-leg combination for a $1.00 stake and accepts the first quote.
|
Command combos-taker asks for quotes on a two-leg combination for a $1.00 stake and accepts the first quote. |
|
connect-account
command
An app with its own accounts links each user's STX account once and acts for them (https://docs.stxapp.io/oauth/connect-your-stx-account/):
|
An app with its own accounts links each user's STX account once and acts for them (https://docs.stxapp.io/oauth/connect-your-stx-account/): |
|
create-markets
command
Create player prop markets on an upcoming event as your app, then send the same request again to show that a repeat is safe.
|
Create player prop markets on an upcoming event as your app, then send the same request again to show that a repeat is safe. |
|
login-service
command
STX as a login option inside a login service such as Auth0, Clerk, Okta or Cognito (https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/login-vendor/).
|
STX as a login option inside a login service such as Auth0, Clerk, Okta or Cognito (https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/login-vendor/). |
|
quickstart
command
Command quickstart checks your STX API key, lists five open markets, reads your balance and positions, and with -place-order places a 1-cent limit buy and cancels it.
|
Command quickstart checks your STX API key, lists five open markets, reads your balance and positions, and with -place-order places a 1-cent limit buy and cancels it. |
|
sign-in-with-stx
command
An app with no login of its own: people register or log in with their STX account, and the app gets back who they are and tokens to act for them (https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/).
|
An app with no login of its own: people register or log in with their STX account, and the app gets back who they are and tokens to act for them (https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/). |
|
stream-account
command
Command stream-account keeps a live view of your account and prints it whenever it changes.
|
Command stream-account keeps a live view of your account and prints it whenever it changes. |
|
stream-orderbook
command
Command stream-orderbook prints the book of one market as it changes.
|
Command stream-orderbook prints the book of one market as it changes. |
|
stream-trades
command
Command stream-trades prints every trade on the exchange as it happens.
|
Command stream-trades prints every trade on the exchange as it happens. |
|
Package oauth lets an app call STX for its members and as itself.
|
Package oauth lets an app call STX for its members and as itself. |