Documentation
¶
Overview ¶
Package client is the public entry point to the Webull OpenAPI SDK. It owns the HTTP client, request signing, compact-JSON encoding, and typed error mapping, and it is the type passed to API-specific packages such as data.
Create a client with New and the functional [Option]s, then issue signed requests with Client.Do:
cl, err := client.New(
client.WithAppKey(key),
client.WithAppSecret(secret),
client.WithRegion(client.HK),
client.WithEnvironment(client.Sandbox),
)
if err != nil {
return err
}
defer cl.Close()
var out json.RawMessage
if err := cl.Do(ctx, http.MethodGet, "/openapi/account/list", nil, &out); err != nil {
return err
}
Every exported type in this package is defined here, so callers outside the module never need to import an internal package.
Index ¶
- Constants
- Variables
- func CorrelationIDFromContext(ctx context.Context) string
- func IsValidAPIVersion(v string) bool
- func WithCorrelationID(ctx context.Context, id string) context.Context
- type CircuitBreaker
- type Client
- func (c *Client) AccessToken() string
- func (c *Client) AppKey() string
- func (c *Client) AppSecret() string
- func (c *Client) CheckToken(ctx context.Context, token string) (*Token, error)
- func (c *Client) Close() error
- func (c *Client) Config() Config
- func (c *Client) CreateToken(ctx context.Context) (*Token, error)
- func (c *Client) CurrentToken() *Token
- func (c *Client) Do(ctx context.Context, method, path string, body, out any) error
- func (c *Client) DoBroker(ctx context.Context, method, path string, body, out any) error
- func (c *Client) DoStream(ctx context.Context, method, path string, body any) (*http.Response, error)
- func (c *Client) EnableTokenInjection()
- func (c *Client) Endpoints() Endpoints
- func (c *Client) EnsureToken(ctx context.Context) (*Token, error)
- func (c *Client) Environment() Environment
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) ObservabilityConfig() *observability.Config
- func (c *Client) Region() Region
- func (c *Client) SetToken(token *Token)
- func (c *Client) SetTokenPollInterval(d time.Duration)
- func (c *Client) SetTokenPollTimeout(d time.Duration)
- type Config
- type Endpoints
- type Environment
- type Hooks
- type Interceptor
- type Option
- func WithAPIVersion(v string) Option
- func WithAPIVersionFor(pathPrefix, v string) Option
- func WithAppKey(appKey string) Option
- func WithAppSecret(appSecret string) Option
- func WithAutoToken(enabled bool) Option
- func WithBaseURL(baseURL string) Option
- func WithBreaker(b CircuitBreaker) Option
- func WithClockDriftCorrection(enabled bool) Option
- func WithCredentials(appKey, appSecret string) Option
- func WithEndpoints(e Endpoints) Option
- func WithEnv() Option
- func WithEnvironment(env Environment) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithHTTPTransport(tr *http.Transport) Option
- func WithHooks(h Hooks) Option
- func WithInterceptor(i Interceptor) Option
- func WithLogger(log *slog.Logger) Option
- func WithMeterProvider(mp observability.MeterProvider) Option
- func WithPropagator(p observability.TextMapPropagator) Option
- func WithRateLimiter(l RateLimiter) Option
- func WithRegion(r Region) Option
- func WithResiliencePreset(preset ResiliencePreset) Option
- func WithRetry(cfg RetryConfig) Option
- func WithSandbox() Option
- func WithTimeout(d time.Duration) Option
- func WithTracerProvider(tp observability.TracerProvider) Option
- func WithUserAgent(ua string) Option
- func WithoutRetry() Option
- type RateLimiter
- type Region
- type ResiliencePreset
- type RetryConfig
- type Token
- type TokenStatus
Constants ¶
const ( // DefaultTimeout is the per-request HTTP timeout. DefaultTimeout = 30 * time.Second // DefaultUserAgent is the User-Agent sent with every request. DefaultUserAgent = "webullapi4go" // DefaultRetryAttempts is the total number of attempts, including the // first, for retryable idempotent requests. DefaultRetryAttempts = 2 // DefaultRetryBaseDelay is the delay before the first retry. DefaultRetryBaseDelay = 100 * time.Millisecond // DefaultRetryMaxDelay caps the exponential retry backoff. DefaultRetryMaxDelay = 2 * time.Second )
Defaults applied by DefaultConfig.
const ( // DefaultTokenPollInterval is the delay between check-token requests while // waiting for a PENDING token to become NORMAL. DefaultTokenPollInterval = 5 * time.Second // DefaultTokenPollTimeout is how long [Client.EnsureToken] waits for a // PENDING token to become NORMAL before giving up. DefaultTokenPollTimeout = 5 * time.Minute )
Default token polling parameters. Webull issues a token as PENDING and gives the user five minutes to complete 2FA, so the default timeout matches that window. The default interval respects the documented limit of 10 requests per 30 seconds for the token endpoints.
const ( // APIVersionV2 is the legacy API version and the SDK default. APIVersionV2 = "v2" // APIVersionV3 is the current API version used by the newer reference // endpoints, notably the /trading/ paths and the market-data // fundamentals and futures static data paths. APIVersionV3 = "v3" // DefaultAPIVersion is the x-version value used for request paths that // have no more specific built-in default, such as the market-data paths. // It remains v2 so that existing behaviour is preserved. DefaultAPIVersion = APIVersionV2 )
API interface versions accepted by the Webull OpenAPI x-version header.
const AccessTokenHeader = "x-access-token"
AccessTokenHeader is the request header that carries an active access token, as documented in Webull's authentication guide. It is not part of the request signature, so it can be attached after signing.
Variables ¶
var CorrelationIDKey = contextKey{}
CorrelationIDKey is the context key for the per-request correlation identifier. It is used by WithCorrelationID and CorrelationIDFromContext.
var ErrAccessTokenRequired = errs.NewSentinel( errs.CodeAuth, "access token required: call client.EnsureToken to complete the 2FA flow before running in production", )
ErrAccessTokenRequired is returned by Client.Do when WithAutoToken is enabled, no usable access token is cached, and the client targets the production environment. Production tokens require the caller to complete the Webull App 2FA flow, which the SDK refuses to start implicitly; call Client.EnsureToken once to create and activate a token, then retry.
var ErrCircuitOpen = errs.NewSentinel(errs.CodeTransport, "circuit breaker is open")
ErrCircuitOpen is wrapped into the error returned by Client.Do, Client.DoBroker, and Client.DoStream when a configured circuit breaker rejects a call.
Functions ¶
func CorrelationIDFromContext ¶
CorrelationIDFromContext returns the correlation identifier stored in ctx, or an empty string if none is set.
func IsValidAPIVersion ¶
IsValidAPIVersion reports whether v is one of the API versions supported by the SDK.
Types ¶
type CircuitBreaker ¶
type CircuitBreaker interface {
Allow() bool
RecordSuccess()
RecordFailure()
}
CircuitBreaker gates outgoing requests. Allow reports whether a call may proceed; RecordSuccess and RecordFailure report its outcome.
func NewBreaker ¶
func NewBreaker(threshold int, cooldown time.Duration) CircuitBreaker
NewBreaker returns a circuit breaker that opens after threshold consecutive server or transport failures and probes again after cooldown.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the Webull OpenAPI HTTP client. It owns the resolved Config and the shared transport, and is the SDK's public entry point: API-specific clients (for example the market-data client in package data) are constructed from it.
A Client is safe for concurrent use. All network access flows through Client.Do, Client.DoBroker, or Client.DoStream.
func New ¶
New returns a Client configured by opts. Options are applied in order on top of DefaultConfig; nil options are ignored. New validates the resulting configuration and returns an error when the credentials are missing or the region, environment, or endpoint is invalid.
func (*Client) AccessToken ¶
AccessToken returns the cached access token value, or an empty string when no token is cached. It never makes a network call.
func (*Client) CheckToken ¶
CheckToken returns the current status of token with POST /openapi/auth/token/check. It does not touch the client's token cache.
func (*Client) Close ¶
Close releases resources owned by the client, in particular the idle connections held by the underlying HTTP transport. It does not close connections that are still in use, and may be called more than once.
func (*Client) CreateToken ¶
CreateToken creates a new access token with POST /openapi/auth/token/create.
In production the returned token is TokenStatusPending until the user completes the Webull App 2FA flow (see Client.EnsureToken for an alternative that waits for that to happen); in the sandbox environment the token is TokenStatusNormal immediately. CreateToken does not touch the client's token cache; most callers want Client.EnsureToken.
func (*Client) CurrentToken ¶
CurrentToken returns a copy of the cached access token, or nil when none is cached. It never makes a network call.
func (*Client) Do ¶
Do performs a signed request against the Webull OpenAPI and decodes the JSON response into out. It is the single transport entry point for the SDK.
path is resolved against the configured base URL and may carry a query string, for example "/openapi/account/list?page=1". body is optional: when non-nil it is serialized as compact JSON without HTML escaping, and the exact bytes transmitted are the bytes that are signed. A nil body sends no request body. out is optional: when non-nil the response body is decoded into it with encoding/json.
Do applies the configured resilience primitives without changing this signature: the rate limiter waits before every attempt, the circuit breaker may reject an attempt, and transient errors are retried according to the configured RetryConfig. By default only idempotent requests (GET and HEAD) are retried.
On a 2xx response Do returns nil. On any other status it returns a typed *errs.Error classified by errs.FromHTTPStatus; network and encoding failures return errs.CodeTransport or errs.CodeAPI errors respectively.
func (*Client) DoBroker ¶
DoBroker performs a signed request against the Broker API and decodes the JSON response into out. It is identical to Client.Do except that it uses the Broker HTTP endpoint (cfg.Endpoints.BrokerHTTP) instead of the default HTTP endpoint. If BrokerHTTP is not configured, DoBroker returns an error.
func (*Client) DoStream ¶
func (c *Client) DoStream(ctx context.Context, method, path string, body any) (*http.Response, error)
DoStream sends a signed request and returns the raw, open response for endpoints that stream their result, such as Server-Sent Events, instead of buffering and JSON-decoding it.
DoStream applies the same request pipeline as Client.Do: path is resolved against the configured base URL and may carry a query string, body is serialized as compact JSON without HTML escaping (a []byte or encoding/json.RawMessage is sent verbatim, nil sends no body), the x-version header follows the same built-in per-path defaults and overrides, a cached access token is attached, the host that is signed is the host that is sent, and the configured rate limiter, circuit breaker, interceptors, hooks, logger, spans, and metrics apply.
Unlike Client.Do, DoStream never retries. A streaming response is a long-lived connection that is consumed incrementally and is not safe to replay, so the configured retry policy is deliberately bypassed.
On a non-2xx response the body is read, closed, and returned as a typed *errs.Error classified by errs.FromHTTPStatus. On success the returned response has an open body that the caller owns: the caller must read and close resp.Body. DoStream never closes a successful response body.
func (*Client) EnableTokenInjection ¶
func (c *Client) EnableTokenInjection()
EnableTokenInjection installs the transport hook that attaches the cached access token as the AccessTokenHeader header on outgoing requests. It is called automatically by Client.EnsureToken and Client.SetToken, and is idempotent.
INTEGRATION SEAM: this is how the SDK attaches x-access-token without changing the core request pipeline. The hook is an http.RoundTripper that wraps the client's existing transport, so it applies to Client.Do, Client.DoBroker, and Client.DoStream requests. Token-lifecycle endpoints are deliberately skipped. The header is added after signing and is therefore not part of the signature. If the request pipeline later grows an explicit token hook, it can consult Client.AccessToken instead; this wrapper remains compatible.
func (*Client) EnsureToken ¶
EnsureToken returns a usable access token, creating and, when necessary, waiting for one to become TokenStatusNormal.
A cached, still-valid token is reused without any network call. Otherwise a token is created: in the sandbox it is expected to be NORMAL immediately and is returned at once; in production a PENDING token is polled with Client.CheckToken until it becomes NORMAL, becomes INVALID or EXPIRED (an error is returned), or the poll timeout elapses. The resolved token is cached and installed as the AccessTokenHeader value for subsequent Client.Do calls.
Polling is bounded by DefaultTokenPollInterval and DefaultTokenPollTimeout, which can be changed with Client.SetTokenPollInterval and Client.SetTokenPollTimeout.
func (*Client) Environment ¶
func (c *Client) Environment() Environment
Environment returns the configured environment.
func (*Client) HTTPClient ¶
HTTPClient returns the HTTP client used for REST calls.
func (*Client) ObservabilityConfig ¶
func (c *Client) ObservabilityConfig() *observability.Config
ObservabilityConfig returns the telemetry configuration shared by this client and service clients created from it. The returned value must be treated as read-only after the client is constructed.
func (*Client) SetToken ¶
SetToken caches token and enables automatic header injection, replacing any previously cached token. Pass nil to clear the cache; a cleared cache also disables the token header for subsequent requests.
func (*Client) SetTokenPollInterval ¶
SetTokenPollInterval sets the delay between check-token requests used by Client.EnsureToken. A non-positive duration is ignored. It should be set before polling begins.
func (*Client) SetTokenPollTimeout ¶
SetTokenPollTimeout sets how long Client.EnsureToken waits for a PENDING token to become NORMAL. A non-positive duration is ignored. It should be set before polling begins.
type Config ¶
type Config struct {
// AppKey is the Webull OpenAPI app key.
AppKey string
// AppSecret is the Webull OpenAPI app secret.
AppSecret string
// Region is the deployment region.
Region Region
// Environment is the deployment environment.
Environment Environment
// Endpoints are the resolved service addresses.
Endpoints Endpoints
// HTTPClient is the client used for REST calls. When nil, [New] creates
// one with the configured timeout.
HTTPClient *http.Client
// Timeout is the per-request timeout. It is applied only to the HTTP
// client that [New] creates; a caller-supplied [Config.HTTPClient] keeps
// its own timeout.
Timeout time.Duration
// UserAgent is the User-Agent header sent with every request.
UserAgent string
// APIVersion is the x-version header sent with every request when it has
// been set explicitly with [WithAPIVersion]. Supported values are
// [APIVersionV2] and [APIVersionV3]. When it is left at its default,
// [Client] applies built-in per-path defaults instead: [APIVersionV3] for
// paths under /trading/ and [APIVersionV2] everywhere else. Per-path
// overrides registered with [WithAPIVersionFor] take precedence over both.
APIVersion string
// contains filtered or unexported fields
}
Config holds the resolved configuration for a Client. It is populated by Option functions and treated as immutable once the client is built.
Every field uses a public type: callers outside the module never need to import an internal package.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config pre-filled with production Hong Kong endpoints and the SDK's transport defaults.
type Endpoints ¶
type Endpoints struct {
// HTTP is the REST API base URL used for trading and market data.
HTTP string
// MQTT is the MQTT broker address (host:port) used for market-data
// streaming.
MQTT string
// MQTTWebSocket is the MQTT-over-WebSocket URL used for market-data
// streaming.
MQTTWebSocket string
// GRPC is the host of the gRPC trading-event stream.
GRPC string
// BrokerHTTP is the Broker API REST endpoint.
BrokerHTTP string
}
Endpoints holds the resolved service addresses for one region/environment pair. It is a public mirror of the internal endpoint set.
func DefaultEndpoints ¶
func DefaultEndpoints() Endpoints
DefaultEndpoints returns the production Hong Kong endpoints.
func EndpointsFor ¶
func EndpointsFor(r Region, env Environment) Endpoints
EndpointsFor returns the service endpoints for the given region and environment. An unknown region falls back to Hong Kong and an unknown environment falls back to production; call Region.IsValid and Environment.IsValid first to detect this.
type Environment ¶
type Environment string
Environment selects between the production and sandbox deployments.
const ( // Production is the live Webull OpenAPI environment. Production Environment = "production" // Sandbox is the Webull test environment. Sandbox Environment = "sandbox" )
func (Environment) IsValid ¶
func (e Environment) IsValid() bool
IsValid reports whether e is a known environment.
func (Environment) String ¶
func (e Environment) String() string
String returns the environment name.
type Hooks ¶
type Hooks struct {
// OnRequest is called after rate-limiting and circuit-breaking, before
// user interceptors, with the HTTP method and path.
OnRequest func(method, path string)
// OnResponse is called on a successful response (2xx), passing the
// actual HTTP status code and the round-trip latency.
OnResponse func(status int, latency time.Duration)
// OnError is called when the request returns an error or a non-2xx HTTP
// status, passing the error and the round-trip latency.
OnError func(err error, latency time.Duration)
// OnLatency is called after every attempt (success, error, or retry) with
// the one-based attempt number and the round-trip latency.
OnLatency func(attempt int, latency time.Duration)
}
Hooks holds optional lifecycle callbacks invoked by Client.Do, Client.DoBroker, and Client.DoStream around each request attempt. All fields are optional; nil fields are no-ops.
These hooks are the integration point for observability tools (structured logging, OpenTelemetry tracing, Prometheus metrics). Attempt numbers start at one for each logical request and increase for retries.
type Interceptor ¶
Interceptor is a function that wraps the request pipeline. It receives the next function in the chain and may inspect, decorate, or short-circuit the request. Interceptors are invoked in the order they are supplied to WithInterceptor for Client.Do, Client.DoBroker, and Client.DoStream. The first interceptor in the chain receives a function that performs the underlying HTTP call (signing and sending).
For example, a logging interceptor:
func(ctx context.Context, next func(context.Context) error) error {
start := time.Now()
err := next(ctx)
log.Printf("request took %s: %v", time.Since(start), err)
return err
}
type Option ¶
type Option func(*Config)
Option mutates a Config during New. Options are applied in order on top of DefaultConfig, so a later option normally overrides an earlier one. A breaker explicitly supplied with WithBreaker remains caller-owned when a resilience preset is applied.
func WithAPIVersion ¶
WithAPIVersion sets the x-version header sent with every request, taking precedence over the SDK's built-in per-path defaults. Supported values are APIVersionV2 and APIVersionV3. When it is not called, paths under /trading/ default to APIVersionV3 and every other path to DefaultAPIVersion ("v2"). New rejects any unsupported version.
func WithAPIVersionFor ¶
WithAPIVersionFor overrides the x-version header for requests whose path starts with pathPrefix. The longest matching prefix wins, so a single endpoint can opt into APIVersionV3 while the rest of the client stays on the configured default. pathPrefix must be non-empty and v must be a supported version; New rejects anything else.
func WithAppSecret ¶
WithAppSecret sets the Webull OpenAPI app secret.
func WithAutoToken ¶
WithAutoToken enables or disables automatic access-token handling for the client. It is off by default, so Client.Do, Client.DoBroker, and Client.DoStream never obtain a token on their own and only attach one cached by Client.EnsureToken or Client.SetToken.
When enabled and no usable token is cached, the first request that is not a token-lifecycle endpoint behaves as follows:
- in the sandbox environment Client.EnsureToken is called automatically (sandbox tokens are activated without 2FA) and the token is attached to the request and every later one;
- in production Client.Do fails with ErrAccessTokenRequired, leaving the caller to drive the 2FA flow explicitly with Client.EnsureToken.
Production 2FA is never started implicitly.
func WithBaseURL ¶
WithBaseURL overrides only the REST base URL, for example "https://api.sandbox.webull.hk" or a local test server. It takes precedence over the address resolved from the region and environment.
func WithBreaker ¶
func WithBreaker(b CircuitBreaker) Option
WithBreaker sets the circuit breaker consulted before every request attempt. A nil breaker disables circuit breaking (the default). A breaker supplied here remains caller-owned when WithResiliencePreset is also used.
func WithClockDriftCorrection ¶
WithClockDriftCorrection enables clock-drift correction. When enabled, the client learns the offset between the local clock and the Webull server's clock by observing the Date response header on each successful request, and applies that offset to subsequent x-timestamp values used in request signing. The offset is clamped to the range [-5 minutes, +5 minutes] to prevent extreme offsets from being injected. Disable with false to opt out.
func WithCredentials ¶
WithCredentials sets both the app key and the app secret.
func WithEndpoints ¶
WithEndpoints overrides the service endpoints resolved from the region and environment.
func WithEnv ¶
func WithEnv() Option
WithEnv returns an Option that fills the configuration from the process environment. It is a convenience for deployment: the same variables the sandbox integration tests read configure a production client.
The variables read are:
- WEBULL_APP_KEY, WEBULL_APP_SECRET — credentials.
- WEBULL_REGION — deployment region, matched case-insensitively against the known regions (for example "hk" or "us").
- WEBULL_ENVIRONMENT — "prod" or "production" selects Production; "uat" or "sandbox" selects Sandbox.
- WEBULL_BASE_URL — optional override of the REST base URL only.
- WEBULL_MQTT_URL — optional override of the MQTT broker address only.
Variables that are unset or empty are ignored. An invalid WEBULL_REGION or WEBULL_ENVIRONMENT value is never silently ignored: New fails with a typed *errs.Error whose code is errs.CodeInvalidConfig (the same code returned when required credentials are missing).
Precedence: WithEnv acts as a lower-precedence default source. It fills a field only when that field has not already been set by another option, so explicit functional options always win over the environment regardless of the order in which the options are passed to New:
// The explicit credentials win; region and environment come from the // environment because no explicit option sets them. client.New(client.WithCredentials(key, secret), client.WithEnv())
Applying WithEnv() before or after an explicit option is therefore equivalent. Similarly, an endpoint option (WithEndpoints or WithBaseURL) suppresses the WEBULL_BASE_URL and WEBULL_MQTT_URL overrides.
The environment is read when the option is applied inside New, not when WithEnv is called.
func WithEnvironment ¶
func WithEnvironment(env Environment) Option
WithEnvironment sets the deployment environment.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client used for REST calls. When omitted, New creates one with the configured timeout.
func WithHTTPTransport ¶
WithHTTPTransport sets the http.Transport used for REST calls. It is applied after WithHTTPClient; if no HTTP client has been set, New creates one with the configured timeout before applying the transport. This allows callers to tune connection pooling, TLS, timeouts, and other transport-level parameters without replacing the entire HTTP client.
func WithInterceptor ¶
func WithInterceptor(i Interceptor) Option
WithInterceptor adds an interceptor to the request pipeline. Interceptors are invoked after rate-limiting and circuit-breaking but before the request is signed and sent, and after the response is received. Multiple interceptors can be added; they fire in the order they are supplied for Client.Do, Client.DoBroker, and Client.DoStream.
func WithLogger ¶
WithLogger sets the structured logger used by Client.Do, Client.DoBroker, and Client.DoStream for per-request log output. When nil (the default), no structured logging is produced.
func WithMeterProvider ¶
func WithMeterProvider(mp observability.MeterProvider) Option
WithMeterProvider sets the OpenTelemetry [MeterProvider] used to create meters for SDK-level metrics. When nil (the default), the global no-op meter is used.
func WithPropagator ¶
func WithPropagator(p observability.TextMapPropagator) Option
WithPropagator sets the OpenTelemetry propagator used to extract and inject trace context on requests. When nil (the default), no trace context propagation is performed.
func WithRateLimiter ¶
func WithRateLimiter(l RateLimiter) Option
WithRateLimiter sets the rate limiter consulted before every request attempt. A nil limiter disables rate limiting (the default).
func WithResiliencePreset ¶
func WithResiliencePreset(preset ResiliencePreset) Option
WithResiliencePreset applies a named resilience preset. Currently only ProductionPreset is defined. The preset sets a per-path rate limiter and retry policy immediately; its circuit breaker is created by New after all options have been applied so the configured meter provider is independent of option order. An explicitly supplied breaker, including nil, is preserved.
func WithRetry ¶
func WithRetry(cfg RetryConfig) Option
WithRetry replaces the default retry policy. Only idempotent requests are retried unless RetryConfig.RetryNonIdempotent is set.
func WithSandbox ¶
func WithSandbox() Option
WithSandbox switches the client to the sandbox environment.
func WithTimeout ¶
WithTimeout sets the per-request timeout used when New creates the HTTP client.
func WithTracerProvider ¶
func WithTracerProvider(tp observability.TracerProvider) Option
WithTracerProvider sets the OpenTelemetry [TracerProvider] used to create spans for Client.Do, Client.DoBroker, and Client.DoStream requests. When nil (the default), the global no-op tracer is used.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header sent with every request.
func WithoutRetry ¶
func WithoutRetry() Option
WithoutRetry disables retries. Requests are attempted exactly once.
type RateLimiter ¶
RateLimiter throttles outgoing requests. Client.Do calls Wait before every attempt, passing the request path as the key so implementations can apply per-endpoint limits. Wait must return ctx.Err() when ctx is done.
func NewRateLimiter ¶
func NewRateLimiter(rate float64, burst int) RateLimiter
NewRateLimiter returns a keyed token-bucket limiter that allows rate tokens per second with the given burst, applied independently per request path. NewRateLimiter panics if rate or burst is not positive.
type Region ¶
type Region string
Region identifies a Webull OpenAPI deployment region. It is a public mirror of the internal region identifier so that external callers never need to import an internal package.
const ( // HK is the Hong Kong region (the SDK's primary target). HK Region = "hk" // US is the United States region. US Region = "us" // JP is the Japan region. JP Region = "jp" // SG is the Singapore region. SG Region = "sg" // TH is the Thailand region. TH Region = "th" // AU is the Australia region. AU Region = "au" // MY is the Malaysia region. MY Region = "my" // UK is the United Kingdom region. UK Region = "uk" // BR is the Brazil region. BR Region = "br" // MX is the Mexico region. MX Region = "mx" // ZA is the South Africa region. ZA Region = "za" // EU is the European Union region. EU Region = "eu" )
type ResiliencePreset ¶
type ResiliencePreset string
ResiliencePreset applies a named set of resilience defaults. Presets are composable: each call adds to or overrides the existing configuration.
const ( // ProductionPreset applies sensible production defaults: a per-path rate // limiter (10 requests per second, burst 20), a circuit breaker (opens after // 5 consecutive failures, 30-second cooldown), and exponential backoff retry // with full jitter (base 200 ms, cap 2 s, up to 3 attempts). ProductionPreset ResiliencePreset = "production" )
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the total number of attempts, including the first. One
// disables retrying while keeping the retry machinery active.
MaxAttempts int
// BaseDelay is the delay before the first retry and the base of the
// exponential backoff.
BaseDelay time.Duration
// MaxDelay caps the computed delay.
MaxDelay time.Duration
// Jitter randomizes each delay by plus or minus 20 percent.
Jitter bool
// RetryNonIdempotent allows retrying methods that are not idempotent
// (for example POST). It is disabled by default so that only GET and HEAD
// requests are retried.
RetryNonIdempotent bool
// IsRetryable reports whether an error is transient. When nil the SDK
// classifier retries transport failures, HTTP 429, and HTTP 5xx.
IsRetryable func(error) bool
}
RetryConfig configures the retries performed by Client.Do for transient failures. Zero-valued duration and attempt fields fall back to the SDK defaults (DefaultRetryAttempts, DefaultRetryBaseDelay, DefaultRetryMaxDelay); a nil IsRetryable falls back to the SDK classifier. To disable retries entirely use WithoutRetry.
type Token ¶
type Token struct {
// Value is the access token string sent as the [AccessTokenHeader] header.
Value string
// ExpiresAt is the token expiry. The zero time means unspecified.
ExpiresAt time.Time
// Status is the current lifecycle state.
Status TokenStatus
}
Token is an access token and its lifecycle metadata. It is the public mirror of the internal token DTO; every exported signature in this package uses this type.
func (Token) Expired ¶
Expired reports whether the token has an expiry that is at or before now. A token without an expiry is never considered expired.
func (Token) Valid ¶
Valid reports whether the token is usable right now: it has a value, its status is TokenStatusNormal, and it has not expired.
type TokenStatus ¶
type TokenStatus string
TokenStatus is the lifecycle state of an access token, mirrored from the Webull TokenRespVo schema so that callers never need an internal package.
const ( // TokenStatusPending means the token awaits verification. TokenStatusPending TokenStatus = "PENDING" // TokenStatusNormal means the token is valid and usable. TokenStatusNormal TokenStatus = "NORMAL" // TokenStatusInvalid means the token is invalid or was never used. TokenStatusInvalid TokenStatus = "INVALID" // TokenStatusExpired means the verification window elapsed. TokenStatusExpired TokenStatus = "EXPIRED" )
Token lifecycle states. A token is created PENDING and becomes NORMAL once 2FA is completed; sandbox tokens are NORMAL immediately. INVALID means the token was unused for 15 consecutive days (or does not exist) and EXPIRED means 2FA was not completed within five minutes.
func (TokenStatus) String ¶
func (s TokenStatus) String() string
String returns the wire representation of the status.
func (TokenStatus) Valid ¶
func (s TokenStatus) Valid() bool
Valid reports whether s is one of the four statuses defined by Webull.