Comprehensive Go SDK for Binance cryptocurrency exchange APIs, supporting both REST and WebSocket APIs across all Binance products.
This repository is automatically generated by OpenXAPI.
For detailed usage examples and documentation:
- REST APIs: See rest/README.md
- WebSocket APIs: See ws/README.md
To contribute or report issues:
- Report Issues: GitHub Issues
- Update Code: Submit PRs to OpenXAPI
- Update Templates: Modify code generation templates
- Complete API Coverage: REST and WebSocket APIs for all Binance products
- Type Safety: Fully typed Go structs for all API responses
- Multiple Authentication: HMAC-SHA256, RSA, and Ed25519 support
- Production Ready: Comprehensive error handling and rate limiting
- Well Tested: Extensive integration tests with real API endpoints
- Auto-Generated: Generated from official OpenAPI/AsyncAPI specifications
Since ws
and rest
are separate modules, install them individually:
go get github.com/openxapi/binance-go/rest
go get github.com/openxapi/binance-go/ws
# REST API for specific products
go get github.com/openxapi/binance-go/rest/spot
go get github.com/openxapi/binance-go/rest/umfutures
go get github.com/openxapi/binance-go/rest/cmfutures
go get github.com/openxapi/binance-go/rest/options
go get github.com/openxapi/binance-go/rest/pmargin
# WebSocket API for specific products
go get github.com/openxapi/binance-go/ws/spot
go get github.com/openxapi/binance-go/ws/spot-streams
go get github.com/openxapi/binance-go/ws/umfutures
go get github.com/openxapi/binance-go/ws/umfutures-streams
go get github.com/openxapi/binance-go/ws/cmfutures
go get github.com/openxapi/binance-go/ws/cmfutures-streams
go get github.com/openxapi/binance-go/ws/options
go get github.com/openxapi/binance-go/ws/options-streams
go get github.com/openxapi/binance-go/ws/pmargin
This SDK is organized into two main components:
- OpenAPI-generated clients for HTTP REST endpoints
- Synchronous request-response operations
- Complete coverage of all Binance REST APIs
- AsyncAPI-generated clients for WebSocket connections
- Real-time data streams and async operations
- Event-driven architecture with handlers
Product | REST API | WebSocket API | WebSocket Streams |
---|---|---|---|
Spot | β
rest/spot |
β
ws/spot |
β
ws/spot-streams |
USDS-M Futures | β
rest/umfutures |
β
ws/umfutures |
β
ws/umfutures-streams |
COIN-M Futures | β
rest/cmfutures |
β
ws/cmfutures |
β
ws/cmfutures-streams |
Options | β
rest/options |
β
ws/options |
β
ws/options-streams |
Portfolio Margin | β
rest/pmargin |
β
ws/pmargin |
- |
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/openxapi/binance-go/rest/spot"
)
func main() {
// Create client
config := spot.NewConfiguration()
client := spot.NewAPIClient(config)
ctx := context.Background()
// Public endpoint - no authentication required
info, _, err := client.SpotAPI.GetExchangeInfoV3(ctx).Symbol("BTCUSDT").Execute()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Exchange info: %+v\n", info)
// Private endpoint - requires authentication
apiKey := os.Getenv("BINANCE_API_KEY")
secretKey := os.Getenv("BINANCE_SECRET_KEY")
if apiKey != "" && secretKey != "" {
auth := spot.NewAuth(apiKey)
auth.SetSecretKey(secretKey)
ctx, err = auth.ContextWithValue(ctx)
if err != nil {
log.Fatal(err)
}
account, _, err := client.SpotAPI.GetAccountV3(ctx).
Timestamp(time.Now().UnixMilli()).Execute()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Account: %+v\n", account)
}
}
package main
import (
"context"
"fmt"
"log"
"os"
"time"
spotws "github.com/openxapi/binance-go/ws/spot"
"github.com/openxapi/binance-go/ws/spot/models"
)
func main() {
// Create WebSocket client
client := spotws.NewClient()
// Set to testnet for testing (optional)
err := client.SetActiveServer("testnet1")
if err != nil {
log.Fatal(err)
}
// Authentication
apiKey := os.Getenv("BINANCE_API_KEY")
secretKey := os.Getenv("BINANCE_SECRET_KEY")
if apiKey != "" && secretKey != "" {
auth := &spotws.Auth{APIKey: apiKey}
auth.SetSecretKey(secretKey)
client.SetAuth(auth)
}
// Register event handlers for user data streams
client.HandleExecutionReportEvent(func(event *models.ExecutionReportEvent) error {
fmt.Printf("Execution Report: %+v\n", event)
return nil
})
client.HandleBalanceUpdateEvent(func(event *models.BalanceUpdateEvent) error {
fmt.Printf("Balance Update: %+v\n", event)
return nil
})
client.HandleOutboundAccountPositionEvent(func(event *models.OutboundAccountPositionEvent) error {
fmt.Printf("Account Position: %+v\n", event)
return nil
})
// Connect to WebSocket
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect()
// Get server time (public endpoint)
err = client.SendTime(ctx,
models.NewTimeRequest(),
func(response *models.TimeResponse, err error) error {
if err != nil {
log.Printf("Time request failed: %v", err)
return err
}
fmt.Printf("Server time: %d\n", response.Result.ServerTime)
return nil
})
if err != nil {
log.Fatal(err)
}
// Get account information (requires authentication)
if apiKey != "" && secretKey != "" {
err = client.SendAccountStatus(ctx,
models.NewAccountStatusRequest(),
func(response *models.AccountStatusResponse, err error) error {
if err != nil {
log.Printf("Account request failed: %v", err)
return err
}
fmt.Printf("Account: %+v\n", response.Result)
return nil
})
if err != nil {
log.Fatal(err)
}
}
// Keep connection alive for user data events
time.Sleep(30 * time.Second)
}
package main
import (
"context"
"fmt"
"log"
"time"
spotstreams "github.com/openxapi/binance-go/ws/spot-streams"
"github.com/openxapi/binance-go/ws/spot-streams/models"
)
func main() {
// Create streams client
client := spotstreams.NewClient()
// Set to testnet for testing (optional)
err := client.SetActiveServer("testnet1")
if err != nil {
log.Fatal(err)
}
// Register event handlers
client.HandleTradeEvent(func(event *models.TradeEvent) error {
fmt.Printf("Trade: %s Price: %s Quantity: %s\n",
event.Symbol, event.Price, event.Quantity)
return nil
})
client.HandleAggregateTradeEvent(func(event *models.AggregateTradeEvent) error {
fmt.Printf("Agg Trade: %s Price: %s Quantity: %s\n",
event.Symbol, event.Price, event.Quantity)
return nil
})
client.HandleKlineEvent(func(event *models.KlineEvent) error {
fmt.Printf("Kline: %s Open: %s High: %s Low: %s Close: %s\n",
event.Symbol, event.Kline.OpenPrice, event.Kline.HighPrice,
event.Kline.LowPrice, event.Kline.ClosePrice)
return nil
})
client.HandleTickerEvent(func(event *models.TickerEvent) error {
fmt.Printf("Ticker: %s Price: %s Change: %s%%\n",
event.Symbol, event.CurrentClosePrice, event.PriceChangePercent)
return nil
})
client.HandleBookTickerEvent(func(event *models.BookTickerEvent) error {
fmt.Printf("Book Ticker: %s Bid: %s Ask: %s\n",
event.Symbol, event.BidPrice, event.AskPrice)
return nil
})
client.HandleStreamError(func(event *models.ErrorResponse) error {
log.Printf("Stream error: %+v", event)
return nil
})
// Connect to WebSocket
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect()
// Subscribe to streams
streams := []string{
"btcusdt@trade",
"btcusdt@aggTrade",
"btcusdt@kline_1m",
"btcusdt@ticker",
"btcusdt@bookTicker",
}
err = client.Subscribe(ctx, streams)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Subscribed to streams: %v\n", streams)
// Keep the connection alive to receive events
time.Sleep(30 * time.Second)
// Unsubscribe from streams
err = client.Unsubscribe(ctx, streams)
if err != nil {
log.Printf("Failed to unsubscribe: %v", err)
} else {
fmt.Printf("Unsubscribed from streams: %v\n", streams)
}
}
All authentication methods are supported across both REST and WebSocket APIs:
// REST API
auth := spot.NewAuth(apiKey)
auth.SetSecretKey(secretKey)
ctx, err := auth.ContextWithValue(ctx)
// WebSocket API
auth := &spotws.Auth{APIKey: apiKey}
auth.SetSecretKey(secretKey)
client.SetAuth(auth)
// REST API
auth := spot.NewAuth(apiKey)
auth.PrivateKeyPath = "/path/to/private_key.pem"
ctx, err := auth.ContextWithValue(ctx)
// WebSocket API
auth := &spotws.Auth{
APIKey: apiKey,
PrivateKeyPath: "/path/to/private_key.pem",
}
client.SetAuth(auth)
// WebSocket API (Ed25519 sessions)
auth := &spotws.Auth{
APIKey: apiKey,
PrivateKeyPath: "/path/to/ed25519_private_key.pem",
}
client.SetAuth(auth)
- REST:
https://api.binance.com
- WebSocket API:
wss://ws-api.binance.com/ws-api/v3
- WebSocket Streams:
wss://stream.binance.com/ws
- REST:
https://testnet.binance.vision
- WebSocket API:
wss://ws-api.testnet.binance.vision/ws-api/v3
- WebSocket Streams:
wss://stream.testnet.binance.vision/ws
// Switch to testnet
client.SetActiveServer("testnet1")
- REST API Documentation - Complete REST API guide
- WebSocket API Documentation - WebSocket API and Streams guide
- Official Binance API Docs - Binance developer documentation
The SDK includes comprehensive integration tests that demonstrate real-world usage:
# Set up environment variables
export BINANCE_API_KEY="your_api_key"
export BINANCE_SECRET_KEY="your_secret_key"
# Test REST APIs
cd rest/spot && go test -v
cd rest/umfutures && go test -v
# Test WebSocket APIs
cd ws/spot && go test -v
cd ws/spot-streams && go test -v
cd ws/umfutures && go test -v
// High-frequency trading with WebSocket streams
client.HandleTradeEvent(func(event *models.TradeEvent) error {
// Implement your trading strategy
return processTradeSignal(event)
})
// Monitor account balances and positions
account, _, err := client.SpotAPI.GetAccountV3(ctx).Execute()
if err != nil {
return err
}
return updatePortfolio(account)
// Collect real-time market data
client.HandleKlineEvent(func(event *models.KlineEvent) error {
return storeCandlestickData(event)
})
// Monitor liquidations and funding rates
client.HandleLiquidationEvent(func(event *models.LiquidationEvent) error {
return assessMarketRisk(event)
})
Please respect Binance API rate limits:
- REST API: Varies by endpoint (typically 1200 requests/minute)
- WebSocket: 5 messages per second per connection
- Streams: 1024 streams per connection
The SDK automatically handles rate limiting for REST APIs. For WebSocket APIs, implement your own rate limiting logic.
// REST API errors
if err != nil {
if apiErr, ok := err.(*spot.GenericOpenAPIError); ok {
fmt.Printf("API Error: %s\n", apiErr.Error())
fmt.Printf("Response: %s\n", string(apiErr.Body()))
}
}
// WebSocket errors
client.HandleError(func(err error) {
log.Printf("WebSocket error: %v", err)
})
import "net/http"
import "net/url"
// Configure proxy for REST APIs
proxyURL, _ := url.Parse("http://proxy:8080")
config := spot.NewConfiguration()
config.HTTPClient = &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
}
// For WebSocket APIs, set environment variable
os.Setenv("HTTP_PROXY", "http://proxy:8080")
// REST API timeouts
config := spot.NewConfiguration()
config.HTTPClient.Timeout = 30 * time.Second
// WebSocket connection timeouts
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := client.Connect(ctx)
- Never hardcode API keys - Use environment variables
- Use testnet for development - Avoid accidental real trades
- Implement proper error handling - Don't ignore API errors
- Respect rate limits - Implement backoff strategies
- Validate signatures - Ensure secure authentication
- Use read-only keys when possible - Limit API key permissions
This SDK is auto-generated from official Binance API specifications. To contribute:
- Report Issues: GitHub Issues
- Update Specifications: Submit PRs to OpenXAPI
- Improve Templates: Enhance the code generation templates
Do not edit the generated code directly - changes will be overwritten on the next generation.
- Go: 1.19 or later
- Dependencies: Managed via Go modules
This project is licensed under the MIT License - see the LICENSE file for details.
- Reuse clients - Don't create new clients for every request
- Use WebSocket for real-time data - More efficient than polling REST APIs
- Batch operations - Use batch endpoints when available
- Connection pooling - Configure HTTP client for optimal performance
- Local caching - Cache static data like exchange info
- Documentation: Binance API Docs
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- OpenXAPI Project: OpenXAPI GitHub
This is an unofficial SDK. Use at your own risk. Always refer to the official Binance API documentation for the most up-to-date information. The authors are not responsible for any financial losses incurred through the use of this SDK.
SDK Version | Binance API Version | Go Version |
---|---|---|
v1.x | 2024+ | 1.19+ |
Happy Trading! π