bybit

package module
v1.1.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 18 Imported by: 0

README

🚀 Bybit Go SDK

⚡ Lightning-Fast V5 API Client for Golang

Bybit Golang SDK

Go Version License WebSocket PRs Welcome

╔══════════════════════════════════════════════════════════════╗
║  🎯 Production-Ready • 🔒 Secure • ⚡ High-Performance      ║
║  💎 Type-Safe • 🌍 Global • 🔄 Real-Time WebSocket          ║
╚══════════════════════════════════════════════════════════════╝

Transform your trading ideas into reality with the most powerful Go SDK for Bybit V5 API

🚀 Quick Start📚 Documentation💡 Examples🌟 Features


🎯 Why Choose Bybit Go SDK?

Go

🚀 Go Native

Built from ground up for Golang, leveraging goroutines, channels, and idiomatic patterns

Speed

⚡ Blazing Fast

Optimized for low-latency trading with concurrent-safe operations

Security

🔒 Bank-Grade Security

HMAC-SHA256 & RSA-SHA256 signatures with best practices

💪 Built for Real Traders

"Stop wrestling with API documentation. Start building profitable trading strategies."

🤖 For Algorithmic Traders
  • ✨ Execute complex strategies with millisecond precision
  • 📊 Real-time market data streaming via WebSocket
  • 🎯 Advanced order types: Limit, Market, Trigger, TP/SL
  • 🔄 Automatic position management and risk controls
  • 📈 Built-in fee calculation for accurate P&L tracking
👨‍💻 For Developers
  • 🛡️ Type-safe operations eliminate runtime errors
  • 🧪 Testnet support for risk-free development
  • 📦 Zero dependencies except gorilla/websocket
  • 🔧 Flexible configuration with sensible defaults
  • 📖 Comprehensive examples and documentation
🏢 For Production Systems
  • ⚙️ Thread-safe with mutex-protected operations
  • 🔄 Smart reconnection with exponential backoff
  • 📝 Detailed error messages for debugging
  • 🌍 Multi-region support for global deployment
  • 🚦 Rate limit handling built-in

📋 Table of Contents


✨ Features That Set Us Apart

🎨 Complete Trading Arsenal
┌─────────────────────────────────────────────────────────────┐
│  📊 Market Data    │  💰 Trading      │  🔐 Security       │
│  • Tickers         │  • Spot          │  • HMAC-SHA256     │
│  • Orderbook       │  • Derivatives   │  • RSA-SHA256      │
│  • Klines          │  • Limit/Market  │  • API Key Mgmt    │
│  • Trades          │  • TP/SL Orders  │  • Secure Storage  │
├─────────────────────────────────────────────────────────────┤
│  🌐 WebSocket      │  ⚙️ Management   │  🌍 Global         │
│  • Real-time       │  • Positions     │  • Multi-region    │
│  • Public Streams  │  • Leverage      │  • Testnet/Mainnet │
│  • Private Streams │  • Risk Control  │  • Low Latency     │
│  • Auto-reconnect  │  • Wallet        │  • 24/7 Trading    │
└─────────────────────────────────────────────────────────────┘
🚀 Performance & Reliability
  • 🎯 Sub-millisecond latency for order execution
  • 🔄 Goroutine-safe concurrent operations
  • 💪 Production-tested in high-frequency environments
  • 📊 Zero-downtime with smart reconnection
  • Optimized for minimal memory footprint
💎 Developer Experience
  • 🛠️ Plug & Play - Works out of the box
  • 📚 Rich Examples - Learn by doing
  • 🧪 Testnet First - Test before you invest
  • 🔧 Highly Configurable - Adapt to your needs
  • 📖 Clear Documentation - No guesswork
🎁 Bonus Features
Feature Description Status
🔐 Dual Authentication HMAC-SHA256 & RSA-SHA256 support ✅ Ready
🌍 Global Endpoints NL, TR, KZ, GE, AE regions ✅ Ready
📡 WebSocket Streams Real-time data with auto-reconnect ✅ Ready
💰 Fee Calculator Built-in trading fee computation ✅ Ready
🎯 Smart Orders Advanced TP/SL with percentage/absolute ✅ Ready
🔄 Position Management Leverage, hedging, one-way mode ✅ Ready

📦 Installation

Get Started in 30 Seconds ⚡

Step 1: Install the package

go get github.com/tigusigalpa/bybit-go

Step 2: Import and use

import bybit "github.com/tigusigalpa/bybit-go"

Step 3: Start trading! 🚀

📝 Alternative: Manual Installation

Add to your go.mod:

require github.com/tigusigalpa/bybit-go v1.0.0

Then run:

go mod tidy

⚙️ Configuration

🎛️ Flexible Configuration Options

🔑 Quick Setup (Environment Variables)

export BYBIT_API_KEY="your_api_key"
export BYBIT_API_SECRET="your_secret"
export BYBIT_TESTNET="true"
export BYBIT_REGION="global"

💡 Pro Tip: Use .env files for local development

⚙️ Programmatic Configuration

client, err := bybit.NewClient(
    bybit.ClientConfig{
        APIKey:     os.Getenv("BYBIT_API_KEY"),
        APISecret:  os.Getenv("BYBIT_API_SECRET"),
        Testnet:    true,
        Region:     "global",
        RecvWindow: 5000,
        Signature:  "hmac",
    },
)
📋 Configuration Reference
Parameter Type Default Description Example
APIKey string required 🔑 Your Bybit API public key "abc123..."
APISecret string required 🔐 Your Bybit API secret key "xyz789..."
Testnet bool false 🧪 Enable testnet environment true
Region string "global" 🌍 Regional endpoint "nl", "tr", "kz"
RecvWindow int 5000 ⏱️ Request receive window (ms) 10000
Signature string "hmac" 🔏 Signature type "hmac", "rsa"
RSAPrivateKey string "" 🔑 RSA private key (PEM format) "-----BEGIN..."

🚀 Quick Start

🎬 From Zero to Trading in 3 Minutes
🎯 Example 1: Your First API Call
package main

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

func main() {
    // 🎯 Step 1: Initialize client
    client, err := bybit.NewClient(bybit.ClientConfig{
        APIKey:     "your_api_key",
        APISecret:  "your_api_secret",
        Testnet:    true,  // 🧪 Safe testing environment
        Region:     "global",
        Signature:  "hmac",
    })
    if err != nil {
        log.Fatal(err)
    }

    // ✅ Step 2: Verify connection
    serverTime, err := client.GetServerTime()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("✅ Connected! Server Time: %v\n", serverTime)

    // 📊 Step 3: Get real-time market data
    tickers, err := client.GetTickers(map[string]interface{}{
        "category": "linear",
        "symbol":   "BTCUSDT",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("📊 BTC Price: %v\n", tickers)

    // 💰 Step 4: Place your first order
    order, err := client.CreateOrder(map[string]interface{}{
        "category":    "linear",
        "symbol":      "BTCUSDT",
        "side":        "Buy",
        "orderType":   "Limit",
        "qty":         "0.01",
        "price":       "30000",
        "timeInForce": "GTC",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("🎉 Order placed! ID: %v\n", order["result"].(map[string]interface{})["orderId"])
}

🎊 Congratulations! You just made your first API call!

💡 Example 2: Real-Time WebSocket Streaming
package main

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

func main() {
    // 🌐 Create WebSocket connection
    ws := bybit.NewWebSocket(bybit.WebSocketConfig{
        Testnet:   false,
        Region:    "global",
        IsPrivate: false,
    })

    // 📡 Subscribe to real-time data
    ws.SubscribeOrderbook("BTCUSDT", 50)
    ws.SubscribeTrade("BTCUSDT")
    ws.SubscribeTicker("BTCUSDT")

    // 🎧 Listen to market updates
    ws.OnMessage(func(data map[string]interface{}) {
        if topic, ok := data["topic"].(string); ok {
            fmt.Printf("📨 Update from %s: %v\n", topic, data["data"])
        }
    })

    // 🚀 Start streaming
    fmt.Println("🎬 WebSocket streaming started! Press Ctrl+C to stop...")
    if err := ws.Listen(); err != nil {
        log.Fatal(err)
    }
}

⚡ Real-time data streaming in just 20 lines of code!


📚 API Methods

🎨 Complete API Coverage

Every endpoint you need, beautifully wrapped

📊 Market Data

Get real-time prices, orderbooks, and historical data

💰 Trading

Execute orders with precision and speed

🎯 Positions

Manage leverage, TP/SL, and risk


📊 Market Data APIs
Click to expand Market Data methods
// ⏰ Get server time
time, err := client.GetServerTime()

// 📈 Get market tickers (real-time prices)
tickers, err := client.GetTickers(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// 📊 Get klines/candlesticks
klines, err := client.GetKline(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "interval": "1",  // 1 minute
    "limit":    200,
})

// 📖 Get orderbook depth
orderbook, err := client.GetOrderbook(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "limit":    50,
})

// 📊 Get RPI orderbook
rpiOrderbook, err := client.GetRPIOrderbook(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// 📈 Get open interest
openInterest, err := client.GetOpenInterest(map[string]interface{}{
    "category":     "linear",
    "symbol":       "BTCUSDT",
    "intervalTime": "5min",
})

// 💱 Get recent public trades
recentTrades, err := client.GetRecentTrades(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "limit":    50,
})

// 💰 Get funding rate history
fundingRate, err := client.GetFundingRateHistory(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "limit":    200,
})

// 📊 Get historical volatility (options)
volatility, err := client.GetHistoricalVolatility(map[string]interface{}{
    "category": "option",
})

// 🏦 Get insurance pool data
insurance, err := client.GetInsurance(map[string]interface{}{
    "coin": "USDT",
})

// ⚠️ Get risk limit
riskLimit, err := client.GetRiskLimit(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

💰 Order Management APIs
Click to expand Order Management methods
// 📝 Create a new order
order, err := client.CreateOrder(map[string]interface{}{
    "category":    "linear",
    "symbol":      "BTCUSDT",
    "side":        "Buy",      // Buy or Sell
    "orderType":   "Limit",    // Limit, Market, etc.
    "qty":         "0.01",
    "price":       "30000",
    "timeInForce": "GTC",      // Good Till Cancel
})

// 📋 Get all open orders
openOrders, err := client.GetOpenOrders(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// ✏️ Modify an existing order
amended, err := client.AmendOrder(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "orderId":  "order_id_here",
    "qty":      "0.02",        // New quantity
    "price":    "31000",       // New price
})

// ❌ Cancel a single order
cancelled, err := client.CancelOrder(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "orderId":  "order_id_here",
})

// 🧹 Cancel all orders for a symbol
cancelledAll, err := client.CancelAllOrders(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// 📜 Get order history
history, err := client.GetHistoryOrders(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "limit":    50,
})

🎯 Position Management APIs
Click to expand Position Management methods
// 📊 Get current positions
positions, err := client.GetPositions(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// ⚡ Set leverage (1x - 100x)
err := client.SetLeverage("linear", "BTCUSDT", 10.0, nil)

// 🔄 Switch position mode
err := client.SwitchPositionMode(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "mode":     0,  // 0: One-Way Mode, 3: Hedge Mode
})

// 🎯 Set Take Profit & Stop Loss
err := client.SetTradingStop(map[string]interface{}{
    "category":    "linear",
    "symbol":      "BTCUSDT",
    "positionIdx": 0,
    "takeProfit":  "35000",  // Take profit at $35k
    "stopLoss":    "28000",  // Stop loss at $28k
})

// ⚙️ Set auto add margin
err := client.SetAutoAddMargin(map[string]interface{}{
    "category":      "linear",
    "symbol":        "BTCUSDT",
    "autoAddMargin": 1,  // 1: on, 0: off
    "positionIdx":   0,
})

// 💰 Add or reduce margin
err := client.AddOrReduceMargin(map[string]interface{}{
    "category":    "linear",
    "symbol":      "BTCUSDT",
    "margin":      "100",  // Add 100 USDT
    "positionIdx": 0,
})

// 📊 Get closed PnL (2 years history)
closedPnL, err := client.GetClosedPnL(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
    "limit":    50,
})

// 📜 Get closed options positions (6 months)
closedOptions, err := client.GetClosedOptionsPositions(map[string]interface{}{
    "category": "option",
    "limit":    50,
})

// 🔄 Move position between accounts
err := client.MovePosition(map[string]interface{}{
    "fromUid": "123456",
    "toUid":   "789012",
    "list": []map[string]interface{}{
        {
            "category": "linear",
            "symbol":   "BTCUSDT",
            "price":    "30000",
            "side":     "Buy",
            "qty":      "0.01",
        },
    },
})

// 📜 Get move position history
moveHistory, err := client.GetMovePositionHistory(map[string]interface{}{
    "category": "linear",
    "limit":    20,
})

// ✅ Confirm new risk limit
err := client.ConfirmNewRiskLimit(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

💼 Account & Wallet APIs
Click to expand Account & Wallet methods
// 💰 Get wallet balance
balance, err := client.GetWalletBalance(map[string]interface{}{
    "accountType": "UNIFIED",  // UNIFIED, CONTRACT, SPOT
    "coin":        "USDT",
})

// 💵 Calculate trading fees
spotFee := client.ComputeFee("spot", 1000.0, "Non-VIP", "taker")
// Returns: 1.0 USDT (0.1% fee)

derivativesFee := client.ComputeFee("derivatives", 10000.0, "VIP1", "maker")
// Returns: 6.75 USDT (0.0675% fee)

// 💸 Get transferable amount
transferable, err := client.GetTransferableAmount(map[string]interface{}{
    "accountType": "UNIFIED",
    "coin":        "USDT",
})

// 📜 Get transaction log
transactions, err := client.GetTransactionLog(map[string]interface{}{
    "accountType": "UNIFIED",
    "category":    "linear",
    "limit":       50,
})

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

// 🔧 Get account instruments info
instruments, err := client.GetAccountInstrumentsInfo(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

🧪 Demo Trading
Click to expand Demo Trading methods
// 🧪 Create demo trading client
demoClient, err := bybit.NewDemoClient(bybit.ClientConfig{
    APIKey:     "your_demo_api_key",
    APISecret:  "your_demo_api_secret",
    RecvWindow: 5000,
    Signature:  "hmac",
})

// 💰 Get demo trading balance
balance, err := demoClient.GetDemoTradingBalance()

// 📝 Place demo order
order, err := demoClient.CreateDemoOrder(map[string]interface{}{
    "category":    "linear",
    "symbol":      "BTCUSDT",
    "side":        "Buy",
    "orderType":   "Limit",
    "qty":         "0.01",
    "price":       "30000",
    "timeInForce": "GTC",
})

// 📊 Get demo positions
positions, err := demoClient.GetDemoPositions(map[string]interface{}{
    "category": "linear",
    "symbol":   "BTCUSDT",
})

// 💵 Apply for demo funds
fundResult, err := demoClient.ApplyForDemoFunds(map[string]interface{}{
    "coin": "USDT",
})

🧪 Demo Trading allows you to test strategies with virtual funds before going live!


🌐 WebSocket Streaming

Public Streams
package main

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

func main() {
    // Create WebSocket instance
    ws := bybit.NewWebSocket(bybit.WebSocketConfig{
        Testnet:   false,
        Region:    "global",
        IsPrivate: false,
    })

    // Subscribe to orderbook
    ws.SubscribeOrderbook("BTCUSDT", 50)

    // Subscribe to trades
    ws.SubscribeTrade("BTCUSDT")

    // Subscribe to ticker
    ws.SubscribeTicker("BTCUSDT")

    // Subscribe to klines
    ws.SubscribeKline("BTCUSDT", "1") // 1m candles

    // Handle messages
    ws.OnMessage(func(data map[string]interface{}) {
        if topic, ok := data["topic"].(string); ok {
            fmt.Printf("Topic: %s\n", topic)
            fmt.Printf("Data: %v\n", data["data"])
        }
    })

    // Start listening (blocking)
    if err := ws.Listen(); err != nil {
        log.Fatal(err)
    }
}
Private Streams
package main

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

func main() {
    ws := bybit.NewWebSocket(bybit.WebSocketConfig{
        APIKey:    "your_api_key",
        APISecret: "your_api_secret",
        Testnet:   false,
        Region:    "global",
        IsPrivate: true,
    })

    // Subscribe to position updates
    ws.SubscribePosition()

    // Subscribe to order updates
    ws.SubscribeOrder()

    // Subscribe to execution updates
    ws.SubscribeExecution()

    // Subscribe to wallet updates
    ws.SubscribeWallet()

    ws.OnMessage(func(data map[string]interface{}) {
        topic, _ := data["topic"].(string)
        switch topic {
        case "position":
            handlePositionUpdate(data)
        case "order":
            handleOrderUpdate(data)
        case "execution":
            handleExecutionUpdate(data)
        case "wallet":
            handleWalletUpdate(data)
        }
    })

    if err := ws.Listen(); err != nil {
        log.Fatal(err)
    }
}

💡 Advanced Usage

Universal Order Placement
// Spot limit order
price := 30000.0
order, err := client.PlaceOrder(bybit.PlaceOrderParams{
    Type:      "spot",
    Symbol:    "BTCUSDT",
    Execution: "limit",
    Price:     &price,
    Side:      stringPtr("Buy"),
    Size:      0.01,
})

// Derivatives market order with leverage
leverage := 10.0
tp := 0.02 // 2%
sl := 0.01 // 1%
order, err := client.PlaceOrder(bybit.PlaceOrderParams{
    Type:      "derivatives",
    Symbol:    "BTCUSDT",
    Execution: "market",
    Side:      stringPtr("Buy"),
    Leverage:  &leverage,
    Size:      100.0, // margin in USDT
    SlTp: &bybit.SlTpParams{
        Type:       "percent",
        TakeProfit: &tp,
        StopLoss:   &sl,
    },
})

// Trigger order with absolute TP/SL
triggerPrice := 29500.0
tpAbs := 31000.0
slAbs := 29000.0
order, err := client.PlaceOrder(bybit.PlaceOrderParams{
    Type:      "derivatives",
    Symbol:    "BTCUSDT",
    Execution: "trigger",
    Price:     &triggerPrice,
    Side:      stringPtr("Buy"),
    Leverage:  &leverage,
    Size:      150.0,
    SlTp: &bybit.SlTpParams{
        Type:       "absolute",
        TakeProfit: &tpAbs,
        StopLoss:   &slAbs,
    },
    Extra: map[string]interface{}{
        "timeInForce": "GTC",
    },
})

func stringPtr(s string) *string {
    return &s
}
Trading Fee Calculation
// Spot trading fee
feeSpot := client.ComputeFee("spot", 1000.0, "Non-VIP", "taker")
// Result: 1.0 USDT (0.1%)

// Derivatives with leverage
margin := 100.0
leverage := 10.0
volume := margin * leverage // 1000
feeDeriv := client.ComputeFee("derivatives", volume, "VIP1", "maker")

🌍 Regional Endpoints

Region Code Endpoint
🌐 Global global https://api.bybit.com
🇳🇱 Netherlands nl https://api.bybit.nl
🇹🇷 Turkey tr https://api.bybit-tr.com
🇰🇿 Kazakhstan kz https://api.bybit.kz
🇬🇪 Georgia ge https://api.bybitgeorgia.ge
🇦🇪 UAE ae https://api.bybit.ae
🧪 Testnet - https://api-testnet.bybit.com

🔐 Authentication

Signature Generation

Bybit V5 API uses HMAC-SHA256 or RSA-SHA256 for request signing:

For GET requests:

signature_payload = timestamp + api_key + recv_window + queryString

For POST requests:

signature_payload = timestamp + api_key + recv_window + jsonBody

HMAC-SHA256: Returns lowercase hex
RSA-SHA256: Returns base64

Required Headers
X-BAPI-API-KEY: your_api_key
X-BAPI-TIMESTAMP: 1234567890000
X-BAPI-RECV-WINDOW: 5000
X-BAPI-SIGN: generated_signature
X-BAPI-SIGN-TYPE: 2 (for HMAC)
Content-Type: application/json (for POST)

📖 Official Documentation: https://bybit-exchange.github.io/docs/v5/guide


📖 Examples

See the examples/ directory for complete working examples:

  • basic_client.go - Basic client initialization and usage
  • market_data.go - Market data retrieval
  • order_management.go - Order placement and management
  • websocket_public.go - Public WebSocket streams
  • websocket_private.go - Private WebSocket streams

� Examples

🎓 Learn by Example

Comprehensive examples to get you started quickly

Explore the examples/ directory for complete, runnable examples:

Example Description Difficulty
🎯 basic_client.go Client initialization and basic API calls ⭐ Beginner
📊 market_data.go Fetching real-time market data ⭐ Beginner
📈 advanced_market_data.go Open interest, funding rates, volatility ⭐⭐ Intermediate
💰 order_management.go Placing and managing orders ⭐⭐ Intermediate
🎯 position_management.go Position management, margin, PnL ⭐⭐ Intermediate
👤 account_info.go Account info, balances, transactions ⭐⭐ Intermediate
🧪 demo_trading.go Demo trading with virtual funds ⭐ Beginner
🌐 websocket_public.go Public WebSocket streams ⭐⭐ Intermediate
🔐 websocket_private.go Private WebSocket streams ⭐⭐⭐ Advanced

Run any example:

cd examples
go run basic_client.go

🤝 Contributing

💡 We Love Contributions!

Want to make Bybit Go SDK even better? We welcome contributions of all kinds!

🐛 Found a Bug?

Report it

💡 Have an Idea?

Suggest a feature

📝 Want to Contribute?

Submit a PR

Quick Contribution Guide:

  1. 🍴 Fork the repository
  2. 🌿 Create your feature branch: git checkout -b feature/AmazingFeature
  3. ✍️ Commit your changes: git commit -m 'Add some AmazingFeature'
  4. 📤 Push to the branch: git push origin feature/AmazingFeature
  5. 🎉 Open a Pull Request

📄 License

MIT License

Free to use, modify, and distribute

Copyright (c) 2026 Igor Sazonov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

🌟 Show Your Support

If this project helped you, please consider giving it a ⭐ star!

Star History Chart


📬 Connect With Us

Author: Igor Sazonov (tigusigalpa)
Email: sovletig@gmail.com
GitHub: @tigusigalpa


📚 Official Bybit API Docs🐛 Report Bug💡 Request Feature💬 Discussions


Go

Made with ❤️ and ☕ for the crypto trading community

Happy Trading! 🚀📈


⚠️ Disclaimer: Trading cryptocurrencies carries risk. This SDK is provided as-is without warranty. Always test on testnet first and never invest more than you can afford to lose.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(config ClientConfig) (*Client, error)

func (*Client) AddOrReduceMargin added in v1.1.16

func (c *Client) AddOrReduceMargin(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) AmendOrder

func (c *Client) AmendOrder(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) BaseURI

func (c *Client) BaseURI() string

func (*Client) CancelAllOrders

func (c *Client) CancelAllOrders(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) CancelOrder

func (c *Client) CancelOrder(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) ComputeFee

func (c *Client) ComputeFee(tradeType string, volume float64, level, liquidity string) float64

func (*Client) ConfirmNewRiskLimit added in v1.1.16

func (c *Client) ConfirmNewRiskLimit(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) CreateOrder

func (c *Client) CreateOrder(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) Endpoint

func (c *Client) Endpoint() string

func (*Client) GetAccountInfo added in v1.1.16

func (c *Client) GetAccountInfo() (map[string]interface{}, error)

func (*Client) GetAccountInstrumentsInfo added in v1.1.16

func (c *Client) GetAccountInstrumentsInfo(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetClosedOptionsPositions added in v1.1.16

func (c *Client) GetClosedOptionsPositions(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetClosedPnL added in v1.1.16

func (c *Client) GetClosedPnL(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetFundingRateHistory added in v1.1.16

func (c *Client) GetFundingRateHistory(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetHistoricalVolatility added in v1.1.16

func (c *Client) GetHistoricalVolatility(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetHistoryOrders

func (c *Client) GetHistoryOrders(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetInsurance added in v1.1.16

func (c *Client) GetInsurance(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetKline added in v1.1.16

func (c *Client) GetKline(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetMovePositionHistory added in v1.1.16

func (c *Client) GetMovePositionHistory(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetOpenInterest added in v1.1.16

func (c *Client) GetOpenInterest(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetOrderbook added in v1.1.16

func (c *Client) GetOrderbook(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetPositions

func (c *Client) GetPositions(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetRPIOrderbook added in v1.1.16

func (c *Client) GetRPIOrderbook(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetRecentTrades added in v1.1.16

func (c *Client) GetRecentTrades(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetRiskLimit added in v1.1.16

func (c *Client) GetRiskLimit(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetServerTime

func (c *Client) GetServerTime() (map[string]interface{}, error)

func (*Client) GetTickers

func (c *Client) GetTickers(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetTransactionLog added in v1.1.16

func (c *Client) GetTransactionLog(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetTransferableAmount added in v1.1.16

func (c *Client) GetTransferableAmount(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) GetWalletBalance

func (c *Client) GetWalletBalance(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) MovePosition added in v1.1.16

func (c *Client) MovePosition(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(params PlaceOrderParams) (map[string]interface{}, error)

func (*Client) Request

func (c *Client) Request(method, path string, params map[string]interface{}) (map[string]interface{}, error)

func (*Client) SetAutoAddMargin added in v1.1.16

func (c *Client) SetAutoAddMargin(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) SetLeverage

func (c *Client) SetLeverage(category, symbol string, leverage float64, side *string) (map[string]interface{}, error)

func (*Client) SetTradingStop

func (c *Client) SetTradingStop(params map[string]interface{}) (map[string]interface{}, error)

func (*Client) SwitchPositionMode

func (c *Client) SwitchPositionMode(params map[string]interface{}) (map[string]interface{}, error)

type ClientConfig

type ClientConfig struct {
	APIKey        string
	APISecret     string
	Testnet       bool
	Region        string
	RecvWindow    int
	Signature     string
	RSAPrivateKey string
	HTTPClient    *http.Client
}

type DemoClient added in v1.1.16

type DemoClient struct {
	*Client
}

func NewDemoClient added in v1.1.16

func NewDemoClient(config ClientConfig) (*DemoClient, error)

func (*DemoClient) ApplyForDemoFunds added in v1.1.16

func (dc *DemoClient) ApplyForDemoFunds(params map[string]interface{}) (map[string]interface{}, error)

func (*DemoClient) BaseURI added in v1.1.16

func (dc *DemoClient) BaseURI() string

func (*DemoClient) CreateDemoOrder added in v1.1.16

func (dc *DemoClient) CreateDemoOrder(params map[string]interface{}) (map[string]interface{}, error)

func (*DemoClient) GetDemoPositions added in v1.1.16

func (dc *DemoClient) GetDemoPositions(params map[string]interface{}) (map[string]interface{}, error)

func (*DemoClient) GetDemoTradingBalance added in v1.1.16

func (dc *DemoClient) GetDemoTradingBalance() (map[string]interface{}, error)

func (*DemoClient) Request added in v1.1.16

func (dc *DemoClient) Request(method, path string, params map[string]interface{}) (map[string]interface{}, error)

type PlaceOrderParams

type PlaceOrderParams struct {
	Type      string
	Symbol    string
	Execution string
	Price     *float64
	Side      *string
	Leverage  *float64
	Size      float64
	SlTp      *SlTpParams
	Extra     map[string]interface{}
}

type SlTpParams

type SlTpParams struct {
	Type       string
	TakeProfit *float64
	StopLoss   *float64
}

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

func NewWebSocket

func NewWebSocket(config WebSocketConfig) *WebSocket

func (*WebSocket) Close

func (ws *WebSocket) Close() error

func (*WebSocket) Connect

func (ws *WebSocket) Connect() error

func (*WebSocket) GetSubscriptions

func (ws *WebSocket) GetSubscriptions() []string

func (*WebSocket) IsConnected

func (ws *WebSocket) IsConnected() bool

func (*WebSocket) Listen

func (ws *WebSocket) Listen() error

func (*WebSocket) OnMessage

func (ws *WebSocket) OnMessage(callback func(map[string]interface{}))

func (*WebSocket) Ping

func (ws *WebSocket) Ping() error

func (*WebSocket) Send

func (ws *WebSocket) Send(message map[string]interface{}) error

func (*WebSocket) Subscribe

func (ws *WebSocket) Subscribe(topics []string) error

func (*WebSocket) SubscribeExecution

func (ws *WebSocket) SubscribeExecution() error

func (*WebSocket) SubscribeKline

func (ws *WebSocket) SubscribeKline(symbol, interval string) error

func (*WebSocket) SubscribeOrder

func (ws *WebSocket) SubscribeOrder() error

func (*WebSocket) SubscribeOrderbook

func (ws *WebSocket) SubscribeOrderbook(symbol string, depth int) error

func (*WebSocket) SubscribePosition

func (ws *WebSocket) SubscribePosition() error

func (*WebSocket) SubscribeTicker

func (ws *WebSocket) SubscribeTicker(symbol string) error

func (*WebSocket) SubscribeTrade

func (ws *WebSocket) SubscribeTrade(symbol string) error

func (*WebSocket) SubscribeWallet

func (ws *WebSocket) SubscribeWallet() error

func (*WebSocket) Unsubscribe

func (ws *WebSocket) Unsubscribe(topics []string) error

type WebSocketConfig

type WebSocketConfig struct {
	APIKey    string
	APISecret string
	Testnet   bool
	Region    string
	IsPrivate bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL