{"id":36441795,"url":"https://github.com/tigusigalpa/bingx-go","last_synced_at":"2026-01-11T21:59:38.683Z","repository":{"id":328664112,"uuid":"1115853631","full_name":"tigusigalpa/bingx-go","owner":"tigusigalpa","description":"Full-featured Golang SDK for BingX cryptocurrency exchange API. Supports USDT-M \u0026 Coin-M perpetual futures, spot trading, market data, WebSocket streams, account management, and copy trading. Type-safe, production-ready with HMAC-SHA256 security. Complete API coverage with idiomatic Go interfaces.","archived":false,"fork":false,"pushed_at":"2025-12-14T15:50:58.000Z","size":28,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-17T00:34:46.816Z","etag":null,"topics":["bingx","bingx-api","cryptocurrency","go","golang","sdk"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tigusigalpa.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-13T17:29:37.000Z","updated_at":"2025-12-14T15:53:31.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/tigusigalpa/bingx-go","commit_stats":null,"previous_names":["tigusigalpa/bingx-go"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/tigusigalpa/bingx-go","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fbingx-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fbingx-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fbingx-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fbingx-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tigusigalpa","download_url":"https://codeload.github.com/tigusigalpa/bingx-go/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tigusigalpa%2Fbingx-go/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28324771,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-11T18:42:50.174Z","status":"ssl_error","status_checked_at":"2026-01-11T18:39:13.842Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bingx","bingx-api","cryptocurrency","go","golang","sdk"],"created_at":"2026-01-11T21:59:38.590Z","updated_at":"2026-01-11T21:59:38.664Z","avatar_url":"https://github.com/tigusigalpa.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# BingX Go SDK\n\n\u003cdiv align=\"center\"\u003e\n\n![BingX Golang SDK](https://github.com/user-attachments/assets/61babf48-746f-469e-aeed-5058a9337d86)\n\n[![Go Version](https://img.shields.io/badge/Go-1.21+-00ADD8?style=flat-square\u0026logo=go)](https://golang.org/)\n[![License](https://img.shields.io/badge/license-MIT-green?style=flat-square)](LICENSE)\n[![Go Report Card](https://goreportcard.com/badge/github.com/tigusigalpa/bingx-go?style=flat-square)](https://goreportcard.com/report/github.com/tigusigalpa/bingx-go)\n[![GitHub Release](https://img.shields.io/github/v/release/tigusigalpa/bingx-go?style=flat-square)](https://github.com/tigusigalpa/bingx-go/releases)\n[![GoDoc](https://img.shields.io/badge/godoc-reference-blue?style=flat-square\u0026logo=go)](https://pkg.go.dev/github.com/tigusigalpa/bingx-go)\n\n**Professional-Grade Go SDK for BingX Cryptocurrency Exchange**\n\n*Comprehensive API integration for USDT-M \u0026 Coin-M Perpetual Futures, Spot Trading, and Advanced Market Operations*\n\n[Features](#-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Documentation](#-documentation) • [Examples](#-usage-examples) • [Support](#-support)\n\n\u003c/div\u003e\n\n---\n\n## 📖 Table of Contents\n\n- [About](#-about)\n- [Why Choose BingX Go SDK](#-why-choose-bingx-go-sdk)\n- [Features](#-features)\n- [Architecture](#-architecture)\n- [Installation](#-installation)\n- [Quick Start](#-quick-start)\n- [Usage Examples](#-usage-examples)\n    - [Market Data](#market-service---market-data)\n    - [Account Management](#account-service---account-management)\n    - [Trading Operations](#trade-service---trading-operations)\n    - [Wallet Management](#wallet-service---wallet-management)\n    - [Coin-M Futures](#coin-m-perpetual-futures)\n    - [Sub-Accounts](#sub-account-management)\n    - [Copy Trading](#copy-trading-operations)\n- [Advanced Features](#-advanced-features)\n- [Configuration](#-configuration)\n- [Error Handling](#-error-handling)\n- [Best Practices](#-best-practices)\n- [Testing](#-testing)\n- [Performance](#-performance)\n- [Roadmap](#-roadmap)\n- [Contributing](#-contributing)\n- [License](#-license)\n- [Support](#-support)\n\n---\n\n## ✨ About\n\n**BingX Go SDK** is an enterprise-grade, production-ready Go library designed for seamless integration with the BingX\ncryptocurrency exchange API. Built from the ground up with modern Go idioms and best practices, this SDK provides\ndevelopers with a robust, type-safe, and highly performant solution for algorithmic trading, market analysis, and\nportfolio management.\n\n### 🎯 Mission\n\nTo empower Go developers with a reliable, efficient, and comprehensive toolkit for building sophisticated cryptocurrency\ntrading applications on the BingX platform.\n\n---\n\n## 🌟 Why Choose BingX Go SDK?\n\n### **Complete API Coverage**\n\n- ✅ **220+ API Methods** - Every endpoint from BingX API v1 \u0026 v2\n- ✅ **USDT-M Perpetual Futures** - Full support for USDT-margined contracts\n- ✅ **Coin-M Perpetual Futures** - Complete Coin-margined futures implementation\n- ✅ **Spot Trading** - Comprehensive spot market operations\n- ✅ **Advanced Features** - Copy trading, sub-accounts, TWAP orders\n\n### **Enterprise-Grade Quality**\n\n- 🛡️ **Type-Safe** - Leverages Go's strong typing for compile-time safety\n- 🔒 **Secure** - HMAC-SHA256 signature with configurable encoding (hex/base64)\n- ⚡ **High Performance** - Optimized for low latency and high throughput\n- 🏗️ **Modular Architecture** - Clean separation of concerns with service-based design\n- 📝 **Well Documented** - Comprehensive inline documentation and examples\n\n### **Developer Experience**\n\n- 🚀 **Easy to Use** - Intuitive API with fluent interfaces\n- 🔧 **Flexible Configuration** - Functional options pattern for customization\n- 🎨 **Idiomatic Go** - Follows Go best practices and conventions\n- 🧪 **Testable** - Designed with testing in mind\n- 📦 **Zero Dependencies** - Minimal external dependencies (only gorilla/websocket)\n\n### **Production Ready**\n\n- 🔄 **Maintained** - Regular updates and bug fixes\n- 📊 **Monitoring Ready** - Comprehensive error types for observability\n- 🌐 **WebSocket Support** - Real-time data streaming capabilities\n- 🔐 **Rate Limit Handling** - Built-in rate limit exception handling\n\n---\n\n## 🚀 Features\n\n### 📊 Comprehensive Service Coverage\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd width=\"50%\" valign=\"top\"\u003e\n\n#### **USDT-M Perpetual Futures**\n\n- **🏪 Market Service** (40+ methods)\n    - Real-time \u0026 historical prices\n    - Market depth \u0026 order books\n    - Candlestick data (K-lines)\n    - 24hr tickers \u0026 statistics\n    - Funding rates \u0026 premium index\n    - Aggregate \u0026 recent trades\n    - Long/short ratios\n    - Basis data \u0026 sentiment analysis\n\n- **👤 Account Service** (20+ methods)\n    - Balance \u0026 asset management\n    - Position tracking \u0026 monitoring\n    - Leverage configuration\n    - Margin mode management\n    - Trading fees \u0026 commissions\n    - API permissions \u0026 rate limits\n    - Balance history \u0026 deposits\n\n- **🔄 Trade Service** (25+ methods)\n    - Order creation \u0026 management\n    - Batch order operations\n    - Order modification \u0026 cancellation\n    - Position management\n    - Trade history \u0026 analytics\n    - Test orders (sandbox)\n    - Commission calculations\n\n- **💰 Wallet Service** (6+ methods)\n    - Deposit \u0026 withdrawal management\n    - Address generation\n    - Transaction history\n    - Multi-coin support\n    - Network selection\n\n\u003c/td\u003e\n\u003ctd width=\"50%\" valign=\"top\"\u003e\n\n#### **Advanced Features**\n\n- **💵 Spot Account Service** (8+ methods)\n    - Spot balance management\n    - Universal transfers\n    - Internal transfers\n    - Transfer history\n    - Multi-account support\n\n- **👥 Sub-Account Service** (20+ methods)\n    - Sub-account creation \u0026 management\n    - API key management\n    - Asset transfers\n    - Deposit address management\n    - Authorization controls\n\n- **🔄 Copy Trading Service** (13+ methods)\n    - Futures copy trading\n    - Spot copy trading\n    - Profit tracking\n    - Commission management\n    - Trading pair configuration\n\n- **📋 Contract Service** (3+ methods)\n    - Standard contract positions\n    - Order history\n    - Balance queries\n\n- **🔐 Listen Key Service** (3+ methods)\n    - WebSocket authentication\n    - Key generation \u0026 extension\n    - Session management\n\n#### **Coin-M Perpetual Futures**\n\n- **🪙 Coin-M Market** (6+ methods)\n    - Contract specifications\n    - Ticker \u0026 price data\n    - Market depth\n    - K-line data\n    - Open interest\n    - Funding rates\n\n- **🪙 Coin-M Trade** (17+ methods)\n    - Order management\n    - Position tracking\n    - Leverage \u0026 margin\n    - Balance queries\n    - Trade history\n\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n### 🎯 Key Capabilities\n\n| Feature              | Description                                                |\n|----------------------|------------------------------------------------------------|\n| **Real-Time Data**   | WebSocket support for live market data and account updates |\n| **Order Types**      | MARKET, LIMIT, STOP, STOP_MARKET, TAKE_PROFIT, and more    |\n| **Position Modes**   | One-way and Hedge mode support                             |\n| **Margin Types**     | ISOLATED and CROSSED margin modes                          |\n| **Time in Force**    | GTC, IOC, FOK order execution options                      |\n| **Risk Management**  | Stop-loss, take-profit, trailing stops                     |\n| **Batch Operations** | Create, modify, and cancel multiple orders at once         |\n| **Historical Data**  | Access to comprehensive historical trading data            |\n\n---\n\n## 🏗️ Architecture\n\nThe SDK follows a clean, modular architecture designed for maintainability and extensibility:\n\n```\nbingx-go/\n├── client.go              # Main client with service orchestration\n├── coinm_client.go        # Coin-M futures client\n├── http/\n│   └── client.go          # HTTP client with HMAC signing\n├── errors/\n│   └── errors.go          # Custom error types\n├── services/\n│   ├── market.go          # Market data service\n│   ├── account.go         # Account management service\n│   ├── trade.go           # Trading operations service\n│   ├── wallet.go          # Wallet operations service\n│   ├── spotaccount.go     # Spot account service\n│   ├── subaccount.go      # Sub-account service\n│   ├── copytrading.go     # Copy trading service\n│   ├── contract.go        # Contract service\n│   ├── listenkey.go       # WebSocket auth service\n│   └── coinm/             # Coin-M specific services\n│       ├── market.go\n│       ├── trade.go\n│       └── listenkey.go\n└── examples/              # Usage examples\n```\n\n### Design Principles\n\n- **Single Responsibility** - Each service handles a specific domain\n- **Dependency Injection** - HTTP client injected for testability\n- **Functional Options** - Flexible client configuration\n- **Error Transparency** - Rich error types for debugging\n- **Immutability** - Thread-safe by design\n\n---\n\n## 📦 Installation\n\n### Prerequisites\n\n- **Go 1.21+** - Latest stable Go version recommended\n- **Git** - For package management\n- **BingX Account** - API keys required for authenticated endpoints\n\n### Quick Install\n\n```bash\n# Install the package\ngo get github.com/tigusigalpa/bingx-go\n\n# Update to latest version\ngo get -u github.com/tigusigalpa/bingx-go\n```\n\n### Verify Installation\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    bingx \"github.com/tigusigalpa/bingx-go\"\n)\n\nfunc main() {\n    client := bingx.NewClient(\"\", \"\", bingx.WithBaseURI(\"https://open-api.bingx.com\"))\n    fmt.Println(\"BingX SDK installed successfully!\")\n}\n```\n\n### Dependencies\n\nThe SDK has minimal dependencies:\n\n- `github.com/gorilla/websocket` - WebSocket support (optional, only if using WebSocket features)\n\n---\n\n## ⚡ Quick Start\n\n### Basic Usage\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \n    bingx \"github.com/tigusigalpa/bingx-go\"\n)\n\nfunc main() {\n    // Create client\n    client := bingx.NewClient(\n        \"YOUR_API_KEY\",\n        \"YOUR_API_SECRET\",\n        bingx.WithBaseURI(\"https://open-api.bingx.com\"),\n        bingx.WithSignatureEncoding(\"base64\"),\n    )\n    \n    // Get current price\n    price, err := client.Market().GetLatestPrice(\"BTC-USDT\")\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"BTC price: %v\\n\", price)\n    \n    // Get account balance\n    balance, err := client.Account().GetBalance()\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"Balance: %v\\n\", balance)\n    \n    // Create an order\n    order, err := client.Trade().CreateOrder(map[string]interface{}{\n        \"symbol\":       \"BTC-USDT\",\n        \"side\":         \"BUY\",\n        \"type\":         \"LIMIT\",\n        \"positionSide\": \"LONG\",\n        \"price\":        50000.0,\n        \"quantity\":     0.001,\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Printf(\"Order created: %v\\n\", order)\n}\n```\n\n---\n\n## 📚 Usage Examples\n\n### Market Service - Market Data\n\n```go\n// Get futures symbols\nsymbols, err := client.Market().GetFuturesSymbols()\n\n// Get spot symbols\nspotSymbols, err := client.Market().GetSpotSymbols()\n\n// Get all symbols\nallSymbols, err := client.Market().GetAllSymbols()\n\n// Get latest price\nprice, err := client.Market().GetLatestPrice(\"BTC-USDT\")\n\n// Get market depth\ndepth, err := client.Market().GetDepth(\"BTC-USDT\", 20)\n\n// Get K-lines\nklines, err := client.Market().GetKlines(\"BTC-USDT\", \"1h\", 100, nil, nil)\n\n// Get 24hr ticker\nticker, err := client.Market().Get24hrTicker(nil) // nil for all symbols\n\n// Get funding rate history\nfundingRate, err := client.Market().GetFundingRateHistory(\"BTC-USDT\", 100)\n```\n\n### Account Service - Account Management\n\n```go\n// Get account balance\nbalance, err := client.Account().GetBalance()\n\n// Get positions\npositions, err := client.Account().GetPositions(nil) // nil for all positions\n\n// Get positions for specific symbol\nbtcPositions, err := client.Account().GetPositions(\u0026symbol)\n\n// Get account info\naccountInfo, err := client.Account().GetAccountInfo()\n\n// Get/Set leverage\nleverage, err := client.Account().GetLeverage(\"BTC-USDT\", nil)\nerr = client.Account().SetLeverage(\"BTC-USDT\", \"BOTH\", 20, nil)\n\n// Get/Set margin mode\nmarginMode, err := client.Account().GetMarginMode(\"BTC-USDT\")\nerr = client.Account().SetMarginMode(\"BTC-USDT\", \"ISOLATED\")\n```\n\n### Trade Service - Trading Operations\n\n```go\n// Create order\norder, err := client.Trade().CreateOrder(map[string]interface{}{\n    \"symbol\":       \"BTC-USDT\",\n    \"side\":         \"BUY\",\n    \"type\":         \"MARKET\",\n    \"positionSide\": \"LONG\",\n    \"quantity\":     0.001,\n})\n\n// Cancel order\norderID := \"123456789\"\nerr = client.Trade().CancelOrder(\"BTC-USDT\", \u0026orderID, nil, nil, nil)\n\n// Cancel all orders\nerr = client.Trade().CancelAllOrders(nil, \u0026symbol, nil, nil)\n\n// Get order details\norder, err := client.Trade().GetOrder(\"BTC-USDT\", \"123456789\")\n\n// Get open orders\nopenOrders, err := client.Trade().GetOpenOrders(nil, 100)\n\n// Get order history\nhistory, err := client.Trade().GetOrderHistory(\u0026symbol, 100, nil, nil)\n\n// Get user trades\ntrades, err := client.Trade().GetUserTrades(\u0026symbol, 100, nil, nil)\n```\n\n### Wallet Service - Wallet Management\n\n```go\n// Get deposit history\ndeposits, err := client.Wallet().GetDepositHistory(\"USDT\", nil, nil, nil, 100)\n\n// Get deposit address\naddress, err := client.Wallet().GetDepositAddress(\"USDT\", \"TRC20\")\n\n// Get withdrawal history\nwithdrawals, err := client.Wallet().GetWithdrawalHistory(\"USDT\", nil, nil, nil, 100)\n\n// Create withdrawal\nwithdrawal, err := client.Wallet().Withdraw(\"USDT\", \"TXxx...xxx\", 100.0, \"TRC20\", nil)\n\n// Get all coin info\ncoins, err := client.Wallet().GetAllCoinInfo()\n```\n\n### Coin-M Perpetual Futures\n\n```go\n// Get Coin-M market data\nticker, err := client.CoinM().Market().GetTicker(\"BTC-USD\")\n\n// Get Coin-M contracts\ncontracts, err := client.CoinM().Market().GetContracts()\n\n// Create Coin-M order\norder, err := client.CoinM().Trade().CreateOrder(map[string]interface{}{\n    \"symbol\":       \"BTC-USD\",\n    \"side\":         \"BUY\",\n    \"positionSide\": \"LONG\",\n    \"type\":         \"MARKET\",\n    \"quantity\":     100,\n})\n\n// Get Coin-M positions\npositions, err := client.CoinM().Trade().GetPositions(nil)\n\n// Get Coin-M balance\nbalance, err := client.CoinM().Trade().GetBalance()\n```\n\n### Sub-Account Management\n\n```go\n// Create sub-account\nresult, err := client.SubAccount().CreateSubAccount(\"sub_account_001\")\n\n// Get sub-account list\nsubAccounts, err := client.SubAccount().GetSubAccountList(nil, 1, 10)\n\n// Create API key for sub-account\napiKey, err := client.SubAccount().CreateSubAccountAPIKey(\n    \"sub_account_001\",\n    \"Trading Bot\",\n    map[string]bool{\"spot\": true, \"futures\": true},\n    nil, // IP whitelist (optional)\n)\n\n// Transfer assets to sub-account\ntransfer, err := client.SubAccount().SubAccountInternalTransfer(\n    \"USDT\",\n    \"SPOT\",\n    100.0,\n    \"FROM_MAIN_TO_SUB\",\n    nil,\n    \u0026subUID,\n    nil,\n)\n\n// Get sub-account assets\nassets, err := client.SubAccount().GetSubAccountAssets(\"12345678\")\n```\n\n### Copy Trading Operations\n\n```go\n// Get current track orders\norders, err := client.CopyTrading().GetCurrentTrackOrders(\"BTC-USDT\")\n\n// Close track order\nresult, err := client.CopyTrading().CloseTrackOrder(\"1252864099381234567\")\n\n// Set take profit and stop loss\nstopLoss := 48000.0\ntakeProfit := 52000.0\nerr = client.CopyTrading().SetTPSL(\"1252864099381234567\", \u0026stopLoss, \u0026takeProfit)\n\n// Get profit summary\nsummary, err := client.CopyTrading().GetProfitSummary()\n\n// Set commission rate\nerr = client.CopyTrading().SetCommission(5.0) // 5% commission\n```\n\n---\n\n## 🔧 Advanced Features\n\n### Commission Calculation\n\n```go\n// Calculate futures commission\ncommission := client.Trade().CalculateFuturesCommission(100.0, 10, nil)\nfmt.Printf(\"Commission: %.6f USDT\\n\", commission.Commission)\nfmt.Printf(\"Net Position Value: %.2f USDT\\n\", commission.NetPositionValue)\n\n// Quick commission amount\namount := client.Trade().GetCommissionAmount(100.0, 10)\nfmt.Printf(\"Commission Amount: %.6f USDT\\n\", amount)\n```\n\n### Batch Operations\n\n```go\n// Create multiple orders at once\norders := []map[string]interface{}{\n    {\n        \"symbol\":       \"BTC-USDT\",\n        \"side\":         \"BUY\",\n        \"type\":         \"LIMIT\",\n        \"positionSide\": \"LONG\",\n        \"price\":        50000.0,\n        \"quantity\":     0.001,\n    },\n    {\n        \"symbol\":       \"ETH-USDT\",\n        \"side\":         \"BUY\",\n        \"type\":         \"LIMIT\",\n        \"positionSide\": \"LONG\",\n        \"price\":        3000.0,\n        \"quantity\":     0.01,\n    },\n}\n\nresult, err := client.Trade().CreateBatchOrders(orders)\n\n// Cancel multiple orders\norderIDs := []string{\"123456789\", \"987654321\"}\nerr = client.Trade().CancelBatchOrders(\"BTC-USDT\", orderIDs, nil, nil, nil)\n```\n\n### Time-Based Queries\n\n```go\nimport \"time\"\n\n// Get trades from last 24 hours\nstartTime := time.Now().Add(-24 * time.Hour).UnixMilli()\nendTime := time.Now().UnixMilli()\n\ntrades, err := client.Trade().GetUserTrades(\n    \u0026symbol,\n    100,\n    \u0026startTime,\n    \u0026endTime,\n)\n\n// Get historical klines\nklines, err := client.Market().GetKlines(\n    \"BTC-USDT\",\n    \"1h\",\n    100,\n    \u0026startTime,\n    \u0026endTime,\n)\n```\n\n---\n\n## ⚙️ Configuration\n\n### Client Configuration Options\n\n```go\nclient := bingx.NewClient(\n    apiKey,\n    apiSecret,\n    // Set custom base URI (default: https://open-api.bingx.com)\n    bingx.WithBaseURI(\"https://open-api.bingx.com\"),\n    \n    // Set source key for tracking (optional)\n    bingx.WithSourceKey(\"my-trading-bot-v1\"),\n    \n    // Set signature encoding: \"base64\" or \"hex\" (default: base64)\n    bingx.WithSignatureEncoding(\"base64\"),\n)\n```\n\n### Environment Variables\n\n```bash\n# Recommended: Store credentials in environment variables\nexport BINGX_API_KEY=\"your_api_key_here\"\nexport BINGX_API_SECRET=\"your_api_secret_here\"\nexport BINGX_SOURCE_KEY=\"optional_source_key\"\n```\n\n```go\nimport \"os\"\n\nclient := bingx.NewClient(\n    os.Getenv(\"BINGX_API_KEY\"),\n    os.Getenv(\"BINGX_API_SECRET\"),\n    bingx.WithSourceKey(os.Getenv(\"BINGX_SOURCE_KEY\")),\n)\n```\n\n### Timeout Configuration\n\n```go\n// The HTTP client uses default timeouts:\n// - Connection timeout: 10 seconds\n// - Request timeout: 30 seconds\n\n// For custom timeout, modify the HTTP client in http/client.go\n```\n\n---\n\n## 📖 API Reference\n\n### Client Methods\n\n| Method                                            | Description                       | Returns                |\n|---------------------------------------------------|-----------------------------------|------------------------|\n| `NewClient(apiKey, apiSecret string, options...)` | Create new BingX client           | `*Client`              |\n| `client.Market()`                                 | Access market data service        | `*MarketService`       |\n| `client.Account()`                                | Access account management service | `*AccountService`      |\n| `client.Trade()`                                  | Access trading operations service | `*TradeService`        |\n| `client.Contract()`                               | Access contract service           | `*ContractService`     |\n| `client.ListenKey()`                              | Access WebSocket auth service     | `*ListenKeyService`    |\n| `client.Wallet()`                                 | Access wallet operations service  | `*WalletService`       |\n| `client.SpotAccount()`                            | Access spot account service       | `*SpotAccountService`  |\n| `client.SubAccount()`                             | Access sub-account service        | `*SubAccountService`   |\n| `client.CopyTrading()`                            | Access copy trading service       | `*CopyTradingService`  |\n| `client.CoinM()`                                  | Access Coin-M futures client      | `*CoinMClient`         |\n| `client.GetHTTPClient()`                          | Get underlying HTTP client        | `*http.BaseHTTPClient` |\n| `client.GetEndpoint()`                            | Get API endpoint URL              | `string`               |\n| `client.GetAPIKey()`                              | Get configured API key            | `string`               |\n\n### Service Overview\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eMarket Service Methods\u003c/b\u003e\u003c/summary\u003e\n\n- `GetFuturesSymbols()` - Get all futures trading symbols\n- `GetSpotSymbols()` - Get all spot trading symbols\n- `GetAllSymbols()` - Get both spot and futures symbols\n- `GetLatestPrice(symbol)` - Get latest price for a symbol\n- `GetSpotLatestPrice(symbol)` - Get latest spot price\n- `GetDepth(symbol, limit)` - Get order book depth\n- `GetSpotDepth(symbol, limit)` - Get spot order book\n- `GetKlines(symbol, interval, limit, startTime, endTime)` - Get candlestick data\n- `GetSpotKlines(...)` - Get spot candlestick data\n- `Get24hrTicker(symbol)` - Get 24hr ticker statistics\n- `GetSpot24hrTicker(symbol)` - Get spot 24hr ticker\n- `GetFundingRateHistory(symbol, limit)` - Get funding rate history\n- `GetMarkPrice(symbol)` - Get mark price\n- `GetPremiumIndexKlines(...)` - Get premium index klines\n- `GetAggregateTrades(...)` - Get aggregate trades\n- `GetRecentTrades(symbol, limit)` - Get recent trades\n- `GetServerTime()` - Get server time\n- `GetContinuousKlines(...)` - Get continuous contract klines\n- `GetIndexPriceKlines(...)` - Get index price klines\n- `GetTopLongShortRatio(...)` - Get long/short ratio\n- `GetHistoricalTopLongShortRatio(...)` - Get historical ratios\n- `GetBasis(...)` - Get basis data\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eAccount Service Methods\u003c/b\u003e\u003c/summary\u003e\n\n- `GetBalance()` - Get account balance\n- `GetPositions(symbol)` - Get positions\n- `GetAccountInfo()` - Get account information\n- `GetTradingFees(symbol)` - Get trading fees\n- `GetMarginMode(symbol)` - Get margin mode\n- `SetMarginMode(symbol, mode)` - Set margin mode\n- `GetLeverage(symbol, recvWindow)` - Get leverage\n- `SetLeverage(symbol, side, leverage, recvWindow)` - Set leverage\n- `GetPositionMargin(symbol)` - Get position margin\n- `SetPositionMargin(symbol, positionSide, amount, type)` - Set position margin\n- `GetBalanceHistory(coin, limit)` - Get balance history\n- `GetAccountPermissions()` - Get API permissions\n- `GetAPIKey()` - Get API key info\n- `GetUserCommissionRates(symbol)` - Get commission rates\n- `GetAPIRateLimits()` - Get rate limits\n- `GetDepositHistory(coin, limit)` - Get deposit history\n- `GetWithdrawHistory(coin, limit)` - Get withdrawal history\n- `GetAssetDetails(asset)` - Get asset details\n- `GetAllAssets()` - Get all assets\n- `GetFundingWallet(asset)` - Get funding wallet\n- `DustTransfer(assets)` - Convert dust to BNB\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTrade Service Methods\u003c/b\u003e\u003c/summary\u003e\n\n- `CreateOrder(params)` - Create new order\n- `ModifyOrder(...)` - Modify existing order\n- `CreateTestOrder(params)` - Create test order (no execution)\n- `CloseAllPositions(symbol, ...)` - Close all positions\n- `GetMarginType(symbol, ...)` - Get margin type\n- `ChangeMarginType(symbol, type, ...)` - Change margin type\n- `GetLeverage(symbol, ...)` - Get leverage\n- `SetLeverage(symbol, leverage, ...)` - Set leverage\n- `CreateBatchOrders(orders)` - Create multiple orders\n- `CancelOrder(symbol, orderID, ...)` - Cancel order\n- `CancelAllOrders(...)` - Cancel all orders\n- `CancelBatchOrders(...)` - Cancel multiple orders\n- `GetOrder(symbol, orderID)` - Get order details\n- `GetOpenOrders(symbol, limit)` - Get open orders\n- `GetOrderHistory(...)` - Get order history\n- `GetFilledOrders(...)` - Get filled orders\n- `GetUserTrades(...)` - Get user trades\n- `ChangeLeverage(symbol, side, leverage, ...)` - Change leverage\n- `CalculateFuturesCommission(margin, leverage, rate)` - Calculate commission\n- `GetCommissionAmount(margin, leverage)` - Get commission amount\n\n\u003c/details\u003e\n\n### Response Format\n\nAll API methods return `(map[string]interface{}, error)`:\n\n```go\nresponse, err := client.Market().GetLatestPrice(\"BTC-USDT\")\nif err != nil {\n    // Handle error\n}\n\n// Access response data\nif data, ok := response[\"data\"].(map[string]interface{}); ok {\n    price := data[\"price\"]\n    fmt.Printf(\"Price: %v\\n\", price)\n}\n```\n\n---\n\n## 🛡️ Error Handling\n\nThe SDK provides custom error types for different scenarios:\n\n```go\nimport \"github.com/tigusigalpa/bingx-go/errors\"\n\n// Handle errors\norder, err := client.Trade().CreateOrder(params)\nif err != nil {\n    switch e := err.(type) {\n    case *errors.AuthenticationException:\n        log.Printf(\"Authentication error: %v\", e)\n    case *errors.RateLimitException:\n        log.Printf(\"Rate limit exceeded: %v\", e)\n    case *errors.InsufficientBalanceException:\n        log.Printf(\"Insufficient balance: %v\", e)\n    case *errors.APIException:\n        log.Printf(\"API error [%s]: %v\", e.APICode, e)\n    default:\n        log.Printf(\"Error: %v\", err)\n    }\n    return\n}\n```\n\n### Error Types\n\n- `BingXException` - Base exception for all errors\n- `APIException` - API-level errors with error codes\n- `AuthenticationException` - Authentication failures\n- `RateLimitException` - Rate limit exceeded\n- `InsufficientBalanceException` - Insufficient balance errors\n\n---\n\n## � Best Practices\n\n### Security\n\n```go\n// ✅ DO: Use environment variables for credentials\napiKey := os.Getenv(\"BINGX_API_KEY\")\napiSecret := os.Getenv(\"BINGX_API_SECRET\")\n\n// ❌ DON'T: Hardcode credentials\napiKey := \"your_api_key_here\" // Never do this!\n\n// ✅ DO: Restrict API key permissions\n// Only enable permissions you need (read-only for monitoring, etc.)\n\n// ✅ DO: Use IP whitelist\n// Configure IP restrictions in BingX API settings\n```\n\n### Error Handling\n\n```go\n// ✅ DO: Always check errors\nresult, err := client.Trade().CreateOrder(params)\nif err != nil {\n    // Handle specific error types\n    switch e := err.(type) {\n    case *errors.RateLimitException:\n        // Implement exponential backoff\n        time.Sleep(time.Second * 5)\n    case *errors.InsufficientBalanceException:\n        // Log and alert\n        log.Error(\"Insufficient balance\")\n    default:\n        // Generic error handling\n        log.Error(err)\n    }\n    return\n}\n\n// ❌ DON'T: Ignore errors\nresult, _ := client.Trade().CreateOrder(params) // Bad practice\n```\n\n### Performance\n\n```go\n// ✅ DO: Reuse client instances\nvar globalClient *bingx.Client\n\nfunc init() {\n    globalClient = bingx.NewClient(apiKey, apiSecret)\n}\n\n// ❌ DON'T: Create new client for each request\nfunc makeRequest() {\n    client := bingx.NewClient(apiKey, apiSecret) // Wasteful\n    client.Market().GetLatestPrice(\"BTC-USDT\")\n}\n\n// ✅ DO: Use batch operations when possible\norders := []map[string]interface{}{...}\nclient.Trade().CreateBatchOrders(orders)\n\n// ❌ DON'T: Make individual requests in loops\nfor _, order := range orders {\n    client.Trade().CreateOrder(order) // Inefficient\n}\n```\n\n### Concurrency\n\n```go\n// ✅ DO: Client is thread-safe\nvar wg sync.WaitGroup\nfor _, symbol := range symbols {\n    wg.Add(1)\n    go func(s string) {\n        defer wg.Done()\n        price, _ := client.Market().GetLatestPrice(s)\n        // Process price\n    }(symbol)\n}\nwg.Wait()\n```\n\n---\n\n## 🧪 Testing\n\n### Unit Testing\n\n```go\npackage main\n\nimport (\n    \"testing\"\n    bingx \"github.com/tigusigalpa/bingx-go\"\n)\n\nfunc TestMarketData(t *testing.T) {\n    client := bingx.NewClient(\"\", \"\") // Empty credentials for public endpoints\n    \n    symbols, err := client.Market().GetFuturesSymbols()\n    if err != nil {\n        t.Fatalf(\"Failed to get symbols: %v\", err)\n    }\n    \n    if symbols == nil {\n        t.Error(\"Expected symbols, got nil\")\n    }\n}\n```\n\n### Integration Testing\n\n```go\nfunc TestOrderCreation(t *testing.T) {\n    if testing.Short() {\n        t.Skip(\"Skipping integration test\")\n    }\n    \n    client := bingx.NewClient(\n        os.Getenv(\"BINGX_API_KEY\"),\n        os.Getenv(\"BINGX_API_SECRET\"),\n    )\n    \n    // Test order creation\n    order, err := client.Trade().CreateTestOrder(params)\n    if err != nil {\n        t.Fatalf(\"Test order failed: %v\", err)\n    }\n}\n```\n\n### Running Tests\n\n```bash\n# Run all tests\ngo test ./...\n\n# Run with coverage\ngo test -cover ./...\n\n# Run specific test\ngo test -run TestMarketData\n\n# Skip integration tests\ngo test -short ./...\n```\n\n---\n\n## ⚡ Performance\n\n### Benchmarks\n\nThe SDK is optimized for high-performance trading applications:\n\n- **Request Latency**: \u003c 50ms (network dependent)\n- **Memory Usage**: ~2MB per client instance\n- **Concurrent Requests**: Supports 1000+ concurrent goroutines\n- **Signature Generation**: \u003c 1ms per request\n\n### Optimization Tips\n\n1. **Connection Pooling**: HTTP client reuses connections automatically\n2. **Batch Operations**: Use batch methods for multiple orders\n3. **Caching**: Cache market data locally when appropriate\n4. **Rate Limiting**: Implement client-side rate limiting to avoid API limits\n\n```go\n// Example: Rate-limited requests\nimport \"golang.org/x/time/rate\"\n\nlimiter := rate.NewLimiter(rate.Limit(10), 1) // 10 requests per second\n\nfunc makeRequest() {\n    limiter.Wait(context.Background())\n    client.Market().GetLatestPrice(\"BTC-USDT\")\n}\n```\n\n---\n\n## �️ Roadmap\n\n### Current Version (v1.0.0)\n\n- ✅ Complete API coverage\n- ✅ All service implementations\n- ✅ Error handling\n- ✅ Documentation\n\n### Planned Features (v1.1.0)\n\n- 🔄 WebSocket streaming implementation\n- 🔄 Order builder with fluent interface\n- 🔄 Rate limiter middleware\n- 🔄 Request/response logging\n- 🔄 Retry mechanism with exponential backoff\n\n### Future Enhancements (v2.0.0)\n\n- 📊 Built-in technical indicators\n- 🤖 Strategy backtesting framework\n- 📈 Portfolio management tools\n- 🔔 Event-driven architecture\n- 📱 Mobile-optimized examples\n\n---\n\n## 🔑 Creating API Keys\n\n### Step-by-Step Guide\n\n1. **Login** to your BingX account\n2. **Navigate** to [API Management](https://bingx.com/en-US/accounts/api)\n3. **Click** \"Create API\"\n4. **Configure** permissions:\n    - ✅ Enable \"Read\" for market data\n    - ✅ Enable \"Trade\" for order placement\n    - ✅ Enable \"Withdraw\" only if needed (not recommended)\n5. **Set IP Whitelist** (highly recommended)\n6. **Save** your API Key and Secret Key\n7. ⚠️ **Important**: Secret Key is shown only once - store it securely!\n\n### Security Recommendations\n\n- 🔒 Never share your API keys\n- 🔒 Use separate keys for different applications\n- 🔒 Enable IP whitelist restrictions\n- 🔒 Regularly rotate API keys\n- 🔒 Monitor API key usage in BingX dashboard\n- 🔒 Disable keys immediately if compromised\n\n---\n\n## 🤝 Contributing\n\nWe welcome contributions from the community! Here's how you can help:\n\n### Ways to Contribute\n\n- 🐛 **Report Bugs** - Open an issue with detailed reproduction steps\n- 💡 **Suggest Features** - Share your ideas for improvements\n- 📝 **Improve Documentation** - Fix typos, add examples, clarify concepts\n- 🔧 **Submit Code** - Fix bugs or implement new features\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/tigusigalpa/bingx-go.git\ncd bingx-go\n\n# Install dependencies\ngo mod download\n\n# Run tests\ngo test ./...\n\n# Run linter\ngolangci-lint run\n```\n\n### Pull Request Process\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes\n4. Add tests for new functionality\n5. Ensure all tests pass\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to the branch (`git push origin feature/amazing-feature`)\n8. Open a Pull Request\n\n### Code Style\n\n- Follow [Effective Go](https://golang.org/doc/effective_go) guidelines\n- Use `gofmt` for formatting\n- Add comments for exported functions\n- Keep functions focused and small\n- Write descriptive commit messages\n\n---\n\n## 📝 License\n\nThis project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.\n\n### MIT License Summary\n\n✅ Commercial use  \n✅ Modification  \n✅ Distribution  \n✅ Private use\n\n⚠️ Liability and warranty limitations apply\n\n---\n\n## ⚠️ Disclaimer\n\n**Important Notice:**\n\n- This SDK is provided \"as-is\" without any warranties\n- Cryptocurrency trading carries significant financial risk\n- Past performance does not guarantee future results\n- Always test thoroughly in a sandbox environment before production use\n- The authors are not responsible for any financial losses\n- Use at your own risk\n\n**Recommendations:**\n\n- Start with small amounts\n- Implement proper risk management\n- Monitor your trading bots continuously\n- Keep your API keys secure\n- Stay informed about market conditions\n\n---\n\n## 📧 Support\n\n### Get Help\n\n- 📖 **Documentation**: Read this README and inline code documentation\n- 💬 **GitHub Issues**: [Report bugs or request features](https://github.com/tigusigalpa/bingx-go/issues)\n- 📚 **BingX API Docs**: [Official API Documentation](https://bingx-api.github.io/docs/)\n- 💡 **Examples**: Check the `examples/` directory for code samples\n\n### Community\n\n- ⭐ **Star this repo** if you find it useful\n- 🐦 **Share** with other Go developers\n- 🔔 **Watch** for updates and new releases\n\n### Commercial Support\n\nFor enterprise support, custom development, or consulting services, please contact the maintainers.\n\n---\n\n## 🙏 Acknowledgments\n\n- **BingX Team** - For providing comprehensive API documentation\n- **Go Community** - For excellent tools and libraries\n- **Contributors** - Thank you to everyone who has contributed to this project\n\n---\n\n## 📊 Project Stats\n\n![GitHub stars](https://img.shields.io/github/stars/tigusigalpa/bingx-go?style=social)\n![GitHub forks](https://img.shields.io/github/forks/tigusigalpa/bingx-go?style=social)\n![GitHub watchers](https://img.shields.io/github/watchers/tigusigalpa/bingx-go?style=social)\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**Made with ❤️ by the Go Community**\n\n[⬆ Back to Top](#bingx-go-sdk)\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftigusigalpa%2Fbingx-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftigusigalpa%2Fbingx-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftigusigalpa%2Fbingx-go/lists"}