Awesome Go

bingx-go

CategoryFinancial
SubcategoryFinancial
Stars52

Go client for BingX API v3 with 260+ methods, USDT-M/Coin-M futures, spot, TradFi, WebSocket streams, and copy trading

About bingx-go

This large README is shown as a plain-text preview. Read the full README at the source

# BingX Golang SDK

![BingX Golang SDK](https://i.postimg.cc/3RmFkpjD/bingx-go-banner-github.jpg)

[![CI](https://github.com/tigusigalpa/bingx-go/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tigusigalpa/bingx-go/actions/workflows/ci.yml)
[![Tests](https://github.com/tigusigalpa/bingx-go/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/tigusigalpa/bingx-go/actions/workflows/test.yml)
[![Go Version](https://img.shields.io/badge/Go-1.21+-00ADD8?style=flat-square&logo=go)](https://golang.org/)
[![License](https://img.shields.io/badge/license-MIT-green?style=flat-square)](LICENSE)
[![CodeQL](https://github.com/tigusigalpa/bingx-go/actions/workflows/codeql.yml/badge.svg?branch=main)](https://github.com/tigusigalpa/bingx-go/actions/workflows/codeql.yml)
[![Codecov](https://codecov.io/gh/tigusigalpa/bingx-go/graph/badge.svg)](https://codecov.io/gh/tigusigalpa/bingx-go)
[![GitHub Release](https://img.shields.io/github/v/release/tigusigalpa/bingx-go?style=flat-square)](https://github.com/tigusigalpa/bingx-go/releases)
[![GoDoc](https://img.shields.io/badge/godoc-reference-blue?style=flat-square&logo=go)](https://pkg.go.dev/github.com/tigusigalpa/bingx-go/v2)

Go client for the [BingX](https://bingx.com) cryptocurrency exchange API v3. Covers USDT-M and Coin-M perpetual futures,
TradFi (stocks, forex, commodities, indices), spot trading, copy trading, sub-accounts, and WebSocket streaming.
260+ API methods with full v3 support.

**Package:** [pkg.go.dev/github.com/tigusigalpa/bingx-go/v2](https://pkg.go.dev/github.com/tigusigalpa/bingx-go/v2)

> ⚠️ **Breaking change in v2.4.x:** the direct WebSocket client was renamed from `websocket.WebSocketClient` to `websocket.Client`, and its constructor from `websocket.NewWebSocketClient(url)` to `websocket.NewClient(url)`. High-level helpers such as `client.NewMarketDataStream()` and `client.NewAccountDataStream()` are unchanged.

> πŸ“– **[Full documentation available on Wiki](https://github.com/tigusigalpa/bingx-go/wiki)**

### πŸš€ Quick Links

- **[Changelog](CHANGELOG.md)** - Version history and release notes
- **[Examples](examples)** - Working code examples

## Table of Contents

- [Features](#features)
- [What's New in v3](#whats-new-in-v3) ⭐
- [Architecture](#architecture)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage Examples](#usage-examples)
  - [Market Data](#market-service---market-data)
  - [Account Management](#account-service---account-management)
  - [Trading Operations](#trade-service---trading-operations)
  - [Advanced Trading (v3)](#advanced-trading-features-v3) ⭐
  - [Spot Trading](#spot-trading---spot-order-management) ⭐
  - [Coin-M Futures](#coin-m-perpetual-futures)
  - [TradFi (Traditional Finance)](#tradfi-traditional-finance)
  - [WebSocket Streaming](#websocket-streaming)
    - [Market Data](#market-service---market-data)
    - [Account Management](#account-service---account-management)
    - [Trading Operations](#trade-service---trading-operations)
    - [Wallet Management](#wallet-service---wallet-management)
    - [Coin-M Futures](#coin-m-perpetual-futures)
    - [TradFi](#tradfi-traditional-finance)
    - [Sub-Accounts](#sub-account-management)
    - [Copy Trading](#copy-trading-operations)
    - [WebSocket Streaming](#websocket-streaming)
- [Advanced Features](#advanced-features)
- [Configuration](#configuration)
- [Error Handling](#error-handling)
- [Best Practices](#best-practices)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

---

## Features

### Key capabilities

| Feature              | Description                                                |
|----------------------|------------------------------------------------------------|
| **Real-Time Data**   | WebSocket support for live market data and account updates |
| **Order Types**      | MARKET, LIMIT, STOP, STOP_MARKET, TAKE_PROFIT, TRIGGER_LIMIT, TRAILING_STOP_MARKET, TRAILING_TP_SL |
| **Position Modes**   | One-way and Hedge mode support                             |
| **Margin Types**     | ISOLATED and CROSSED margin modes                          |
| **Time in Force**    | GTC, IOC, FOK order execution options                      |
| **Risk Management**  | Stop-loss, take-profit, trailing stops                     |
| **Batch Operations** | Create, modify, and cancel multiple orders at once         |
| **Historical Data**  | Access to comprehensive historical trading data            |

---

## Architecture

```
bingx-go/
β”œβ”€β”€ client.go              # Main client with service orchestration
β”œβ”€β”€ coinm_client.go        # Coin-M futures client
β”œβ”€β”€ tradfi_client.go       # TradFi (Traditional Finance) client
β”œβ”€β”€ http/
β”‚   └── client.go          # HTTP client with HMAC signing
β”œβ”€β”€ errors/
β”‚   └── errors.go          # Custom error types
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ market.go          # Market data service
β”‚   β”œβ”€β”€ account.go         # Account management service
β”‚   β”œβ”€β”€ trade.go           # Trading operations service
β”‚   β”œβ”€β”€ wallet.go          # Wallet operations service
β”‚   β”œβ”€β”€ spotaccount.go     # Spot account service
β”‚   β”œβ”€β”€ subaccount.go      # Sub-account service
β”‚   β”œβ”€β”€ copytrading.go     # Copy trading service
β”‚   β”œβ”€β”€ contract.go        # Contract service
β”‚   β”œβ”€β”€ listenkey.go       # WebSocket auth service
β”‚   β”œβ”€β”€ coinm/             # Coin-M specific services
β”‚   β”‚   β”œβ”€β”€ market.go
β”‚   β”‚   β”œβ”€β”€ trade.go
β”‚   β”‚   └── listenkey.go
β”‚   └── tradfi/            # TradFi specific services
β”‚       β”œβ”€β”€ market.go      # Stocks, forex, commodities market data
β”‚       β”œβ”€β”€ trade.go       # TradFi trading operations
β”‚       β”œβ”€β”€ account.go     # TradFi account management
β”‚       └── listenkey.go   # WebSocket auth for TradFi
└── examples/              # Usage examples
```

### Design Principles

- **Single Responsibility** - Each service handles a specific domain
- **Dependency Injection** - HTTP client injected for testability
- **Functional Options** - Flexible client configuration
- **Error Transparency** - Rich error types for debugging
- **Immutability** - Thread-safe by design

---

## Installation

- Go 1.21+
- BingX account with API keys (for authenticated endpoints)

```bash
go get github.com/tigusigalpa/bingx-go/v2
```

Only external dependency: `github.com/gorilla/websocket` (for WebSocket features)

---

## Quick Start

```go
package main

import (
    "fmt"
    "log"
    
    bingx "github.com/tigusigalpa/bingx-go/v2"
)

func main() {
    // Create client
    client := bingx.NewClient(
        "YOUR_API_KEY",
        "YOUR_API_SECRET",
        bingx.WithBaseURI("https://open-api.bingx.com"),
        bingx.WithSignatureEncoding("base64"),
    )
    
    // Get current price
    price, err := client.Market().GetLatestPrice("BTC-USDT")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("BTC price: %v\n", price)
    
    // Get account balance
    balance, err := client.Account().GetBalance()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Balance: %v\n", balance)
    
    // Create an order
    order, err := client.Trade().CreateOrder(map[string]interface{}{
        "symbol":       "BTC-USDT",
        "side":         "BUY",
        "type":         "LIMIT",
        "positionSide": "LONG",
        "price":        50000.0,
        "quantity":     0.001,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Order created: %v\n", order)
}
```

---

## Usage Examples

### Market Service - Market Data

```go
// Get futures symbols
symbols, err := client.Market().GetFuturesSymbols()

// Get spot symbols
spotSymbols, err := client.Market().GetSpotSymbols()

// Get all symbols
allSymbols, err := client.Market().GetAllSymbols()

// Get latest price
price, err := client.Market().GetLatestPrice("BTC-USDT")

// Get market depth
depth, err := client.Market().GetDepth("BTC-USDT", 20)

// Get K-lines
klines, err := client.Market().GetKlines("BTC-USDT", "1h", 100, nil, nil)

// Get spot K-lines with timezone (v2 endpoint)
// timeZone: 0=UTC (default), 8=UTC+8
timeZone := int64(8) // UTC+8
spotKlines, err := client.Market().GetSpotKlines("BTC-USDT", "1h", 100, nil, nil, &timeZone)

// Get 24hr ticker
ticker, err := client.Market().Get24hrTicker(nil) // nil for all symbols

// Get funding rate history
fundingRate, err := client.Market().GetFundingRateHistory("BTC-USDT", 100)

// Enhanced Market Data (v3)

// Open Interest
oi, err := client.Market().GetOpenInterest("BTC-USDT")

// Open Interest History
oiHistory, err := client.Market().GetOpenInterestHistory("BTC-USDT", "5m", 100, nil, nil)

// Funding Rate Info
fundingInfo, err := client.Market().GetFundingRateInfo("BTC-USDT")

// Book Ticker (Best Bid/Ask)
// GetBookTicker returns the raw BingX futures response envelope.
rawBookTicker, err := client.Market().GetBookTicker(&symbol)

// GetBookTickerData is recommended for the current v3 futures payload.
ticker, err := client.Market().GetBookTickerData(&symbol)
if err != nil {
    return err
}
fmt.Println("Best bid:", ticker.BidPrice)
fmt.Println("Best ask:", ticker.AskPrice)

// Spot uses a distinct array payload with bidVolume and askVolume fields.
spotTicker, err := client.Market().GetSpotBookTickerData(&symbol)

// Index Price
indexPrice, err := client.Market().GetIndexPrice("BTC-USDT")

// Ticker Price
tickerPrice, err := client.Market().GetTickerPrice(&symbol)
```

### Account Service - Account Management

```go
// Get account balance
balance, err := client.Account().GetBalance()

// Get positions
positions, err := client.Account().GetPositions(nil) // nil for all positions

// Get positions for specific symbol
btcPositions, err := client.Account().GetPositions(&symbol)

// Get account info
accountInfo, err := client.Account().GetAccountInfo()

// Get/Set leverage
leverage, err := client.Account().GetLeverage("BTC-USDT", nil)
err = client.Account().SetLeverage("BTC-USDT", "BOTH", 20, nil)

// Get/Set margin mode
marginMode, err := client.Account().GetMarginMode("BTC-USDT")
err = client.Account().SetMarginMode("BTC-USDT", "ISOLATED")

// Advanced Account Features (v3)

// Position Risk Metrics
risk, err := client.Account().GetPositionRisk(&symbol, nil)
// Returns: liquidation price, leverage, margin ratio, unrealized PnL, etc.

// Income/PnL History
incomeType := "REALIZED_PNL" // REALIZED_PNL, FUNDING_FEE, COMMISSION, etc.
income, err := client.Account().GetIncomeHistory(&symbol, &incomeType, nil, nil, 100, nil)

// Commission History
commissions, err := client.Account().GetCommissionHistory("BTC-USDT", nil, nil, 100, nil)

// Liquidation/Force Orders
forceOrders, err := client.Account().GetForceOrders(&symbol, nil, nil, nil, 100, nil)

// Position Mode (Hedge vs One-Way)
mode, err := client.Account().GetPositionMode(nil)
err = client.Account().SetPositionMode(true, nil) // true = hedge mode, false = one-way
```

### Trade Service - Trading Operations

```go
import "github.com/tigusigalpa/bingx-go/v2/services"

// Create order with new v3 order types
order, err := client.Trade().CreateOrder(map[string]interface{}{
    "symbol":       "BTC-USDT",
    "side":         "BUY",
    "type":         services.OrderTypeTriggerLimit, // New v3 order type
    "positionSide": "LONG",
    "price":        50000.0,
    "stopPrice":    49500.0,
    "quantity":     0.001,
})

// Trailing stop market order (v3)
order, err = client.Trade().CreateOrder(map[string]interface{}{
    "symbol":           "ETH-USDT",
    "side":             "SELL",
    "type":             services.OrderTypeTrailingStopMarket,
    "positionSide":     "SHORT",
    "activationPrice":  3000.0,
    "callbackRate":     1.0, // 1% callback
    "quantity":         0.1,
})

// Cancel order
orderID := "123456789"
err = client.Trade().CancelOrder("BTC-USDT", &orderID, nil, nil, nil)

// Cancel all orders
err = client.Trade().CancelAllOrders(nil, &symbol, nil, nil)

// Get order details
order, err := client.Trade().GetOrder("BTC-USDT", "123456789")

// Get open orders
openOrders, err := client.Trade().GetOpenOrders(nil, 100)

// Get order history
history, err := client.Trade().GetOrderHistory(&symbol, 100, nil, nil)

// Get user trades
trades, err := client.Trade().GetUserTrades(&symbol, 100, nil, nil)
```

### Advanced Trading Features (v3)

```go
import "github.com/tigusigalpa/bingx-go/v2/services"

// TWAP Orders - Execute large orders with minimal market impact
twapOrder, err := client.Trade().PlaceTWAPOrder(map[string]interface{}{
    "symbol":       "BTC-USDT",
    "side":         "BUY",
    "positionSide": "LONG",
    "quantity":     10.0,
    "duration":     3600, // Execute over 1 hour
    "interval":     60,   // Split into 1-minute intervals
})

// Query TWAP order
twap, err := client.Trade().GetTWAPOrder("twap_order_id", nil)

// List TWAP orders
status := "WORKING"
twapOrders, err := client.Trade().GetTWAPOrders(&symbol, &status, nil, nil, 100, nil)

// Cancel TWAP order
err = client.Trade().CancelTWAPOrder("twap_order_id", nil)

// One-Click Position Reversal - Instantly reverse LONG↔SHORT
result, err := client.Trade().OneClickReversePosition("BTC-USDT", nil)

// Multi-Assets Mode - Portfolio margin across multiple positions
err = client.Trade().SwitchMultiAssetsMode(true, nil)
mode, err := client.Trade().GetMultiAssetsMode(nil)
rules, err := client.Trade().GetMultiAssetsRules(nil)
margin, err := client.Trade().GetMultiAssetsMargin(nil)

// Auto Add Margin (Hedge Mode)
err = client.Trade().SetAutoAddMargin("BTC-USDT", "LONG", true, nil)
```

### Wallet Service - Wallet Management

```go
// Get deposit history
deposits, err := client.Wallet().GetDepositHistory("USDT", nil, nil, nil, 100)

// Get deposit address
address, err := client.Wallet().GetDepositAddress("USDT", "TRC20")

// Get withdrawal history
withdrawals, err := client.Wallet().GetWithdrawalHistory("USDT", nil, nil, nil, 100)

// Create withdrawal
withdrawal, err := client.Wallet().Withdraw("USDT", "TXxx...xxx", 100.0, "TRC20", nil)

// Get all coin info
coins, err := client.Wallet().GetAllCoinInfo()
```

### Spot Account Service - Spot Account

```go
import "github.com/tigusigalpa/bingx-go/v2/services"

// Get spot balance
balance, err := client.SpotAccount().GetBalance()

// Get a combined overview of all wallet types.
// Use AccountType* constants to filter by a single wallet, or pass nil for all.
overview, err := client.SpotAccount().GetAccountOverview(nil)

// Query only the USDT-M perpetual wallet
usdtOverview, err := client.SpotAccount().GetAccountOverview(&services.AccountTypeUSDTMPerp)

// Internal transfer with wallet type constants
// Wallet types: WalletTypeFund=1, WalletTypeStandardFutures=2,
//               WalletTypePerpetualFutures=3, WalletTypeSpot=4
userAccountType := 1 // 1=UID, 2=Phone, 3=Email
userAccount := "123456"
transfer, err := client.SpotAccount().InternalTransfer(
    "USDT",                           // coin
    services.WalletTypeSpot,          // walletType (4 = Spot Account)
    100.0,                            // amount
    userAccountType,                  // userAccountType
    userAccount,                      // userAccount
    nil,                              // callingCode (required when userAccountType=2)
    nil,                              // transferClientID
    nil,                              // recvWindow
)

// Get all spot account balances
allBalances, err := client.SpotAccount().GetAllAccountBalances()

// Deprecated: GetFundBalance is retired and no longer calls the API.
// Use GetAccountOverview instead.
```

**Supported account types** for `GetAccountOverview`:

```go
services.AccountTypeSpotFund     // "sopt"
services.AccountTypeStdFutures   // "stdFutures"
services.AccountTypeCoinMPerp    // "coinMPerp"
services.AccountTypeUSDTMPerp    // "USDTMPerp"
services.AccountTypeCopyTrading  // "copyTrading"
services.AccountTypeGrid         // "grid"
services.AccountTypeWealth       // "eran"
services.AccountTypeC2C          // "c2c"
```

### Spot Trading - Spot Order Management

`SpotAccount()` only covers balances and transfers; `SpotTrade()` is the
dedicated service for placing, cancelling, and querying **spot** orders
(as opposed to `Trade()`, which is for **perpetual futures** orders). Spot
trading buys/sells the underlying asset directly with no leverage or
position side, so its parameters and endpoints differ from `Trade()`.

**Decimal safety:** `SpotOrderRequest.Quantity`, `Price`, and
`QuoteOrderQty` are all `string`, never `float64`. Passing decimals as
`float64` risks silent binary-precision rounding (e.g. `0.1 + 0.2 !=
0.3` in IEEE 754), which can cause rejected orders or subtly wrong fills.
Always format your decimal amounts as exact strings.

```go
import "github.com/tigusigalpa/bingx-go/v2/services"

// Create a limit buy order (typed, validated client-side)
price := "60000"
quantity := "0.001"

order, err := client.SpotTrade().CreateOrderRequest(services.SpotOrderRequest{
    Symbol:   "BTC-USDT",
    Side:     services.SpotSideBuy,
    Type:     services.SpotOrderTypeLimit,
    Quantity: quantity,
    Price:    &price,
})

// Create a market buy order using a quote amount (spend 100 USDT)
quoteOrderQty := "100"
marketOrder, err := client.SpotTrade().CreateOrderRequest(services.SpotOrderRequest{
    Symbol:        "BTC-USDT",
    Side:          services.SpotSideBuy,
    Type:          services.SpotOrderTypeMarket,
    QuoteOrderQty: &quoteOrderQty,
})

// Advanced order types (TAKE_STOP_LIMIT, TAKE_STOP_MARKET, TRIGGER_LIMIT,
// TRIGGER_MARKET) or exchange-specific parameters: use the raw CreateOrder.
order, err = client.SpotTrade().CreateOrder(map[string]interface{}{
    "symbol":     "BTC-USDT",
    "side":       "SELL",
    "type":       "TRIGGER_LIMIT",
    "quantity":   "0.001",
    "price":      "58000",
    "stopPrice":  "59000",
})

// Cancel an order by orderID or clientOrderID
orderID := "123456789"
_, err = client.SpotTrade().CancelOrder("BTC-USDT", &orderID, nil)

// Cancel all open orders for a symbol (nil = all symbols)
_, err = client.SpotTrade().CancelAllOrders(&symbol)

// Cancel a batch of orders
_, err = client.SpotTrade().CancelBatchOrders("BTC-USDT", []string{"111", "222"}, nil)

// Query a single order, current open orders, order history, and fills
order, err = client.SpotTrade().GetOrder("BTC-USDT", &orderID, nil)
openOrders, err := client.SpotTrade().GetOpenOrders(&symbol) // no limit param on this endpoint
history, err := client.SpotTrade().GetOrderHistory(&symbol, 50, nil, nil)
trades, err := client.SpotTrade().GetTrades(&symbol, 100, nil, nil) // symbol is required here
```

**Order amendment:** BingX Spot does not support true in-place order
modification the way Futures does (`Trade().ModifyOrder`, which only
changes an existing order's quantity via `/openApi/swap/v1/trade/amend`).
Instead, the Spot API exposes a native cancel-and-replace endpoint
(`POST /openApi/spot/v1/trade/order/cancelReplace`) that atomically cancels
one order and places a new one in a single signed request. This is exposed
as `AmendOrder`:

```go
// Amend (cancel + replace) an order atomically
newPrice := "61000"
_, err = client.SpotTrade().AmendOrder(
    "BTC-USDT",
    &orderID, nil, // identify the order to cancel: orderID or clientOrderID
    services.SpotCancelReplaceStopOnFailure, // abort if cancel fails; or SpotCancelReplaceAllowFailure
    services.SpotOrderRequest{
        Side:     services.SpotSideBuy,
        Type:     services.SpotOrderTypeLimit,
        Quantity: "0.001",
        Price:    &newPrice,
    },
)
```

If you'd rather do it manually (or need it split into two independent,
auditable calls), the safe workflow is `CancelOrder` followed by
`CreateOrder`/`CreateOrderRequest`, checking the cancel result before
placing the new order.

**Not implemented β€” spot test orders:** Unlike `Trade().CreateTestOrder`
(Futures `POST /openApi/swap/v2/trade/order/test`), the BingX Spot API does
not expose a dry-run order-validation endpoint. `SpotTradeService`

Frequently Asked Questions

What is bingx-go?

bingx-go is a Financial library for the Go programming language. Go client for BingX API v3 with 260+ methods, USDT-M/Coin-M futures, spot, TradFi, WebSocket streams, and copy trading

How do I install bingx-go?

Install bingx-go with the Go module system using `go get tigusigalpa/bingx-go`. Check the repository for the current installation instructions.

What category does bingx-go belong to?

bingx-go is listed under Financial, specifically Financial.

← Back to Financial