go-binance SDK
repository·master·Indexed 24 days ago
https://github.com/ccxt/go-binanceA Golang SDK for the Binance exchange providing comprehensive support for REST and Websocket APIs. It includes implementations for Spot, USDT-M Futures, Coin-M Futures, and Options, with support for market data retrieval, order placement, and real-time data streaming. Compatible with Go version 1.8 or higher.
What's inside go-binance
- go-binance is a Golang SDK for the Binance API. It provides implementations for all REST APIs listed in the official Binance API documentation, as well as support for Websocket APIs. For optimal compatibility, ensure you are using Go version 1.8 or higher.
How Websocket works in go-binance
masterWebsocket functionality does not require a
Clientinstance. Instead, you call specializedbinance.WsXxxServefunctions, passing a handler for events and an error handler. These functions are blocking; they return adoneCchannel that signals when the connection is closed, and astopCchannel that you can use to manually trigger a shutdown.To use a proxy with Websockets, you can either set the
HTTPS_PROXYorHTTP_PROXYenvironment variables or usebinance.SetWsProxyUrl(url)in your code.Security best practices for Binance API
masterWhen using the
go-binancelibrary, follow these security guidelines:- Never commit API credentials to version control.
- Use environment variables for production deployments instead of hardcoding keys.
- Use the Testnet for testing and development to avoid accidental real-money trades.
- Always validate your configuration before making API calls.
How REST API services work
masterREST API interactions follow a chain-style pattern. A service instance represents a specific endpoint and is initialized via a
client.NewXXXService()method. You chain configuration methods (like.Symbol()or.Price()) and must call.Do(context.Background())at the end to execute the HTTP request.For testing purposes without sending real requests, you can use
.Test()instead of.Do().Configure Binance API credentials
masterYou can configure your Binance API credentials using either environment variables or direct configuration in the code. Using environment variables is the recommended approach for security and production deployments.
Option 1: Environment Variables (Recommended)
Set the following environment variables in your shell:
BINANCE_API_KEY: Your Binance API key.BINANCE_SECRET_KEY: Your Binance secret key.BINANCE_USE_TESTNET: Set to"true"for testing or"false"for production.
Option 2: Direct Configuration
Update the
AppConfigvariable inconfig.gowith your credentials.export BINANCE_API_KEY="your_api_key_here" export BINANCE_SECRET_KEY="your_secret_key_here" export BINANCE_USE_TESTNET="true" # Set to "false" for productionImport go-binance packages
masterDepending on the services you need, import the main v2 package and optional sub-packages for futures, delivery, or options:
import ( "github.com/adshao/go-binance/v2" "github.com/adshao/go-binance/v2/futures" // optional "github.com/adshao/go-binance/v2/delivery" // optional "github.com/adshao/go-binance/v2/options" // optional )import ( "github.com/adshao/go-binance/v2" "github.com/adshao/go-binance/v2/futures" // optional package "github.com/adshao/go-binance/v2/delivery" // optional package "github.com/adshao/go-binance/v2/options" // optional package )Install go-binance v1
masterThe v1 API has been moved to a separate branch. To use the v1 version, run:
go get github.com/adshao/go-binance/v1Install go-binance v2
masterTo install the latest version (v2) of the go-binance library, use the following command:
go get github.com/adshao/go-binance/v2Run Binance API examples
masterTo run all available examples in the directory at once, use the following command:
go run .Validate Binance API configuration
masterBefore making API calls, you should validate the
AppConfigto ensure credentials are present and valid. This prevents runtime errors during API execution.if err := AppConfig.Validate(); err != nil { fmt.Printf("Configuration error: %v\n", err) return }Use Binance Testnet
masterTo use the Binance Testnet instead of production, you must set the corresponding
UseTestnetflag before creating your client or calling websocket methods. Note that you must use Testnet-specific API keys.Spot Testnet:
binance.UseTestnet = true client := binance.NewClient(apiKey, secretKey)Futures Testnet:
import "github.com/adshao/go-binance/v2/futures" futures.UseTestnet = true client := futures.NewClient(apiKey, secretKey)Delivery Testnet:
import "github.com/adshao/go-binance/v2/delivery" delivery.UseTestnet = true client := delivery.NewClient(apiKey, secretKey)// Spot binance.UseTestnet = true client := binance.NewClient(apiKey, secretKey) // Futures (usd(s)-m futures) import "github.com/adshao/go-binance/v2/futures" futures.UseTestnet = true BinanceClient = futures.NewClient(ApiKey, SecretKey) // Delivery (coin-m futures) import "github.com/adshao/go-binance/v2/delivery" delivery.UseTestnet = true BinanceClient = delivery.NewClient(ApiKey, SecretKey)How the WebSocket Client manages requests and reconnections
masterThe
Clientmaintains an internalRequestListto track theidof every message sent viaWrite.- Tracking: When
Writeis called, theidis added to the list. When a message is read from the socket, the client unmarshals theidfield and removes it from the list. - Reconnection: If the connection fails, the
readloop signals thehandleReconnectgoroutine. The client uses abackoff.Backoffstrategy to restore the connection. - State Recovery: Upon successful reconnection, the
RequestListis recreated (RecreateList) to clear out stale pending requests from the previous connection, preventing the client from waiting indefinitely for responses that will never arrive.
- Tracking: When