Binance Go Spot SDK

This is a client library for the Binance Spot SDK API, enabling developers to interact programmatically with Binance's SPOT trading platform. The library provides tools for retrieving market data, executing trades, and managing orders through three distinct endpoints:
Table of Contents
Supported Features
- REST API Endpoints:
- WebSocket Endpoints: Real-time data streaming and request-response communication.
- Inclusion of test cases and examples for quick onboarding.
Installation
To use this library, ensure you have Go installed (version 1.25 or higher is recommended). You can install the library using the following command:
go get github.com/binance/binance-connector-go/clients/spot
Documentation
For detailed information, refer to the Binance API Documentation.
REST APIs
All REST API endpoints are available through the restapi module. The REST API enables you to fetch market data, manage trades, and access account information. Note that some endpoints require authentication using your Binance API credentials.
package main
import (
"context"
"encoding/json"
"log"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/common/v2/common"
)
func main() {
ExchangeInfo()
}
func ExchangeInfo() {
configuration := common.NewConfigurationRestAPI(
common.WithBasePath(common.SpotRestApiProdUrl),
)
apiClient := client.NewBinanceSpotClient(
client.WithRestAPI(configuration),
)
resp, err := apiClient.RestApi.GeneralAPI.ExchangeInfo(context.Background()).Execute()
if err != nil {
log.Println(err)
return
}
rateLimitsValue, _ := json.MarshalIndent(resp.RateLimits, "", " ")
log.Printf("Rate limits: %s\n", string(rateLimitsValue))
dataValue, _ := json.MarshalIndent(resp.Data, "", " ")
log.Printf("Response: %s\n", string(dataValue))
}
More examples can be found in the examples/restapi folder.
Configuration Options
The REST API supports the following advanced configuration options:
Timeout: Timeout for requests in milliseconds (default: 1000 ms).
Proxy: Proxy configuration:
Host: Proxy server hostname.
Port: Proxy server port.
Protocol: Proxy protocol (http or https).
Auth: Proxy authentication credentials:
Username: Proxy username.
Password: Proxy password.
KeepAlive: Enable HTTP keep-alive (default: true).
Compression: Enable response compression (default: true).
Retries: Number of retry attempts for failed requests (default: 3).
Backoff: Delay in milliseconds between retries (default: 1000 ms).
HTTPSAgent: Custom HTTPS agent for advanced TLS configuration.
TimeUnit: Specify the time unit for timestamps (e.g., milliseconds or microseconds).
PrivateKey: RSA or ED25519 private key for authentication.
PrivateKeyPassphrase: Passphrase for the private key, if encrypted.
Timeout
You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the Timeout example for detailed usage.
Proxy
The REST API supports HTTP/HTTPS proxy configurations. See the Proxy example for detailed usage.
Keep-Alive
Enable HTTP keep-alive for persistent connections. See the Keep-Alive example for detailed usage.
Compression
Enable or disable response compression. See the Compression example for detailed usage.
Retries
Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the Retries example for detailed usage.
HTTPS Agent
Customize the HTTPS agent for advanced TLS configurations. See the HTTPS Agent example for detailed usage.
Key Pair Based Authentication
The REST API supports key pair-based authentication for secure communication. You can use RSA or ED25519 keys for signing requests. See the Key Pair Based Authentication example for detailed usage.
Time Unit
The REST API supports different time units for timestamp values. See the Time Unit example for more details.
Certificate Pinning
To enhance security, you can use certificate pinning with the HTTPSAgent option in the configuration. This ensures the client only communicates with servers using specific certificates. See the Certificate Pinning example for detailed usage.
Error Handling
The REST API provides detailed error types to help you handle issues effectively:
ConnectorClientError: General client error.
RequiredError: Thrown when a required parameter is missing.
UnauthorizedError: Indicates missing or invalid authentication credentials.
ForbiddenError: Access to the requested resource is forbidden.
TooManyRequestsError: Rate limit exceeded.
RateLimitBanError: IP address banned for exceeding rate limits.
ServerError: Internal server error.
NetworkError: Issues with network connectivity.
NotFoundError: Resource not found.
BadRequestError: Invalid request.
See the Error Handling example for detailed usage.
Testnet
For testing purposes, /api/* endpoints can be used in the Spot Testnet. Update the BasePath in your configuration:
package main
import (
"context"
"encoding/json"
"log"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/common/v2/common"
)
configuration := common.NewConfigurationRestAPI(
common.WithBasePath(common.SpotRestApiTestnetUrl),
)
If BasePath is not provided, it defaults to https://api.binance.com.
Websocket APIs
The WebSocket API provides request-response communication for market data and trading actions. Use the websocketapi module to interact with these endpoints.
package main
import (
"encoding/json"
"log"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/common/v2/common"
)
func main() {
ExchangeInfo()
}
func ExchangeInfo() {
configuration := common.NewConfigurationWebsocketApi(
common.WithWsApiBasePath(common.SpotWebsocketApiProdUrl),
)
wsClient := client.NewBinanceSpotClient(
client.WithWebsocketAPI(configuration),
)
err := wsClient.WebsocketAPI.Connect()
if err != nil {
log.Printf("Error connecting to WebSocket: %v\n", err)
return
}
responseChan, errorChan, err := wsClient.WebsocketAPI.GeneralAPI.ExchangeInfo().ExecuteAsync()
if err != nil {
log.Printf("Error executing exchange info request: %v\n", err)
return
}
select {
case resp := <-responseChan:
result, _ := json.MarshalIndent(resp.Typed, "", " ")
log.Printf("Result: %s\n", result)
case err := <-errorChan:
log.Printf("Error: %v\n", err)
}
err = wsClient.WebsocketAPI.CloseWebSocketConnection()
if err != nil {
log.Printf("Error closing WebSocket connection: %v\n", err)
return
}
}
More examples are available in the examples/websocketapi folder.
Configuration Options
The WebSocket API supports the following advanced configuration options:
Timeout: Set the timeout for WebSocket requests (default: 5000 ms).
ReconnectDelay: Delay (ms) between reconnections.
Compression: Enable response compression.
Proxy: Proxy configuration:
Host: Proxy server hostname.
Port: Proxy server port.
Protocol: Proxy protocol (http or https).
Auth: Proxy authentication credentials:
Username: Proxy username.
Password: Proxy password.
Mode: Choose between single and pool connection modes.
single: A single WebSocket connection.
pool: A pool of WebSocket connections.
PoolSize: Define the number of WebSocket connections in pool mode.
TimeUnit: Specify the time unit for timestamps (e.g., milliseconds or microseconds).
PrivateKey: RSA or ED25519 private key for authentication.
PrivateKeyPassphrase: Passphrase for the private key, if encrypted.
Agent: Customize the WebSocket Agent for advanced configurations.
Timeout
Set the timeout for WebSocket API requests in milliseconds. See the Timeout example for detailed usage.
Reconnect Delay
Specify the delay in milliseconds between WebSocket reconnection attempts. See the Reconnect Delay example for detailed usage.
Compression
Enable or disable compression for WebSocket messages. See the Compression example for detailed usage.
Proxy
The WebSocket API supports HTTP/HTTPS proxy configurations. See the Proxy example for detailed usage.
Connection Mode
Choose between single and pool connection modes for WebSocket connections. The single mode uses a single WebSocket connection, while the pool mode uses a pool of WebSocket connections. See the Connection Mode example for detailed usage.
Time Unit
Specify the time unit for WebSocket API timestamps (e.g., milliseconds or microseconds). See the Time Unit example for detailed usage.
Key Pair Based Authentication
Use RSA or ED25519 private keys for WebSocket API authentication. See the Key Pair Authentication example for detailed usage.
WebSocket Agent
Customize the agent for advanced configurations. See the WebSocket Agent example for detailed usage.
Testnet
For testing purposes, the Websocket API also supports a testnet environment. Update the BasePath in your configuration:
package main
import (
"encoding/json"
"log"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/common/v2/common"
)
configuration := common.NewConfigurationWebsocketApi(
common.WithWsApiBasePath(common.SpotWebsocketApiTestnetUrl),
)
If BasePath is not provided, it defaults to wss://ws-api.binance.com:443/ws-api/v3.
Websocket Streams
WebSocket Streams provide real-time data feeds for market trades, candlesticks, and more. Use the websocket-streams module to subscribe to these streams.
package main
import (
"encoding/json"
"log"
"time"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/clients/spot/src/websocketstreams/models"
"github.com/binance/binance-connector-go/common/v2/common"
)
func main() {
AggTrade()
}
func AggTrade() {
configuration := common.NewConfigurationWebsocketStreams(
common.WithWsStreamsBasePath(common.SpotWebsocketStreamsProdUrl),
)
wsClient := client.NewBinanceSpotClient(
client.WithWebsocketStreams(configuration),
)
err := wsClient.WebsocketStreams.Connect([]string{})
if err != nil {
log.Fatalf("Error connecting to WebSocket: %v", err)
}
handler, err := wsClient.WebsocketStreams.WebSocketStreamsAPI.AggTrade().Symbol("bnbusdt").Execute()
if err != nil {
log.Fatalf("Error subscribing to stream: %v", err)
}
if err != nil {
log.Fatalf("Error subscribing to stream: %v", err)
}
handler.On("message", func(message models.AggTradeResponse) {
b, _ := json.MarshalIndent(message, "", " ")
log.Printf("Received message: %s\n", string(b))
})
for {
time.Sleep(1 * time.Second)
}
}
More examples are available in the examples/websocketstreams/WebSocketStreamsAPI folder.
Configuration Options
The WebSocket Streams API supports the following advanced configuration options:
ReconnectDelay: Delay (ms) between reconnections.
Compression: Enable response compression.
Proxy: Proxy configuration:
Host: Proxy server hostname.
Port: Proxy server port.
Protocol: Proxy protocol (http or https).
Auth: Proxy authentication credentials:
Username: Proxy username.
Password: Proxy password.
Mode: Choose between single and pool connection modes.
Single: A single WebSocket connection.
Pool: A pool of WebSocket connections.
PoolSize: Define the number of WebSocket connections in pool mode.
TimeUnit: Specify the time unit for timestamps (e.g., milliseconds or microseconds).
Agent: Customize the WebSocket Agent for advanced configurations.
Reconnect Delay
Specify the delay in milliseconds between WebSocket reconnection attempts for streams. See the Reconnect Delay example for detailed usage.
Compression
Enable or disable compression for WebSocket Streams messages. See the Compression example for detailed usage.
Proxy
The WebSocket Streams supports HTTP/HTTPS proxy configurations. See the Proxy example for detailed usage.
Connection Mode
Choose between single and pool connection modes for WebSocket Streams. The single mode uses a single WebSocket connection, while the pool mode uses a pool of WebSocket connections. See the Connection Mode example for detailed usage.
Time Unit
Specify the time unit for WebSocket Streams timestamps (e.g., milliseconds or microseconds). See the Time Unit example for detailed usage.
WebSocket Agent
Customize the agent for advanced configurations. See the WebSocket Agent example for detailed usage.
Unsubscribing from Streams
You can unsubscribe from specific WebSocket streams using the unsubscribe method. This is useful for managing active subscriptions without closing the connection.
package main
import (
"encoding/json"
"log"
"time"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/clients/spot/src/websocketstreams/models"
"github.com/binance/binance-connector-go/common/v2/common"
)
func main() {
AggTrade()
}
func AggTrade() {
configuration := common.NewConfigurationWebsocketStreams(
common.WithWsStreamsBasePath(common.SpotWebsocketStreamsProdUrl),
)
wsClient := client.NewBinanceSpotClient(
client.WithWebsocketStreams(configuration),
)
err := wsClient.WebsocketStreams.Connect([]string{})
if err != nil {
log.Fatalf("Error connecting to WebSocket: %v", err)
}
handler, err := wsClient.WebsocketStreams.WebSocketStreamsAPI.AggTrade().Symbol("bnbusdt").Execute()
if err != nil {
log.Fatalf("Error subscribing to stream: %v", err)
}
handler.On("message", func(message models.AggTradeResponse) {
b, _ := json.MarshalIndent(message, "", " ")
log.Printf("Received message: %s\n", string(b))
})
log.Println("Subscribed. Waiting 10 seconds...")
time.Sleep(10 * time.Second)
log.Println("Unsubscribing from stream...")
handler.Unsubscribe()
log.Println("Closing WebSocket connection...")
err = wsClient.WebsocketStreams.CloseWebSocketStreamConnection()
if err != nil {
log.Fatalf("Error closing WebSocket connection: %v", err)
}
}
Testnet
Websocket Streams also support a testnet environment for development and testing. Update the BasePath in your configuration:
package main
import (
"context"
"encoding/json"
"log"
client "github.com/binance/binance-connector-go/clients/spot"
"github.com/binance/binance-connector-go/common/v2/common"
)
configuration := common.NewConfigurationWebsocketStreams(
common.WithWsStreamsBasePath(common.SpotWebsocketStreamsTestnetUrl),
)
If BasePath is not provided, it defaults to wss://stream.binance.com:9443/stream.
Automatic Connection Renewal
The WebSocket connection is automatically renewed for both WebSocket API and WebSocket Streams connections, before the 24 hours expiration of the API key. This ensures continuous connectivity.
Testing
To run the test cases, use the following command:
go test ./tests/...
The tests cover:
- REST API endpoints
- WebSocket API and Streams
- Error handling and edge cases
Migration Guide
For information on migrating from previous versions of the Binance Go Spot SDK, please refer to the Migration Guide.
Contributing
Contributions are welcome!
Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.
To contribute:
- Open a GitHub issue describing your suggestion or the bug you've identified.
- If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.
Please ensure that all tests pass if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.
Thank you for your contributions!
Disclaimer
This SDK is provided by Binance on an "as is" and "as available" basis for use at your own risk. Binance makes no representations or warranties of any kind, whether express or implied, as to the operation of the SDK, its accuracy, reliability, completeness, or fitness for any particular purpose.
To the fullest extent permitted by law, Binance shall not be liable for any losses, damages, or expenses of any kind arising from or in connection with your use of, or inability to use, this SDK, including but not limited to any financial losses resulting from errors, bugs, interruptions, or inaccuracies in the SDK.
Your use of this SDK to access the Binance Platform is subject to the Binance API Key Terms and the Binance Terms of Use, which shall prevail in the event of any conflict with this disclaimer. You are solely responsible for any orders or transactions executed through the Binance Platform using this SDK.
This SDK is not intended to constitute investment advice or a recommendation to buy, sell, or hold any digital asset. You should independently evaluate and verify all information before acting.
License
This project is licensed under the MIT License. See the LICENSE file for details.