webullapi4go

package module
v2.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 0 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

webullapi4go

An idiomatic Go SDK for the Webull OpenAPI. It provides typed clients for Webull's HTTP, MQTT, and gRPC services. The module path is github.com/shing1211/webullapi4go/v2 and the first installable Go-semver v2 tag is v2.2.0. Earlier v2.1.x repository tags declared the pre-migration module path and were not installable; they have been removed.

Feature matrix

Status distinguishes implementation and live availability. “Implemented” does not mean every endpoint is live-verified; see the implementation status for verification boundaries.

Area Implementation Verification Details
Authentication Implemented Offline-tested; core token flow live-verified in HK HMAC-SHA1 REST signing, token create/check/ensure, automatic token injection
Market Data HTTP Implemented Offline-tested; selected HK calls live-verified Instruments, fundamentals, futures, snapshot, tick, quotes/depth, bars, watchlists, options, news, event contracts, crypto/funds, and Display routes
Market Data MQTT Implemented Offline-tested; basic HK stream path previously live-verified QUOTE, SNAPSHOT, and TICK over MQTT or MQTT-over-WebSocket, reconnect/resubscribe, health state, and bounded channels
Trading HTTP + OMS Implemented Offline-tested; selected HK account/preview paths live-verified Accounts, assets, stock/single-leg/multi-leg/futures/event order validation, order queries, guardrails, and local order-state reconciliation
Trading events Implemented Offline-tested; basic stream path previously exercised Order, position, and option streams over server-streaming gRPC, reconnect, correlation, spans, and metrics
Broker API HK Implemented and offline-tested Live blocked Scope-protected virtual accounts, instruments, assets, orders, funding, journals, and events; separate broker/ module
Broker FD API US Implemented and offline-tested Live blocked without US credentials Agreements, accounts, documents, assets, activity, funding, instruments, orders, journals, and master data
Broker FD events Implemented and offline-tested Live blocked without US credentials Broker FD event stream over gRPC using grpc.event.EventService
Display Solution Implemented and offline-tested Live blocked by host/entitlement Company profile, analyst data, news, streaming, screeners, and quotes; HK host returns 403
Connect OAuth Implemented and offline-tested US live access unavailable Authorization-code URL builder and token exchange/refresh

Install

The module path is github.com/shing1211/webullapi4go/v2, carrying the /v2 suffix required by Go's semantic import versioning. Install the latest release:

go get github.com/shing1211/webullapi4go/v2@latest

The first installable Go-semver v2 tag is v2.2.0. Earlier v2.1.x repository tags declared the pre-migration module path and were not installable; they have been removed. A commit pin (@<sha>) or branch ref (@main) still work for a specific tree.

The broker/ package is a separate Broker API HK module. Its go.mod replaces the root module with ../; it is not a nested package that root go build ./... traverses.

Quickstart

HTTP market data
package main

import (
	"context"
	"log"

	"github.com/shing1211/webullapi4go/v2/client"
	"github.com/shing1211/webullapi4go/v2/data"
)

func main() {
	// WithEnv reads WEBULL_APP_KEY, WEBULL_APP_SECRET, WEBULL_REGION, and
	// WEBULL_ENVIRONMENT.
	cl, err := client.New(client.WithEnv())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = cl.Close() }()

	ctx := context.Background()
	if _, err := cl.EnsureToken(ctx); err != nil {
		log.Fatal(err)
	}

	market := data.New(cl)
	snaps, err := market.GetSnapshot(ctx, data.SnapshotQuery{
		Symbols:  []string{"AAPL"},
		Category: data.StockCategoryUS,
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range snaps {
		log.Printf("%s %s", s.Symbol, s.Price)
	}
}
Streaming over MQTT
package main

import (
	"context"
	"log"

	"github.com/shing1211/webullapi4go/v2/client"
	marketdatav1 "github.com/shing1211/webullapi4go/v2/gen/webull/marketdata/v1"
	"github.com/shing1211/webullapi4go/v2/stream"
)

func main() {
	cl, err := client.New(client.WithEnv())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = cl.Close() }()

	ctx := context.Background()
	if _, err := cl.EnsureToken(ctx); err != nil {
		log.Fatal(err)
	}

	s, err := stream.New(cl, stream.WithWebSocket(true))
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = s.Close() }()

	s.OnSnapshot(func(snap *marketdatav1.Snapshot) {
		log.Printf("%s %s", snap.GetBasic().GetSymbol(), snap.GetPrice())
	})

	if err := s.Connect(ctx); err != nil {
		log.Fatal(err)
	}
	if err := s.Subscribe(ctx, stream.SubscribeRequest{
		Symbols:  []string{"AAPL"},
		Category: stream.CategoryUSStock,
		SubTypes: []stream.SubType{stream.SubTypeQuote, stream.SubTypeSnapshot, stream.SubTypeTick},
	}); err != nil {
		log.Fatal(err)
	}

	select {} // block until the process is interrupted
}
Trading: accounts and positions
package main

import (
	"context"
	"log"

	"github.com/shing1211/webullapi4go/v2/client"
	"github.com/shing1211/webullapi4go/v2/trade"
)

func main() {
	cl, err := client.New(client.WithEnv())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = cl.Close() }()

	ctx := context.Background()
	if _, err := cl.EnsureToken(ctx); err != nil {
		log.Fatal(err)
	}

	trading := trade.New(cl)
	accounts, err := trading.ListAccounts(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, acct := range accounts {
		balance, err := trading.GetBalance(ctx, acct.AccountID)
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("%s cash=%s market_value=%s", acct.AccountID,
			balance.TotalCashBalance, balance.TotalMarketValue)
	}
}
Trading events over gRPC
package main

import (
	"context"
	"log"

	"github.com/shing1211/webullapi4go/v2/client"
	"github.com/shing1211/webullapi4go/v2/events"
)

func main() {
	cl, err := client.New(client.WithEnv())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = cl.Close() }()

	ev, err := events.New(cl, events.WithSubscribeTypes(events.SubscribeOrder))
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = ev.Close() }()

	ev.OnConnect(func() { log.Println("subscribed") })
	ev.OnOrder(func(o *events.OrderEvent) {
		log.Printf("%s %s %s", o.OrderID, o.OrderStatus, o.SceneType)
	})

	if err := ev.Run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

More runnable programs live in examples/.

Configuration

Credentials and environment are never hard-coded. client.WithEnv() reads the following process environment variables:

Variable Purpose
WEBULL_APP_KEY Webull OpenAPI app key (required)
WEBULL_APP_SECRET Webull OpenAPI app secret, used to sign requests (required)
WEBULL_REGION Deployment region: hk (default), us, jp, sg, th, au, my, uk, br, mx, za, eu
WEBULL_ENVIRONMENT prod / production (default) or uat / sandbox
WEBULL_BASE_URL Optional override of the REST base URL only
WEBULL_MQTT_URL Optional override of the MQTT broker address only

Explicit functional options always take precedence over WithEnv() regardless of order. Common options:

Option Purpose
WithAppKey, WithAppSecret, WithCredentials Set credentials directly
WithRegion(client.HK) Select the deployment region
WithEnvironment(client.Sandbox), WithSandbox() Select the environment
WithBaseURL, WithEndpoints Override resolved service endpoints
WithHTTPClient, WithHTTPTransport, WithTimeout, WithUserAgent Tune HTTP transport and connection pooling
WithRetry(RetryConfig), WithoutRetry(), WithResiliencePreset Configure transient-failure handling
WithRateLimiter, NewRateLimiter(rate, burst) Throttle requests per path
WithBreaker, NewBreaker(threshold, cooldown) Add a circuit breaker
WithClockDriftCorrection Learn a bounded signing-clock offset from response Date headers
WithInterceptor, WithHooks Add request-pipeline behavior and lifecycle callbacks
WithAPIVersion("v2"|"v3"), WithAPIVersionFor(prefix, version) Select the x-version header
WithAutoToken(true) Obtain a sandbox token automatically before the first token-consuming request
WithLogger, WithTracerProvider, WithMeterProvider, WithPropagator Configure structured logs and OpenTelemetry
WithEnv() Fill configuration from the environment

Streaming is configured with stream.WithSessionID, WithMQTTURL, WithWebSocket, WithAutoReconnect, WithAutoResubscribe, WithResubscribeTimeout, WithKeepAlive, WithConnectTimeout, WithWriteTimeout, WithMessageChannelDepth, WithCleanSession, WithTLSConfig, WithHealthWatchdog, and WithMeter.

Trading is configured with trade.WithMaxOrderNotional, trade.WithMaxOrderQuantity, and trade.WithAutoClientOrderID. The first two are advisory configuration guardrails enforced before placement. The notional cap does not cover multi-leg option orders, which have no single top-level notional; the quantity cap still applies. Auto client-order IDs are stable for the same logical place request and do not mutate the caller's request.

Trading events are configured with events.WithSubscribeTypes, events.WithAccounts, events.WithGRPCEndpoint, events.WithGRPCPort, events.WithTLS, events.WithDialTimeout, events.WithGRPCDialOption, events.WithAutoReconnect, events.WithReconnectBaseDelay, events.WithReconnectMaxDelay, and events.WithMaxReconnectAttempts.

See Observability for OTel setup, metric names, event spans, and correlation propagation.

Sandbox testing

Use the sandbox while developing. Point the client at the environment and it resolves the Hong Kong sandbox host https://api.sandbox.webull.hk:

export WEBULL_ENVIRONMENT="sandbox"
export WEBULL_APP_KEY="your-sandbox-app-key"
export WEBULL_APP_SECRET="your-sandbox-app-secret"

Core, data, stream, and events sandbox tests are skipped unless explicitly enabled. Use the actual Sandbox test selector, and never commit credentials:

# macOS / Linux
WEBULL_SANDBOX=1 \
WEBULL_APP_KEY=your-sandbox-app-key \
WEBULL_APP_SECRET=your-sandbox-app-secret \
go test ./... -run Sandbox
# Windows PowerShell
$env:WEBULL_SANDBOX = "1"
$env:WEBULL_APP_KEY = "your-sandbox-app-key"
$env:WEBULL_APP_SECRET = "your-sandbox-app-secret"
go test ./... -run Sandbox

Trading-package sandbox tests use separate credentials and the WEBULL_TRADE_SANDBOX=1, WEBULL_TRADE_APP_KEY, WEBULL_TRADE_APP_SECRET, and WEBULL_TRADE_ACCOUNT_ID variables:

WEBULL_TRADE_SANDBOX=1 \
WEBULL_TRADE_APP_KEY=your-trading-sandbox-app-key \
WEBULL_TRADE_APP_SECRET=your-trading-sandbox-app-secret \
WEBULL_TRADE_ACCOUNT_ID=your-trading-account-id \
go test ./trade -run Sandbox

The mutating trade test additionally requires WEBULL_TRADE_MUTATE=1. The mutating order-event test uses the generic WEBULL_SANDBOX credentials plus WEBULL_TRADE_ACCOUNT_ID and WEBULL_TRADE_MUTATE=1. MQTT over WebSocket tests additionally read WEBULL_MQTT_WEBSOCKET=1. See the local sandbox guide and troubleshooting guide for the complete gates and known limitations (a single supported symbol, entitlement-gated footprint data, empty depth outside market hours, and network blocking of plain MQTT on port 1883). HTTP 417 is mapped to the historical INVALID_TOKEN category for compatibility, but Webull also uses it for invalid symbols and other business validation; inspect the API message before treating it as a token failure.

Package map

Package Purpose
client Canonical core SDK: configuration, signing, tokens, HTTP transport, request pipeline, and resilience
data Canonical Market Data HTTP client and DTOs
stream Canonical Market Data MQTT client with reconnect, health, and channel policies
trade Canonical Trading HTTP client and OMS tracking integration
events Canonical Trading Events gRPC client
connect OAuth 2.0 authorization-code flow for third-party apps (US only)
display Display Solution client-to-server authentication and token management
broker Broker API HK (separate Go module; broker/go.mod: replace github.com/shing1211/webullapi4go/v2 => ../)
brokerfd Broker FD US HTTP endpoints (accounts, orders, funding, instruments, etc.)
brokerfd/events Broker FD US events over gRPC
webull Optional thin aliases for the core client; service clients remain in their root packages
pkg/errors Public typed errors, codes, and sentinels
pkg/observability OpenTelemetry handles, span helpers, shared instruments, and sanitized telemetry error text
pkg/resilience Public retry, rate-limit, circuit-breaker, and clock primitives
pkg/transport Public HTTP transport and MQTT transport
pkg/domain/money money.Money, the public DTO decimal type
pkg/domain/order Public order state machine and reconciliation model
pkg/types Shared public market/instrument types
gen/webull/... Committed generated protobuf types; do not hand-edit
internal/* Non-public authentication and compatibility implementation details

Roadmap and release status

Version Scope Status
v0.x–v1.0 Core API, Trading, Events, full endpoint coverage, examples, and API stabilization Released
v1.1.1 Production test/security tooling, multi-OS CI, leak checks, and fuzzing Released
v2.0.0–v2.0.2 Public error/resilience/transport foundations, OMS domain, money.Money, and thin webull aliases; root services retained Historical tag; not a published v2 module
v2.0.3–v2.0.4 Context hygiene, structured resilience, clock correction, idempotency, and transport tuning Historical tag; not a published v2 module
v2.0.5–v2.0.7 Request interceptors/hooks, initial OMS, stream state/channels, slog, OTel tracing, and metrics Historical tag; not a published v2 module
v2.0.8–v2.0.9 Context and typed-error hardening Historical tag; not a published v2 module
v2.1.0 go vet mutex-copy fixes Historical tag; not a published v2 module
v2.1.1 Error matching specificity, request-pipeline parity, OMS reconciliation, stream/MQTT lifecycle hardening, gRPC event telemetry, cancellation/leak coverage, and documentation reconciliation Repository tag; not a published v2 module; offline-tested and not newly live-verified

The next version number is intentionally unassigned for future work. The current hardening is represented by repository tag v2.1.4. The module-path decision is settled (stay on the /v2 import path, no /v2 migration); live verification remains a separate follow-up decision. See CHANGELOG.md and PLAN.md for the decision record.

Development

Target Description
make build compile the root module and every nested module listed by the Makefile
make vet vet the root module and every nested module listed by the Makefile
make test unit tests across those modules (sandbox tests remain environment-gated)
make test-race tests with the race detector across those modules
make cover coverage profiling across those modules
make lint golangci-lint (includes gosec)
make fuzz fuzz the data deserializers
make vuln govulncheck in every module
make docs build the MkDocs site (mkdocs build --strict)

Root go build ./... and go test ./... cover only the root module; use the Makefile targets for module-aware verification. The 2026-09-26 offline run measured 73.6% aggregate coverage in the root module and 80.8% in the nested broker/ module. These are reproducible measurements, not behavior or release guarantees; CI's 60% gate is root-only.

The current hardening was not newly live-verified. Historical live results are listed separately and must not be read as verification of the v2.1.1 repository tag.

License

Apache-2.0. See LICENSE.

Disclaimer

This SDK is an independent, unofficial wrapper around the Webull OpenAPI and is provided for reference and educational use only. It is not affiliated with or endorsed by Webull. Nothing here is investment advice. Use it at your own risk, and always follow Webull's terms of service and your own risk controls.

Documentation

Overview

Package webullapi4go is an idiomatic Go SDK for the Webull OpenAPI.

The root module provides the shared client in client and service clients in data, stream, trade, events, connect, display, brokerfd, and brokerfd/events. Broker API HK is provided by the separate broker module. The optional webull package aliases selected core-client types and options; it is not an aggregate service facade.

Shared public foundations live in pkg/errors, pkg/observability, pkg/resilience, pkg/transport, pkg/types, pkg/domain/money, and pkg/domain/order. Public financial DTOs use money.Money for required and response values, or *money.Money for optional and request values; decimal JSON strings remain the wire representation.

The current request, OMS, streaming, event-telemetry, and documentation hardening is tagged in repository v2.1.1. This is a repository patch release, not a published Go-semver v2 module; v2 module publication remains deferred, and this module remains github.com/shing1211/webullapi4go.

Directories

Path Synopsis
Package brokerfd provides the Webull Broker FD (US) API client.
Package brokerfd provides the Webull Broker FD (US) API client.
events
Package events provides a gRPC event-streaming client for the Webull Broker FD (US) API.
Package events provides a gRPC event-streaming client for the Webull Broker FD (US) API.
Package client is the public entry point to the Webull OpenAPI SDK.
Package client is the public entry point to the Webull OpenAPI SDK.
Package conformance holds the committed wire-conformance fixtures and the manifest that records where each one came from.
Package conformance holds the committed wire-conformance fixtures and the manifest that records where each one came from.
Package connect provides a client for the Webull Connect API, an OAuth 2.0 flow for third-party applications.
Package connect provides a client for the Webull Connect API, an OAuth 2.0 flow for third-party applications.
Package data provides the Webull Market Data API client.
Package data provides the Webull Market Data API client.
Package display provides a client for the Webull Display Solution API, a separate product from the core Market Data API with its own host, authentication, and endpoint paths.
Package display provides a client for the Webull Display Solution API, a separate product from the core Market Data API with its own host, authentication, and endpoint paths.
Package events provides a client for Webull's gRPC trade-event stream.
Package events provides a client for Webull's gRPC trade-event stream.
examples
account command
Command account lists the authenticated user's trading accounts and, for one account, prints its balance and open positions.
Command account lists the authenticated user's trading accounts and, for one account, prints its balance and open positions.
account-monitor command
Command account-monitor periodically prints an account's balance, buying power, and initial margin.
Command account-monitor periodically prints an account's balance, buying power, and initial margin.
auth command
Command auth creates or reuses a Webull access token and prints its status.
Command auth creates or reuses a Webull access token and prints its status.
brokerfd command
Command brokerfd demonstrates read-only Broker FD (US) API operations.
Command brokerfd demonstrates read-only Broker FD (US) API operations.
brokerfd-events command
Command brokerfd-events connects to the Webull Broker FD gRPC event stream, subscribes to events for one or more trading accounts, and prints each received data event until interrupted with Ctrl+C.
Command brokerfd-events connects to the Webull Broker FD gRPC event stream, subscribes to events for one or more trading accounts, and prints each received data event until interrupted with Ctrl+C.
data-fundamentals command
Command data-fundamentals fetches fundamental data for AAPL over the Market Data HTTP API.
Command data-fundamentals fetches fundamental data for AAPL over the Market Data HTTP API.
events command
Command events connects to the Webull gRPC trade-event stream, subscribes to order events for one trading account, and prints each decoded event until interrupted with Ctrl+C.
Command events connects to the Webull gRPC trade-event stream, subscribes to order events for one trading account, and prints each decoded event until interrupted with Ctrl+C.
marketdata command
Command marketdata fetches a market snapshot and recent daily bars for AAPL over the Market Data HTTP API.
Command marketdata fetches a market snapshot and recent daily bars for AAPL over the Market Data HTTP API.
options command
Command options demonstrates a multi-leg US options order preview.
Command options demonstrates a multi-leg US options order preview.
order command
Command order demonstrates the stock-order lifecycle: it previews a small AAPL limit buy and, only when explicitly opted in, places it far below the market and immediately cancels it.
Command order demonstrates the stock-order lifecycle: it previews a small AAPL limit buy and, only when explicitly opted in, places it far below the market and immediately cancels it.
path-probe command
Command path-probe compares the paths the SDK calls against the paths in the official Webull OpenAPI definition for endpoints where the two disagree.
Command path-probe compares the paths the SDK calls against the paths in the official Webull OpenAPI definition for endpoints where the two disagree.
probe command
probe tests data package endpoints and arbitrary paths against the live HK and US sandboxes.
probe tests data package endpoints and arbitrary paths against the live HK and US sandboxes.
streaming command
Command streaming connects to the Webull streaming broker over MQTT-over- WebSocket, subscribes to AAPL quote/snapshot/tick pushes, and consumes bounded channels until interrupted with Ctrl+C or the two-minute run limit expires.
Command streaming connects to the Webull streaming broker over MQTT-over- WebSocket, subscribes to AAPL quote/snapshot/tick pushes, and consumes bounded channels until interrupted with Ctrl+C or the two-minute run limit expires.
watchlist command
Command watchlist lists the authenticated user's watchlists.
Command watchlist lists the authenticated user's watchlists.
gen
internal
auth
Package auth implements Webull request signing and token lifecycle management.
Package auth implements Webull request signing and token lifecycle management.
region
Package region describes Webull OpenAPI deployment regions and the service endpoints (HTTP, MQTT, gRPC) for each environment.
Package region describes Webull OpenAPI deployment regions and the service endpoints (HTTP, MQTT, gRPC) for each environment.
pkg
domain/order
Package order implements the SDK's order management domain model: a validated state machine that enforces the legal transitions of a Webull order through its lifecycle.
Package order implements the SDK's order management domain model: a validated state machine that enforces the legal transitions of a Webull order through its lifecycle.
errors
Package errs defines the typed error model shared by every webullapi4go package.
Package errs defines the typed error model shared by every webullapi4go package.
observability
Package observability provides OpenTelemetry tracing and metrics integration for the Webull API SDK.
Package observability provides OpenTelemetry tracing and metrics integration for the Webull API SDK.
resilience
Package resilience groups the SDK's resilience primitives:
Package resilience groups the SDK's resilience primitives:
resilience/breaker
Package breaker implements the circuit-breaker pattern.
Package breaker implements the circuit-breaker pattern.
resilience/clock
Package clock provides the time source used by the SDK's resilience primitives so that retry, rate limiting, and circuit-breaking behaviour can be tested with an injected, deterministic clock.
Package clock provides the time source used by the SDK's resilience primitives so that retry, rate limiting, and circuit-breaking behaviour can be tested with an injected, deterministic clock.
resilience/ratelimit
Package ratelimit implements a token-bucket rate limiter and a keyed variant for applying independent limits per endpoint.
Package ratelimit implements a token-bucket rate limiter and a keyed variant for applying independent limits per endpoint.
resilience/retry
Package retry provides context-aware retries with exponential backoff and optional jitter.
Package retry provides context-aware retries with exponential backoff and optional jitter.
transport
Package transport provides the HTTP transport layer used by the public client.
Package transport provides the HTTP transport layer used by the public client.
transport/mqtt
Package mqtt is the low-level MQTT transport used by the public stream package to receive Webull market-data pushes.
Package mqtt is the low-level MQTT transport used by the public stream package to receive Webull market-data pushes.
types
Package types defines shared Webull domain types that are safe for external use.
Package types defines shared Webull domain types that are safe for external use.
Package stream provides Webull market-data streaming over MQTT.
Package stream provides Webull market-data streaming over MQTT.
Package trade provides the Webull Trading HTTP API client.
Package trade provides the Webull Trading HTTP API client.
Package webull provides optional aliases for selected core-client types and options.
Package webull provides optional aliases for selected core-client types and options.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL