bitget

package module
v0.20260625.2 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 14 Imported by: 0

README

go-bitget

Go Reference

A Go SDK for the Bitget exchange, covering both account systems.

Account system API Aligned to
UTA — Unified Trading Account /api/v3 REST + v3 WebSocket 2026-06-25
Classic — per-product account /api/v2 REST + v2 WebSocket 2026-06-23

Response structs are reconciled against the live API (not just the docs), so endpoints stay in sync with the dates above.

Install

go get github.com/UnipayFI/go-bitget@latest

Highlights

  • One signing/transport core shared by UTA (uta) and Classic (classic/*).
  • Fluent per-endpoint API: NewXxxService(...).SetFoo(...).Do(ctx).
  • Amounts as decimal.Decimal, ms timestamps as time.Time — Bitget's string-encoded numbers and ""/"0"/"-1" "not set" sentinels are decoded for you.
  • Every endpoint is tested against the live API, diffing real JSON keys against the struct.

Quick start

package main

import (
	"context"
	"fmt"

	bitget "github.com/UnipayFI/go-bitget"
	"github.com/UnipayFI/go-bitget/client"
	"github.com/UnipayFI/go-bitget/uta"
	"github.com/shopspring/decimal"
)

func main() {
	ctx := context.Background()

	c := bitget.NewUTAClient(
		client.WithAuth("apiKey", "apiSecret", "passphrase"),
		// client.WithProxy("socks5://127.0.0.1:7890"),
		// client.WithDemoTrading(true),
	)
	_ = c.SyncServerTime(ctx) // align clock to avoid signature drift

	// Public market data (no auth).
	instruments, _ := c.NewGetInstrumentsService(uta.CategorySpot).
		SetSymbol("BTCUSDT").Do(ctx)
	fmt.Println(instruments[0].Symbol, instruments[0].PricePrecision)

	// Private account data.
	assets, _ := c.NewGetAccountAssetsService().Do(ctx)
	fmt.Println("equity:", assets.AccountEquity)

	// Place a limit order.
	ref, err := c.NewPlaceOrderService(uta.CategorySpot, "BTCUSDT",
		decimal.RequireFromString("0.0001"), uta.SideBuy, uta.OrderTypeLimit).
		SetPrice(decimal.RequireFromString("30000")).
		SetTimeInForce(uta.TimeInForceGTC).
		Do(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Println("orderId:", ref.OrderID)
}

Authentication

Pass credentials from the Bitget API-management page:

c := bitget.NewUTAClient(client.WithAuth(apiKey, apiSecret, passphrase))

Requests are signed with HMAC-SHA256 over timestamp + method + requestPath(+ "?" + query) + body, base64-encoded into the ACCESS-SIGN header. For an RSA key or external signer, pass client.WithSignFn(fn).

Other options: WithProxy (http/https/socks5), WithBaseURL, WithLocale, WithDemoTrading, WithTimeOffset, WithLogger, WithHTTPClient.

WebSocket

ws := bitget.NewUTAWebSocketClient(
	client.WithWebSocketAuth(apiKey, apiSecret, passphrase), // private channels only
)

// Public ticker.
done, _, _ := ws.NewSubscribeTickerService(uta.WsInstTypeUSDTFutures, "BTCUSDT").
	Do(ctx, func(p *request.WsPush[[]uta.WsTicker], err error) {
		if err != nil {
			return
		}
		fmt.Println(p.Action, p.Data[0].LastPrice)
	})
close(done) // unsubscribe + close

// Private account (auto login).
ws.NewSubscribeAccountService().Do(ctx, func(p *request.WsPush[[]uta.WsAccount], err error) {
	// p.Data[0].TotalEquity, p.Data[0].Coin, ...
})

Each Do returns (done chan<- struct{}, stop <-chan struct{}, err error): close done to unsubscribe; stop closes when the reader exits. Ping/pong keepalive is automatic.

Orders can also be placed over a persistent, logged-in connection — a low-latency alternative to the REST trade endpoints:

tc, _ := ws.DialTrade(ctx) // connect + login
defer tc.Close()
price := decimal.RequireFromString("30000")
ack, _ := tc.PlaceOrder(ctx, uta.CategorySpot, uta.WsNewOrder{
	Symbol: "BTCUSDT", Side: uta.SideBuy, OrderType: uta.OrderTypeLimit,
	Qty: decimal.RequireFromString("0.0001"), Price: &price,
})
// tc.ModifyOrder / tc.CancelOrder / tc.BatchPlaceOrders / ...

Classic account

Each product line is a separate package (so PlaceOrder, GetTickers, Account, … don't collide), with the same NewXxxService(...).SetFoo(...).Do(ctx) shape:

sp := bitget.NewSpotClient(client.WithAuth(apiKey, apiSecret, passphrase))
tickers, _ := sp.NewGetTickersService().SetSymbol("BTCUSDT").Do(ctx)

mx := bitget.NewMixClient(client.WithAuth(apiKey, apiSecret, passphrase))
pos, _ := mx.NewGetAllPositionService(mix.ProductTypeUSDTFutures).Do(ctx)

Packages

UTA (uta/)

Area Files
Market data market*.go — instruments, tickers, orderbook, candles, funding rate, open interest, …
Account account*.go — assets, settings, leverage, fee rate, records, transfer, deposit, withdrawal, …
Trade trade_*.go — place/modify/cancel, batch, cancel-symbol, countdown-cancel, queries
Position / Strategy position.go strategy.go — positions, ADL rank, trigger & TPSL plans
Copy / Earn / Loans / Tax copy.go earn.go crypto_loan.go ins_loan.go tax.go
Broker / P2P / Sub-account broker.go p2p.go sub_account.go
WebSocket ws_public.go ws_private.go ws_trade.go

Classic (classic/)

Package Scope
common server time, announcements, trade-rate, all-account balance, convert / BGB-convert, virtual sub-accounts, insights
spot market, trade, plan (trigger) orders, account, wallet/transfer/deposit/withdrawal
mix futures market/account/position/trade/plan (USDT-/USDC-/COIN-M)
margin cross + isolated: assets, borrow/repay, orders, fills, records
copy futures & spot copy-trading: trader / follower / broker
earn savings, shark-fin, loan: subscribe/redeem/borrow/repay + records
broker affiliate insloan tax p2p broker sub-accounts & api-keys, affiliate, institutional loans, tax, p2p merchant
ws v2 WebSocket — public + private channels (spot/mix/margin) + order entry

Core

Package Scope
bitget.go entry point: NewUTAClient + NewSpotClient/NewMixClient/… + WS clients
client/ request/ REST client, options, HMAC signer, envelope decode, WS subscribe
common/ constants, global time.Time + decimal.Decimal JSON codec
cmd/bgraw/ dev tool: sign + dump any endpoint's raw response

Testing

Tests hit the live API and read credentials from the environment, skipping when unset:

export BITGET_API_KEY=...  BITGET_API_SECRET=...  BITGET_PASSPHRASE=...
export BITGET_PROXY=socks5://127.0.0.1:7890   # optional

go test ./uta/ -run TestAccountConfig -v            # one module at a time
BITGET_TEST_WRITE=1 go test ./uta/ -run TestOrder   # live order tests (tiny, reversible)
  • Run per module (-run TestXxx) — Bitget rate-limits to ~1–20 req/s, so the full suite can trip HTTP 429.
  • An IP whitelist on the key returns 40018 Invalid IP from non-whitelisted egress IPs.
  • Capability-gated reads (broker, copy-trading, P2P, loans) are skipped when the account lacks the capability — signing is still exercised.
  • State-changing tests are gated behind BITGET_TEST_WRITE=1 (minimal amounts, large-cap symbols). Destructive endpoints (downgrade, withdrawals, sub-account/broker creation) are implemented but never executed.

The cmd/bgraw helper dumps any endpoint's raw signed response:

go run ./cmd/bgraw GET /api/v3/account/info
go run ./cmd/bgraw GET /api/v3/account/financial-records "coin=USDT&limit=5"

License

MIT

Documentation

Overview

Package bitget is the entry point of the Bitget exchange Go SDK.

Install: go get github.com/UnipayFI/go-bitget Import: import bitget "github.com/UnipayFI/go-bitget"

The SDK covers BOTH of Bitget's account systems:

  • Unified Trading Account (UTA): the /api/v3/* REST API and the v3 WebSocket streams, exposed through package uta.
  • Classic account: the /api/v2/* REST API and the v2 WebSocket streams, split by product line into packages under classic/ (spot, mix (futures), margin, copy, earn, common, broker, affiliate, insloan, tax, p2p) plus the shared classic/ws stream client.

Authentication uses the HMAC-SHA256 scheme (ACCESS-KEY / ACCESS-SIGN / ACCESS-TIMESTAMP / ACCESS-PASSPHRASE); the core client/request/sign layers are shared by every product.

Quick start (UTA):

c := bitget.NewUTAClient(client.WithAuth(apiKey, apiSecret, passphrase))
if err := c.SyncServerTime(ctx); err != nil { /* ... */ }
assets, err := c.NewGetAccountAssetsService().Do(ctx)

Quick start (classic spot):

sp := bitget.NewSpotClient(client.WithAuth(apiKey, apiSecret, passphrase))
if err := sp.SyncServerTime(ctx); err != nil { /* ... */ }
tickers, err := sp.NewGetTickersService().Do(ctx)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewAffiliateClient added in v0.20260618.1

func NewAffiliateClient(options ...client.Options) *affiliate.AffiliateClient

NewAffiliateClient constructs a classic-account Affiliate REST client.

func NewBrokerClient added in v0.20260618.1

func NewBrokerClient(options ...client.Options) *broker.BrokerClient

NewBrokerClient constructs a classic-account Broker REST client.

func NewClassicWebSocketClient added in v0.20260618.1

func NewClassicWebSocketClient(options ...client.WebSocketOptions) *ws.WebSocketClient

NewClassicWebSocketClient constructs a WebSocket client for the classic-account v2 public and private streams (spot, futures, margin), including WebSocket order entry.

func NewCommonClient added in v0.20260618.1

func NewCommonClient(options ...client.Options) *common.CommonClient

NewCommonClient constructs a classic-account common REST client (server time, announcements, convert, trade-rate, virtual sub-accounts, big-data insights).

func NewCopyClient added in v0.20260618.1

func NewCopyClient(options ...client.Options) *copy.CopyClient

NewCopyClient constructs a classic-account Copy-Trading REST client.

func NewEarnClient added in v0.20260618.1

func NewEarnClient(options ...client.Options) *earn.EarnClient

NewEarnClient constructs a classic-account Earn REST client.

func NewInsLoanClient added in v0.20260618.1

func NewInsLoanClient(options ...client.Options) *insloan.InsLoanClient

NewInsLoanClient constructs a classic-account Institutional-Loan REST client.

func NewMarginClient added in v0.20260618.1

func NewMarginClient(options ...client.Options) *margin.MarginClient

NewMarginClient constructs a classic-account Margin (cross + isolated) REST client.

func NewMixClient added in v0.20260618.1

func NewMixClient(options ...client.Options) *mix.MixClient

NewMixClient constructs a classic-account Futures (Mix) REST client.

func NewP2PClient added in v0.20260618.1

func NewP2PClient(options ...client.Options) *p2p.P2PClient

NewP2PClient constructs a classic-account P2P REST client.

func NewSpotClient added in v0.20260618.1

func NewSpotClient(options ...client.Options) *spot.SpotClient

NewSpotClient constructs a classic-account Spot REST client.

func NewTaxClient added in v0.20260618.1

func NewTaxClient(options ...client.Options) *tax.TaxClient

NewTaxClient constructs a classic-account Tax REST client.

func NewUTAClient

func NewUTAClient(options ...client.Options) *uta.UTAClient

NewUTAClient constructs a REST client for the unified-account /api/v3/* endpoints.

func NewUTAWebSocketClient

func NewUTAWebSocketClient(options ...client.WebSocketOptions) *uta.UTAWebSocketClient

NewUTAWebSocketClient constructs a WebSocket client for the unified-account public and private streams.

Types

This section is empty.

Directories

Path Synopsis
classic
affiliate
Package affiliate implements the Bitget classic-account Affiliate/agent customer-info REST endpoints under /api/v2/broker/.
Package affiliate implements the Bitget classic-account Affiliate/agent customer-info REST endpoints under /api/v2/broker/.
broker
Package broker implements the Bitget classic-account Broker REST endpoints (commission, sub-accounts, api-keys) under /api/v2/broker/.
Package broker implements the Bitget classic-account Broker REST endpoints (commission, sub-accounts, api-keys) under /api/v2/broker/.
common
Package common implements the Bitget classic-account "common" REST endpoints: the cross-product utilities that are not specific to a single trading product — server time, announcements, trade fee rates, the all-account balance overview, coin conversion (Convert / BGB-Convert), virtual sub-account management, and the public big-data trading-insight feeds.
Package common implements the Bitget classic-account "common" REST endpoints: the cross-product utilities that are not specific to a single trading product — server time, announcements, trade fee rates, the all-account balance overview, coin conversion (Convert / BGB-Convert), virtual sub-account management, and the public big-data trading-insight feeds.
copy
Package copy implements the Bitget classic-account Copy-Trading REST endpoints (futures + spot, trader/follower/broker) under /api/v2/copy/.
Package copy implements the Bitget classic-account Copy-Trading REST endpoints (futures + spot, trader/follower/broker) under /api/v2/copy/.
earn
Package earn implements the Bitget classic-account Earn REST endpoints (savings, sharkfin, loan) under /api/v2/earn/.
Package earn implements the Bitget classic-account Earn REST endpoints (savings, sharkfin, loan) under /api/v2/earn/.
insloan
Package insloan implements the Bitget classic-account Institutional Loan REST endpoints under /api/v2/spot/ins-loan/.
Package insloan implements the Bitget classic-account Institutional Loan REST endpoints under /api/v2/spot/ins-loan/.
internal/apitest
Package apitest holds the shared, test-only helpers used by every classic-account product package (classic/spot, classic/mix, classic/margin, ...) to verify that the typed endpoint structs cover every field the live Bitget API returns.
Package apitest holds the shared, test-only helpers used by every classic-account product package (classic/spot, classic/mix, classic/margin, ...) to verify that the typed endpoint structs cover every field the live Bitget API returns.
internal/core
Package core holds the REST client base shared by every classic-account product package (classic/spot, classic/mix, classic/margin, ...).
Package core holds the REST client base shared by every classic-account product package (classic/spot, classic/mix, classic/margin, ...).
margin
Package margin implements the Bitget classic-account Margin (cross + isolated) REST endpoints under /api/v2/margin/.
Package margin implements the Bitget classic-account Margin (cross + isolated) REST endpoints under /api/v2/margin/.
mix
Package mix implements the Bitget classic-account Futures (Mix) REST (and, in the websocket files, the v2 Mix streams): market data, account, position, order and plan/trigger-order endpoints under the /api/v2/mix/ path namespace.
Package mix implements the Bitget classic-account Futures (Mix) REST (and, in the websocket files, the v2 Mix streams): market data, account, position, order and plan/trigger-order endpoints under the /api/v2/mix/ path namespace.
p2p
Package p2p implements the Bitget classic-account P2P merchant REST endpoints under /api/v2/p2p/.
Package p2p implements the Bitget classic-account P2P merchant REST endpoints under /api/v2/p2p/.
spot
Package spot implements the Bitget classic-account Spot REST (and, in the websocket files, the v2 Spot streams): market data, spot trading, plan (trigger) orders, account information and the wallet/transfer endpoints under the /api/v2/spot/ path namespace.
Package spot implements the Bitget classic-account Spot REST (and, in the websocket files, the v2 Spot streams): market data, spot trading, plan (trigger) orders, account information and the wallet/transfer endpoints under the /api/v2/spot/ path namespace.
tax
Package tax implements the Bitget classic-account Tax transaction-record REST endpoints under /api/v2/tax/.
Package tax implements the Bitget classic-account Tax transaction-record REST endpoints under /api/v2/tax/.
ws
Package ws implements the Bitget classic-account (non-UTA) v2 WebSocket streams: public market channels (ticker, candlestick, depth/order-book, trades, auction) and private channels (account, orders, fill, positions, plan orders, ...) for spot, futures (mix) and margin, plus WebSocket order entry (op:"trade").
Package ws implements the Bitget classic-account (non-UTA) v2 WebSocket streams: public market channels (ticker, candlestick, depth/order-book, trades, auction) and private channels (account, orders, fill, positions, plan orders, ...) for spot, futures (mix) and margin, plus WebSocket order entry (op:"trade").
cmd
bgraw command
Command bgraw signs and executes a single Bitget UTA REST call and pretty prints the raw response.
Command bgraw signs and executes a single Bitget UTA REST call and pretty prints the raw response.
pkg
log

Jump to

Keyboard shortcuts

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