go-binance SDK

repository·master·Indexed 24 days ago

https://github.com/ccxt/go-binance

A 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.

Tokens
40.5K
Snippets
58
Records
213
Agent score
83%

What's inside go-binance

  1. Overview of go-binance SDK

    master
    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.
  2. How Websocket works in go-binance

    master

    Websocket functionality does not require a Client instance. Instead, you call specialized binance.WsXxxServe functions, passing a handler for events and an error handler. These functions are blocking; they return a doneC channel that signals when the connection is closed, and a stopC channel that you can use to manually trigger a shutdown.

    To use a proxy with Websockets, you can either set the HTTPS_PROXY or HTTP_PROXY environment variables or use binance.SetWsProxyUrl(url) in your code.

  3. Security best practices for Binance API

    master

    When using the go-binance library, 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.
  4. How REST API services work

    master

    REST 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().

  5. Configure Binance API credentials

    master

    You 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.

    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 AppConfig variable in config.go with 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 production
  6. Import go-binance packages

    master

    Depending 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
    )
  7. Validate Binance API configuration

    master

    Before making API calls, you should validate the AppConfig to 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
    }
  8. Use Binance Testnet

    master

    To use the Binance Testnet instead of production, you must set the corresponding UseTestnet flag 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)
  9. How the WebSocket Client manages requests and reconnections

    master

    The Client maintains an internal RequestList to track the id of every message sent via Write.

    1. Tracking: When Write is called, the id is added to the list. When a message is read from the socket, the client unmarshals the id field and removes it from the list.
    2. Reconnection: If the connection fails, the read loop signals the handleReconnect goroutine. The client uses a backoff.Backoff strategy to restore the connection.
    3. State Recovery: Upon successful reconnection, the RequestList is recreated (RecreateList) to clear out stale pending requests from the previous connection, preventing the client from waiting indefinitely for responses that will never arrive.