### Install Go Dependencies Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Ensure you have Go 1.21.0 or higher. Use these dependencies in your go.mod file. ```go require ( github.com/google/uuid v1.4.0 github.com/gorilla/websocket v1.5.1 github.com/stretchr/testify v1.8.4 ) ``` -------------------------------- ### Get Instrument Info Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Get trading rules, tick size, and lot size for instruments. This endpoint requires specifying the category and symbol. ```go params := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", } result, err := client.NewUtaBybitServiceWithParams(params).GetInstrumentInfo(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Borrowable Coins (Public) Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves a list of coins that can be borrowed for flexible loans. This is a public endpoint. ```go // Get borrowable coins (public) borrowCoins, _ := client.NewUtaBybitServiceNoParams().GetBorrowableCoins(context.Background()) fmt.Println(bybit.PrettyPrint(borrowCoins)) ``` -------------------------------- ### Utility Functions for Timestamps and Formatting Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Utilize package-level helper functions for pretty-printing response structs as indented JSON, getting the current Unix timestamp in milliseconds, and formatting a time.Time value to Unix milliseconds. ```go // Pretty-print any response struct as indented JSON fmt.Println(bybit.PrettyPrint(result)) ``` ```go // Get current Unix timestamp in milliseconds (used for signing) ts := bybit.GetCurrentTime() fmt.Println("Current time ms:", ts) ``` ```go // Format a time.Time value to Unix milliseconds import "time" ts2 := bybit.FormatTimestamp(time.Now()) fmt.Println("Formatted ts:", ts2) ``` -------------------------------- ### Get API Key Info - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Queries information about the current API key being used. No parameters are required. ```go // Query current API key info apiKeyInfo, _ := client.NewUtaBybitServiceNoParams().GetAPIKeyInfo(context.Background()) fmt.Println(bybit.PrettyPrint(apiKeyInfo)) ``` -------------------------------- ### GetInstrumentInfo Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Get trading rules, tick size, and lot size for instruments. ```APIDOC ## Market Data — Instrument Info Get trading rules, tick size, and lot size for instruments. ```go params := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", } result, err := client.NewUtaBybitServiceWithParams(params).GetInstrumentInfo(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` ``` -------------------------------- ### Get Market Tickers Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Get the latest ticker price and 24-hour statistics for one or all symbols. Specify the category and symbol for targeted retrieval. ```go params := map[string]interface{}{ "category": "linear", "symbol": "ETHUSDT", } result, err := client.NewUtaBybitServiceWithParams(params).GetMarketTickers(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Broker Account Info Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Fetches information about the broker's account. This is a public endpoint. ```go // Get broker account info brokerInfo, _ := client.NewUtaBybitServiceNoParams().GetBrokerAccountInfo(context.Background()) fmt.Println(bybit.PrettyPrint(brokerInfo)) ``` -------------------------------- ### Get Earn Product Info - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves information about available earn products, such as flexible savings or staking. Requires category and coin. ```go // Get available earn products productParams := map[string]interface{}{"category": "FlexibleSaving", "coin": "USDT"} products, err := client.NewUtaBybitServiceWithParams(productParams).GetEarnProductInfo(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(products)) ``` -------------------------------- ### Get Coin Info - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves information about available coins. No parameters are required. ```go // Get coin info coinInfo, _ := client.NewUtaBybitServiceNoParams().GetCoinInfo(context.Background()) fmt.Println(bybit.PrettyPrint(coinInfo)) ``` -------------------------------- ### Place Orders via WebSocket Trade Channel Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Place, amend, or cancel orders directly via the WebSocket trade channel. This example demonstrates creating a limit order for ETHUSDT. Ensure the 'X-BAPI-TIMESTAMP' is current and 'X-BAPI-RECV-WINDOW' is set appropriately. ```go import ( bybit "github.com/bybit-exchange/bybit.go.api" "fmt" "time" ) ws := bybit.NewBybitPrivateWebSocket( bybit.WEBSOCKET_TRADE_TESTNET, "YOUR_API_KEY", "YOUR_API_SECRET", func(message string) error { fmt.Println("Trade response:", message) return nil }, bybit.WithPingInterval(10), ) ws.Connect() ws.SendTradeRequest(map[string]interface{}{ "reqId": "req-001", "header": map[string]string{ "X-BAPI-TIMESTAMP": fmt.Sprintf("%d", time.Now().UnixMilli()), "X-BAPI-RECV-WINDOW": "8000", "Referer": "bot-001", }, "op": "order.create", "args": []interface{}{ map[string]interface{}{ "symbol": "ETHUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.2", "price": "2800", "category": "linear", "timeInForce": "PostOnly", }, }, }) select {} ``` -------------------------------- ### Get Server Time Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieve the current server time. No authentication is required for this endpoint. ```go result, err := client.NewUtaBybitServiceNoParams().GetServerTime(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Manual WebSocket Subscription and Disconnect Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Manually subscribe to specific public WebSocket streams like order books or trades, or send custom requests. This example also shows how to gracefully disconnect from the WebSocket connection. ```go ws := bybit.NewBybitPublicWebSocket( bybit.SPOT_MAINNET, func(message string) error { fmt.Println("Message:", message) return nil }, ) ws.Connect() // Manual subscription ws.SendSubscription([]string{"orderbook.50.BTCUSDT", "publicTrade.BTCUSDT"}) // Or use SendRequest for custom ops ws.SendRequest("subscribe", map[string]interface{}{"args": []string{"tickers.ETHUSDT"}}, nil) // Graceful disconnect if err := ws.Disconnect(); err != nil { fmt.Println("Disconnect error:", err) } ``` -------------------------------- ### Get Earn Positions - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves a list of current earn product positions. No parameters are required. ```go // Get earn positions positions, _ := client.NewUtaBybitServiceNoParams().GetEarnRedeemPosition(context.Background()) fmt.Println(bybit.PrettyPrint(positions)) ``` -------------------------------- ### Set Custom Recv Window for Requests Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Override the default receive window (5000 ms) for signed REST API requests. This example extends the window to 10 seconds for fetching open orders. ```go params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "limit": 10} result, err := client.NewUtaBybitServiceWithParams(params).GetOpenOrders( context.Background(), bybit.WithRecvWindow("10000"), // extend to 10 seconds ) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Position List Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Retrieve a list of current positions for a specified account category and settlement coin. Filters can be applied. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) params := map[string]interface{}{"category": "linear", "settleCoin": "USDT", "limit": 10} orderResult, err := client.NewUtaBybitServiceWithParams(params).GetPositionList(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(orderResult)) ``` -------------------------------- ### Utility Functions Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Provides access to helpful utility functions for common tasks such as pretty-printing response structs, getting the current Unix timestamp in milliseconds, and formatting time values. ```APIDOC ## Utility Functions Helper functions available at the package level. ```go // Pretty-print any response struct as indented JSON fmt.Println(bybit.PrettyPrint(result)) // Get current Unix timestamp in milliseconds (used for signing) ts := bybit.GetCurrentTime() fmt.Println("Current time ms:", ts) // Format a time.Time value to Unix milliseconds import "time" ts2 := bybit.FormatTimestamp(time.Now()) fmt.Println("Formatted ts:", ts2) ``` ``` -------------------------------- ### Get Transaction Log Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Fetch transaction logs for a given account type and category. This helps in auditing and tracking account activity. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) params := map[string]interface{}{"accountType": "UNIFIED", "category": "linear"} accountResult, err := client.NewUtaBybitServiceWithParams(params).GetTransactionLog(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(accountResult)) ``` -------------------------------- ### Get Spread Trade Instruments Info (Public) Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves information about available spread trade instruments. Requires a symbol. This is a public endpoint. ```go // Get spread instruments (public) instrParams := map[string]interface{}{"symbol": "BTC-SPREAD"} instruments, _ := client.NewUtaBybitServiceWithParams(instrParams).GetSpreadTradeInstrumentsInfo(context.Background()) fmt.Println(bybit.PrettyPrint(instruments)) ``` -------------------------------- ### Get Order Book Depth Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Fetch the order book depth for a specified symbol. The 'limit' parameter controls the number of order entries returned. ```go params := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", "limit": 50, } result, err := client.NewUtaBybitServiceWithParams(params).GetOrderBookInfo(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Initialize Bybit HTTP Client Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Create an HTTP client for mainnet or testnet with optional proxy and debug settings. Available base URLs include MAINNET, TESTNET, DEMO_ENV, and others. ```go import ( bybit "github.com/bybit-exchange/bybit.go.api" "context" "fmt" ) // Testnet client client := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET), ) ``` ```go // Mainnet client with debug logging mainnetClient := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.MAINNET), bybit.WithDebug(true), ) ``` ```go // Client with proxy proxyClient := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithProxyURL("http://proxy.example.com:8080"), ) ``` ```go // Available base URL constants: // bybit.MAINNET, bybit.TESTNET, bybit.DEMO_ENV, // bybit.MAINNET_BACKT, bybit.NETHERLAND_ENV, // bybit.HONGKONG_ENV, bybit.TURKEY_ENV, bybit.KAZAKHSTAN_ENV ``` -------------------------------- ### Client Initialization Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Create an HTTP client for mainnet or testnet with optional proxy and debug settings. ```APIDOC ## Client Initialization Create an HTTP client for mainnet or testnet with optional proxy and debug settings. ```go import ( bybit "github.com/bybit-exchange/bybit.go.api" "context" "fmt" ) // Testnet client client := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET), ) // Mainnet client with debug logging mainnetClient := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.MAINNET), bybit.WithDebug(true), ) // Client with proxy proxyClient := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithProxyURL("http://proxy.example.com:8080"), ) // Available base URL constants: // bybit.MAINNET, bybit.TESTNET, bybit.DEMO_ENV, // bybit.MAINNET_BACKT, bybit.NETHERLAND_ENV, // bybit.HONGKONG_ENV, bybit.TURKEY_ENV, bybit.KAZAKHSTAN_ENV ``` ``` -------------------------------- ### Manage Positions in Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieve and configure futures/options positions, including setting leverage and trading stops (Take Profit/Stop Loss). Also includes retrieving closed PnL. ```go // List positions posParams := map[string]interface{}{"category": "linear", "settleCoin": "USDT", "limit": 10} positions, err := client.NewUtaBybitServiceWithParams(posParams).GetPositionList(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(positions)) ``` ```go // Set leverage levParams := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "buyLeverage": "10", "sellLeverage": "10", } _, _ = client.NewUtaBybitServiceWithParams(levParams).SetPositionLeverage(context.Background()) ``` ```go // Set trading stop (TP/SL) tpslParams := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "positionIdx": 0, "takeProfit": "35000", "stopLoss": "28000", } _, _ = client.NewUtaBybitServiceWithParams(tpslParams).SetPositionTradingStop(context.Background()) ``` ```go // Get closed PnL pnlParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "limit": 10} pnl, _ := client.NewUtaBybitServiceWithParams(pnlParams).GetClosePnl(context.Background()) fmt.Println(bybit.PrettyPrint(pnl)) ``` -------------------------------- ### GetMarketTickers Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Get the latest ticker price and 24h stats for one or all symbols. ```APIDOC ## Market Data — Tickers Get the latest ticker price and 24h stats for one or all symbols. ```go params := map[string]interface{}{ "category": "linear", "symbol": "ETHUSDT", } result, err := client.NewUtaBybitServiceWithParams(params).GetMarketTickers(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` ``` -------------------------------- ### Get Position List Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Retrieves a list of positions based on specified parameters. ```APIDOC ## Get Position List ### Description This method retrieves a list of user positions, allowing filtering by category, settle coin, and other criteria. ### Method ```APIDOC GET ``` ### Endpoint ```APIDOC /v5/position/list ``` ### Parameters #### Query Parameters - **category** (string) - Required - e.g., "linear" - **settleCoin** (string) - Optional - e.g., "USDT" - **limit** (integer) - Optional - e.g., 10 ### Request Example ```json { "category": "linear", "settleCoin": "USDT", "limit": 10 } ``` ### Response #### Success Response (200) - **result** (object) - The list of positions. - **retCode** (integer) - The return code. - **retMsg** (string) - The return message. ``` -------------------------------- ### Place Order by Map Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Demonstrates how to place an order using a map of parameters for the Bybit API. ```APIDOC ## Place Order by Map ### Description This method allows placing an order by providing a map of parameters. It supports various order types and configurations. ### Method ```APIDOC POST ``` ### Endpoint ```APIDOC /v5/order/create ``` ### Parameters #### Request Body - **category** (string) - Required - e.g., "linear" - **symbol** (string) - Required - e.g., "BTCUSDT" - **side** (string) - Required - e.g., "Buy" - **positionIdx** (integer) - Required - e.g., 0 - **orderType** (string) - Required - e.g., "Limit" - **qty** (string) - Required - e.g., "0.001" - **price** (string) - Required - e.g., "10000" - **timeInForce** (string) - Required - e.g., "GTC" ### Request Example ```json { "category": "linear", "symbol": "BTCUSDT", "side": "Buy", "positionIdx": 0, "orderType": "Limit", "qty": "0.001", "price": "10000", "timeInForce": "GTC" } ``` ### Response #### Success Response (200) - **result** (object) - The result of the order placement. - **retCode** (integer) - The return code. - **retMsg** (string) - The return message. ``` -------------------------------- ### Connect to Bybit Trade Websocket Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Establishes a connection to the Bybit testnet trade websocket. Requires API key and secret. Includes a custom ping interval. ```go ws := bybit.NewBybitPrivateWebSocket(bybit.WEBSOCKET_TRADE_TESTNET, "YOUR_API_KEY", "YOUR_API_SECRET", func(message string) error { fmt.Println("Received:", message) return nil }, bybit.WithPingInterval(10)) _, _ = ws.Connect().SendTradeRequest(map[string]interface{}{ "reqId": "test-005", "header": map[string]string{ "X-BAPI-TIMESTAMP": fmt.Sprintf("%d", time.Now().UnixMilli()), "X-BAPI-RECV-WINDOW": "8000", "Referer": "bot-001", }, "op": "order.create", "args": []interface{}{ map[string]interface{}{ "symbol": "ETHUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.2", "price": "2800", "category": "linear", "timeInForce": "PostOnly", }, }, }) select {} ``` -------------------------------- ### Place Order using Map Parameters Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Place a single order using a map of parameters. This method supports all order types and categories. Ensure API keys and base URL are correctly configured. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.001", "price": "30000", "timeInForce": "GTC", "positionIdx": 0, } result, err := client.NewUtaBybitServiceWithParams(params).PlaceOrder(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Transaction Log Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Fetches the transaction log for a specified account type and category. ```APIDOC ## Get Transaction Log ### Description This method retrieves the transaction log, providing details of past transactions for a given account type and category. ### Method ```APIDOC GET ``` ### Endpoint ```APIDOC /v5/account/transaction-log ``` ### Parameters #### Query Parameters - **accountType** (string) - Required - e.g., "UNIFIED" - **category** (string) - Required - e.g., "linear" ### Request Example ```json { "accountType": "UNIFIED", "category": "linear" } ``` ### Response #### Success Response (200) - **result** (object) - The transaction log data. - **retCode** (integer) - The return code. - **retMsg** (string) - The return message. ``` -------------------------------- ### Retrieve Account Information in Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Fetch wallet balances, fee rates, transaction logs, and account settings. This includes methods for different account types and specific data points like fees and transaction history. ```go // Wallet balance (UTA account) walletParams := map[string]interface{}{"accountType": "UNIFIED", "coin": "BTC"} wallet, err := client.NewUtaBybitServiceWithParams(walletParams).GetAccountWallet(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(wallet)) ``` ```go // Fee rates feeParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT"} fees, _ := client.NewUtaBybitServiceWithParams(feeParams).GetFeeRates(context.Background()) fmt.Println(bybit.PrettyPrint(fees)) ``` ```go // Transaction log (UTA) txParams := map[string]interface{}{"accountType": "UNIFIED", "category": "linear", "limit": 20} tx, _ := client.NewUtaBybitServiceWithParams(txParams).GetTransactionLog(context.Background()) fmt.Println(bybit.PrettyPrint(tx)) ``` ```go // Account info info, _ := client.NewUtaBybitServiceNoParams().GetAccountInfo(context.Background()) fmt.Println(bybit.PrettyPrint(info)) ``` ```go // Set margin mode marginParams := map[string]interface{}{"setMarginMode": "PORTFOLIO_MARGIN"} _, _ = client.NewUtaBybitServiceWithParams(marginParams).SetMarginMode(context.Background()) ``` -------------------------------- ### Place Order using Typed Builder Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Place an order using the fluent `Order` builder for compile-time safety and optional parameter chaining. This method is recommended for type safety. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) result, err := client.NewPlaceOrderService("linear", "XRPUSDT", "Buy", "Market", "10"). TimeInForce("GTC"). TakeProfit("0.70"). StopLoss("0.50"). ReduceOnly(false). Do(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Broker Earnings Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves broker earnings. Requires business type and a limit for the number of results. ```go // Get broker earnings earningParams := map[string]interface{}{"bizType": "SPOT", "limit": 10} earnings, err := client.NewUtaBybitServiceWithParams(earningParams).GetBrokerEarning(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(earnings)) ``` -------------------------------- ### Create Sub-Member - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Creates a new sub-member account. Requires username, password, member type, and other configuration options. ```go // Create sub-member createSubParams := map[string]interface{}{ "username": "sub_user_01", "password": "Bybit1234!", "memberType": 1, "switch": 1, "isUta": true, "note": "created via API", } subMember, err := client.NewUtaBybitServiceWithParams(createSubParams).CreateSubMember(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(subMember)) ``` -------------------------------- ### View Fixed Borrowing Market (Public) Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Fetches information about the fixed-term borrowing market. This is a public endpoint. ```go // View borrowing market (public) market, _ := client.NewUtaBybitServiceNoParams().GetFixedBorrowingMarket(context.Background()) fmt.Println(bybit.PrettyPrint(market)) ``` -------------------------------- ### Connect to Bybit Private Websocket Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Establishes a connection to the Bybit private websocket endpoint. Requires API key and secret for authenticated access. ```go ws := bybit.NewBybitPrivateWebSocket("wss://stream-testnet.bybit.com/v5/private", "YOUR_API_KEY", "YOUR_API_SECRET", func(message string) error { fmt.Println("Received:", message) return nil }) _ = ws.Connect([]string{"order"}) select {} ``` -------------------------------- ### Place Order - Typed Builder Style Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Use the fluent `Order` builder for compile-time safety and optional parameter chaining when placing an order. ```APIDOC ## Place Order — Typed Builder Style Use the fluent `Order` builder for compile-time safety and optional parameter chaining. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) result, err := client.NewPlaceOrderService("linear", "XRPUSDT", "Buy", "Market", "10"). TimeInForce("GTC"). TakeProfit("0.70"). StopLoss("0.50"). ReduceOnly(false). Do(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` ``` -------------------------------- ### Configure Disconnect Cancel All (DCP) in Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Set up automatic order cancellation when the connection drops. Configure the time window in seconds before cancellation occurs after a disconnect. ```go params := map[string]interface{}{ "timeWindow": 10, // seconds before all orders are cancelled after disconnect } result, err := client.NewUtaBybitServiceWithParams(params).SetDisconnectCancelAll(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Place Order by Map Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Use this method to place a limit order by providing parameters as a map. Ensure to replace placeholders with actual values. ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "side": "Buy", "positionIdx": 0, "orderType": "Limit", "qty": "0.001", "price": "10000", "timeInForce": "GTC"} orderResult, err := client.NewUtaBybitServiceWithParams(params).PlaceOrder(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(orderResult)) ``` -------------------------------- ### Get Sub-UID List - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves a list of User IDs for all sub-members associated with the main account. No parameters are required. ```go // List sub-member UIDs subList, _ := client.NewUtaBybitServiceNoParams().GetSubUidList(context.Background()) fmt.Println(bybit.PrettyPrint(subList)) ``` -------------------------------- ### Pre-Check Order Submission in Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Validate an order before actual submission to check price limits and margin requirements. Ensure all necessary order parameters are provided. ```go params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.001", "price": "30000", "timeInForce": "GTC", } result, err := client.NewUtaBybitServiceWithParams(params).PlacePreCheckOrder(context.Background()) if err != nil { fmt.Println("Pre-check failed:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Funding Rate History Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieve historical funding rates for a perpetual contract. The 'limit' parameter specifies the number of historical records to fetch. ```go params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "limit": 10, } result, err := client.NewUtaBybitServiceWithParams(params).GetFundingRateHistory(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Get Spot Margin State - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieves the current spot margin trading state for UTA accounts. No specific parameters are needed. ```go // Get spot margin state (UTA only) stateParams := map[string]interface{}{} state, err := client.NewUtaBybitServiceWithParams(stateParams).GetSpotMarginState(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(state)) ``` -------------------------------- ### Earn (Savings/Staking) Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Manage your Bybit Earn products, including querying available products and managing staking positions. ```APIDOC ## Get Earn Product Info ### Description Retrieves information about available Earn products, such as flexible savings or staking. ### Method GET ### Endpoint /v5/earn/product-info ### Parameters #### Query Parameters - **category** (string) - Required - The category of the earn product (e.g., "FlexibleSaving"). - **coin** (string) - Required - The coin for which to retrieve product info (e.g., "USDT"). ### Request Example ```go productParams := map[string]interface{}{"category": "FlexibleSaving", "coin": "USDT"} products, err := client.NewUtaBybitServiceWithParams(productParams).GetEarnProductInfo(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(products)) ``` ### Response #### Success Response (200) - **list** (array) - List of available earn products. - **serialNo** (string) - The serial number of the product. - **title** (string) - The title of the product. - **coin** (string) - The coin offered in the product. - **apy** (string) - The Annual Percentage Yield (APY). - **minAmount** (string) - The minimum amount that can be subscribed. - **maxAmount** (string) - The maximum amount that can be subscribed. - **period** (integer) - The duration of the product in days. - **status** (string) - The status of the product (e.g., "ON"). - **category** (string) - The category of the product. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "serialNo": "YOUR_PRODUCT_ID", "title": "USDT Flexible Savings", "coin": "USDT", "apy": "3.0", "minAmount": "10", "maxAmount": "1000000", "period": 30, "status": "ON", "category": "FlexibleSaving" } ] }, "time": 1677677677000 } ``` ``` ```APIDOC ## Redeem Earn Order ### Description Subscribes to or redeems an Earn product order. ### Method POST ### Endpoint /v5/earn/redeem ### Parameters #### Request Body - **accountType** (string) - Required - The account type (e.g., "FUND"). - **coin** (string) - Required - The coin involved in the order. - **amount** (string) - Required - The amount for the order. - **orderType** (integer) - Required - The type of order (1 for subscribe, 2 for redeem). - **serialNo** (string) - Required - The serial number of the Earn product. ### Request Example ```go redeemParams := map[string]interface{}{ "accountType": "FUND", "coin": "USDT", "amount": "100", "orderType": 1, // 1 = subscribe "serialNo": "YOUR_PRODUCT_ID", } _, _ = client.NewUtaBybitServiceWithParams(redeemParams).RedeemEarnOrder(context.Background()) ``` ### Response #### Success Response (200) - **orderId** (string) - The ID of the placed order. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "orderId": "ORDER_ID" }, "time": 1677677677000 } ``` ``` ```APIDOC ## Get Earn Redeem Position ### Description Retrieves your current Earn product positions, including subscribed and redeemed amounts. ### Method GET ### Endpoint /v5/earn/position ### Parameters None ### Response #### Success Response (200) - **list** (array) - List of your Earn positions. - **serialNo** (string) - The serial number of the product. - **title** (string) - The title of the product. - **coin** (string) - The coin involved. - **amount** (string) - The subscribed or redeemed amount. - **createAt** (integer) - The creation timestamp. - **updateAt** (integer) - The update timestamp. - **status** (string) - The status of the position. - **apy** (string) - The APY for the position. - **period** (integer) - The duration of the product. - **redeemDate** (integer) - The date of redemption. - **principal** (string) - The principal amount. - **interest** (string) - The earned interest. ### Request Example ```go positions, _ := client.NewUtaBybitServiceNoParams().GetEarnRedeemPosition(context.Background()) fmt.Println(bybit.PrettyPrint(positions)) ``` ### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "serialNo": "YOUR_PRODUCT_ID", "title": "USDT Flexible Savings", "coin": "USDT", "amount": "100.0", "createAt": 1677677677000, "updateAt": 1677677677000, "status": "SUBSCRIBED", "apy": "3.0", "period": 30, "redeemDate": 0, "principal": "100.0", "interest": "0.0" } ] }, "time": 1677677677000 } ``` ``` -------------------------------- ### Get Market Kline Data Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Fetch OHLCV kline data for any category and symbol. The 'interval' parameter accepts values like '1' for 1-minute, '60' for hourly, or 'D' for daily. ```go params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "interval": "60", // 1-minute: "1", hourly: "60", daily: "D" "limit": 5, } result, err := client.NewUtaBybitServiceWithParams(params).GetMarketKline(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) ``` -------------------------------- ### Subscribe to Order Book Public Websocket Source: https://github.com/bybit-exchange/bybit.go.api/blob/main/README.md Connects to the Bybit public spot websocket to subscribe to order book updates for a specific symbol. ```go ws := bybit.NewBybitPublicWebSocket("wss://stream.bybit.com/v5/public/spot", func(message string) error { fmt.Println("Received:", message) return nil }) _ = ws.Connect([]string{"orderbook.1.BTCUSDT"}) select {} ``` -------------------------------- ### Place Order - Map Style Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Place a single order using a parameter map. This method supports all order types and categories. ```APIDOC ## Place Order — Map Style Place a single order using a parameter map (supports all order types and categories). ```go client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET)) params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.001", "price": "30000", "timeInForce": "GTC", "positionIdx": 0, } result, err := client.NewUtaBybitServiceWithParams(params).PlaceOrder(context.Background()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(bybit.PrettyPrint(result)) // Output: {"retCode":0,"retMsg":"OK","result":{"orderId":"...","orderLinkId":""},...} ``` ``` -------------------------------- ### Set Spot Margin Auto-Repay Mode - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Configures the auto-repayment mode for spot margin. Requires specifying the mode, with '1' indicating a specific setting. ```go // Set auto-repay mode (UTA only) repayParams := map[string]interface{}{"autoRepayMode": 1} _, _ = client.NewUtaBybitServiceWithParams(repayParams).SetSpotMarginAutoRepayMode(context.Background()) ``` -------------------------------- ### Get Market Data: Open Interest, Long/Short Ratio, Historical Volatility Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieve market analytics data such as open interest, long/short ratio, and historical volatility. Ensure the correct category and symbol are specified. ```go // Open interest oiParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "intervalTime": "5min"} oi, _ := client.NewUtaBybitServiceWithParams(oiParams).GetOpenInterests(context.Background()) fmt.Println(bybit.PrettyPrint(oi)) ``` ```go // Long/short ratio lsParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "period": "1h"} ls, _ := client.NewUtaBybitServiceWithParams(lsParams).GetLongShortRatio(context.Background()) fmt.Println(bybit.PrettyPrint(ls)) ``` ```go // Historical volatility (options) hvParams := map[string]interface{}{"category": "option", "baseCoin": "BTC"} hv, _ := client.NewUtaBybitServiceWithParams(hvParams).GetHistoryVolatility(context.Background()) fmt.Println(bybit.PrettyPrint(hv)) ``` -------------------------------- ### Subscribe to Public WebSocket Channels Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Subscribes to real-time public market data streams using WebSockets. Supports different endpoints like SPOT and LINEAR. Requires a callback function to handle incoming messages. ```go import ( bybit "github.com/bybit-exchange/bybit.go.api" "fmt" ) // Subscribe to order book updates ws := bybit.NewBybitPublicWebSocket( bybit.SPOT_MAINNET, // wss://stream.bybit.com/v5/public/spot func(message string) error { fmt.Println("Received:", message) return nil }, ) _ = ws.Connect([]string{"orderbook.1.BTCUSDT", "tickers.BTCUSDT"}) select {} // block forever // Subscribe to linear perpetual klines wsLinear := bybit.NewBybitPublicWebSocket( bybit.LINEAR_MAINNET, func(message string) error { fmt.Println("Kline:", message) return nil }, ) _ = wsLinear.Connect([]string{"kline.1.BTCUSDT"}) select {} ``` -------------------------------- ### Create Withdrawal - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Initiates a withdrawal of assets to an external wallet address. Requires coin, chain, address, amount, and account type. Timestamp is automatically generated. ```go // Withdrawal withdrawParams := map[string]interface{}{ "coin": "USDT", "chain": "TRX", "address": "YOUR_WALLET_ADDRESS", "amount": "50", "timestamp": bybit.GetCurrentTime(), "accountType": "UNIFIED", } wd, _ := client.NewUtaBybitServiceWithParams(withdrawParams).CreateWithdraw(context.Background()) fmt.Println(bybit.PrettyPrint(wd)) ``` -------------------------------- ### Set Spot Margin Leverage - Bybit API Go Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Sets the leverage for spot margin trading. Requires the desired leverage value. ```go // Set spot margin leverage (UTA only) leverageParams := map[string]interface{}{"leverage": "3"} _, _ = client.NewUtaBybitServiceWithParams(leverageParams).SetSpotMarginLeverage(context.Background()) ``` -------------------------------- ### Connect to Private WebSocket Channel Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Authenticate and subscribe to private account and order update streams using the Bybit Private WebSocket. Ensure you replace 'YOUR_API_KEY' and 'YOUR_API_SECRET' with your actual credentials. The ping interval is set to 20 seconds and the maximum alive time to 1 hour. ```go ws := bybit.NewBybitPrivateWebSocket( bybit.WEBSOCKET_PRIVATE_TESTNET, "YOUR_API_KEY", "YOUR_API_SECRET", func(message string) error { fmt.Println("Private update:", message) return nil }, bybit.WithPingInterval(20), bybit.WithMaxAliveTime("1h"), ) // Subscribes and authenticates automatically _ = ws.Connect([]string{"order", "position", "wallet", "execution"}) select {} ``` -------------------------------- ### Custom Recv Window Option Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Illustrates how to override the default receive window for signed requests using the `WithRecvWindow` option. This allows for adjusting the server's response timeout for specific API calls. ```APIDOC ## Request Options — Custom Recv Window Override the default `recvWindow` (5000 ms) on any signed request. ```go params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "limit": 10} result, err := client.NewUtaBybitServiceWithParams(params).GetOpenOrders( context.Background(), bybit.WithRecvWindow("10000"), // extend to 10 seconds ) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(result)) ``` ``` -------------------------------- ### Manual Subscription and Disconnect Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Demonstrates how to manually subscribe to public WebSocket streams and gracefully disconnect from the WebSocket connection. This allows for more control over subscriptions and connection management. ```APIDOC ## WebSocket — Manual Subscription and Disconnect Send subscriptions manually and cleanly close a WebSocket connection. ```go ws := bybit.NewBybitPublicWebSocket( bybit.SPOT_MAINNET, func(message string) error { fmt.Println("Message:", message) return nil }, ) ws.Connect() // Manual subscription ws.SendSubscription([]string{"orderbook.50.BTCUSDT", "publicTrade.BTCUSDT"}) // Or use SendRequest for custom ops ws.SendRequest("subscribe", map[string]interface{}{"args": []string{"tickers.ETHUSDT"}}, nil) // Graceful disconnect if err := ws.Disconnect(); err != nil { fmt.Println("Disconnect error:", err) } ``` ``` -------------------------------- ### Position Management Source: https://context7.com/bybit-exchange/bybit.go.api/llms.txt Retrieve and configure futures/options positions. This includes listing positions, setting leverage, configuring take-profit and stop-loss orders, and retrieving profit and loss data. ```APIDOC ## Position Management Retrieve and configure futures/options positions. ### List Positions ```go posParams := map[string]interface{}{"category": "linear", "settleCoin": "USDT", "limit": 10} positions, err := client.NewUtaBybitServiceWithParams(posParams).GetPositionList(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(bybit.PrettyPrint(positions)) ``` ### Set Leverage ```go levParams := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "buyLeverage": "10", "sellLeverage": "10", } _, _ = client.NewUtaBybitServiceWithParams(levParams).SetPositionLeverage(context.Background()) ``` ### Set Trading Stop (TP/SL) ```go tpslParams := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "positionIdx": 0, "takeProfit": "35000", "stopLoss": "28000", } _, _ = client.NewUtaBybitServiceWithParams(tpslParams).SetPositionTradingStop(context.Background()) ``` ### Get Closed PnL ```go pnlParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "limit": 10} pnl, _ := client.NewUtaBybitServiceWithParams(pnlParams).GetClosePnl(context.Background()) fmt.Println(bybit.PrettyPrint(pnl)) ``` ```