### Getting Started Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/introduction.md Provides a step-by-step guide for new users to begin integrating with the Bybit API v5, including account creation and API key generation. ```APIDOC ## Getting Started 1. [Create a Bybit account](https://www.bybit.com/register) 2. [Generate API keys](https://www.bybit.com/app/user/api-management) 3. Read the [Authentication](./authentication.md) guide 4. Check [Rate Limits](./rate-limits.md) to understand API constraints 5. Review [Error Codes](./error-codes.md) for troubleshooting ``` -------------------------------- ### Account Management Examples Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/go.md Examples demonstrating how to retrieve account information such as wallet balance and positions, and how to set leverage. ```APIDOC ## Account Management Examples ### Get Wallet Balance #### Description Retrieves the wallet balance for a specified account type and coin. #### Method GET #### Endpoint `/v5/account/wallet-balance` #### Query Parameters - **accountType** (string) - Required - The type of account (e.g., UNIFIED, CONTRACT, SPOT). - **coin** (string) - Optional - The specific coin for which to get the balance. #### Request Example ```go params := map[string]interface{}{ "accountType": "UNIFIED", "coin": "USDT", } balanceResult, err := client.NewAccountService().GetWalletBalance(context.Background(), params) ``` ### Get Positions #### Description Retrieves current positions for a given category and symbol. #### Method GET #### Endpoint `/v5/position/list` #### Query Parameters - **category** (string) - Required - The category of positions (e.g., linear, inverse). - **symbol** (string) - Optional - The specific trading symbol (e.g., BTCUSDT). #### Request Example ```go params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", } positionResult, err := client.NewAccountService().GetPositions(context.Background(), params) ``` ### Set Leverage #### Description Sets the leverage for a specified symbol within a given category. #### Method POST #### Endpoint `/v5/position/set-leverage` #### Request Body - **category** (string) - Required - The category of the position (e.g., linear). - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). - **buyLeverage** (string) - Required - The leverage to set for buy orders. - **sellLeverage** (string) - Required - The leverage to set for sell orders. #### Request Example ```go params := map[string]interface{}{ "category": "linear", "symbol": "BTCUSDT", "buyLeverage": "2", "sellLeverage": "2", } leverageResult, err := client.NewAccountService().SetLeverage(context.Background(), params) ``` ``` -------------------------------- ### Get Account Info - HTTP Request Example Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/account-info.md Example HTTP GET request to retrieve spot account information from the Bybit API. It includes necessary headers like API key, timestamp, and signature. ```http GET /v5/account/info HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Market Data Examples Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/java.md Provides examples of how to retrieve market data, including klines and server time, using the SDK. ```APIDOC ## Market Data Examples ### Description Examples demonstrating how to fetch market data such as klines (price, index) and server time using the Bybit Java SDK. ### Method `client.getMarketLinesData()` `client.getMarketPriceLinesData()` `client.getIndexPriceLinesData()` `client.getServerTime()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **category** (CategoryType) - Required - The category of the market (e.g., LINEAR, INVERSE). - **symbol** (String) - Required - The trading symbol (e.g., BTCUSDT). - **marketInterval** (MarketInterval) - Required - The interval for kline data (e.g., WEEKLY, DAILY). ### Request Example ```java // Get market data using builder pattern var marketKLineRequest = MarketDataRequest.builder() .category(CategoryType.LINEAR) .symbol("BTCUSDT") .marketInterval(MarketInterval.WEEKLY) .build(); // Get weekly market kline var marketKlineResult = client.getMarketLinesData(marketKLineRequest); System.out.println(marketKlineResult); // Get weekly market price kline var marketPriceKlineResult = client.getMarketPriceLinesData(marketKLineRequest); System.out.println(marketPriceKlineResult); // Get weekly index price kline var indexPriceKlineResult = client.getIndexPriceLinesData(marketKLineRequest); System.out.println(indexPriceKlineResult); // Get server time var serverTime = client.getServerTime(); System.out.println(serverTime); ``` ### Response #### Success Response (200) - **marketKlineResult** (Object) - Kline data for the specified symbol and interval. - **marketPriceKlineResult** (Object) - Price kline data. - **indexPriceKlineResult** (Object) - Index price kline data. - **serverTime** (Object) - Server timestamp. #### Response Example ```json { "example": "Kline data, Price Kline data, Index Price Kline data, or Server Time" } ``` ``` -------------------------------- ### Bybit V5 Account Info HTTP Request Example Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/options/account/account-info.md Example of an HTTP GET request to the Bybit V5 API endpoint for fetching account information. This includes necessary headers like API key, signature, timestamp, and receive window. It demonstrates how to optionally specify a base coin. ```http GET /v5/account/info?baseCoin=BTC HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Install Bybit C# SDK using dotnet CLI Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/csharp.md Installs the `bybit.net.api` package using the .NET CLI. This is a prerequisite for using the SDK in your C# project. ```bash dotnet add package bybit.net.api ``` -------------------------------- ### Install Bybit Node.js SDK Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/nodejs.md Installs the `bybit-api` Node.js package using npm. It's recommended to always use the latest version for full v5 API support. ```bash npm install --save bybit-api ``` -------------------------------- ### Install pybit Python SDK Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/python.md This snippet shows how to install the pybit Python SDK using pip. It requires Python 3.9.1 or higher. Ensure you have pip installed and updated. ```bash pip install pybit ``` -------------------------------- ### Go: Initialize Bybit HTTP Client Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/go.md Demonstrates how to initialize the Bybit HTTP client for both mainnet and testnet environments. It also shows optional configurations like setting request timeouts and enabling debug logging. Requires the 'bybit.go.api' library. ```go import ( "context" "fmt" "log" "time" "github.com/bybit-exchange/bybit.go.api" ) func main() { // Create client for mainnet client := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.MAINNET) ) // For testnet testnetClient := bybit.NewBybitHttpClient( "YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET) ) // Optional: Configure client options client.WithTimeout(5 * time.Second) // Set request timeout client.WithDebug(true) // Enable debug logging fmt.Println("Bybit HTTP clients initialized.") } ``` -------------------------------- ### Get Wallet Balance (HTTP Request Example) Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/wallet-balance.md Example of an HTTP GET request to retrieve wallet balance for a specified account type and coin. This includes necessary headers for API authentication and request parameters. ```http GET /v5/account/wallet-balance?accountType=UNIFIED&coin=USDT HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Python REST API Authentication and Request Examples Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/authentication.md This Python code demonstrates how to generate authentication headers for Bybit's V5 API using HMAC SHA256. It includes functions for generating signatures for GET and POST requests and provides examples for fetching wallet balance and placing an order. Requires the 'requests', 'hashlib', 'hmac', 'time', 'json', and 'urllib.parse' libraries. ```python import hmac import hashlib import time import json import requests from urllib.parse import urlencode def generate_signature(api_key, api_secret, recv_window, method, params=None): """ Generate signature for API request :param api_key: Your API key :param api_secret: Your API secret :param recv_window: Request valid time window :param method: HTTP method (GET or POST) :param params: Request parameters :return: Dict with authentication headers """ timestamp = str(int(time.time() * 1000)) param_str = "" if method == "GET": if params: param_str = urlencode(sorted(params.items())) else: # POST if params: param_str = json.dumps(params) sign_str = timestamp + api_key + str(recv_window) + param_str signature = hmac.new( bytes(api_secret, "utf-8"), bytes(sign_str, "utf-8"), hashlib.sha256 ).hexdigest() return { "X-BAPI-API-KEY": api_key, "X-BAPI-SIGN": signature, "X-BAPI-SIGN-TYPE": "2", "X-BAPI-TIMESTAMP": timestamp, "X-BAPI-RECV-WINDOW": str(recv_window) } # Example GET request def get_wallet_balance(api_key, api_secret): endpoint = "https://api.bybit.com/v5/account/wallet-balance" params = {"accountType": "UNIFIED"} headers = generate_signature( api_key=api_key, api_secret=api_secret, recv_window=5000, method="GET", params=params ) response = requests.get( endpoint, headers=headers, params=params ) return response.json() # Example POST request def place_order(api_key, api_secret, order_params): endpoint = "https://api.bybit.com/v5/order/create" headers = generate_signature( api_key=api_key, api_secret=api_secret, recv_window=5000, method="POST", params=order_params ) headers["Content-Type"] = "application/json" response = requests.post( endpoint, headers=headers, json=order_params ) return response.json() ``` -------------------------------- ### Client Initialization Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/java.md Demonstrates how to initialize the Bybit API client for mainnet, testnet, and public endpoints. ```APIDOC ## Client Initialization ### Description Initialize the Bybit API client for different environments (mainnet, testnet) and access levels (trade, market data). ### Method `BybitApiClientFactory.newInstance(...).newAsyncTradeRestClient()` `BybitApiClientFactory.newInstance(...).newMarketDataRestClient()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Create client for mainnet var client = BybitApiClientFactory.newInstance( "YOUR_API_KEY", "YOUR_API_SECRET", BybitApiConfig.MAINNET_DOMAIN, true // Enable debug mode ).newAsyncTradeRestClient(); // For testnet var testnetClient = BybitApiClientFactory.newInstance( "YOUR_API_KEY", "YOUR_API_SECRET", BybitApiConfig.TESTNET_DOMAIN, true ).newAsyncTradeRestClient(); // For public endpoints only var publicClient = BybitApiClientFactory.newInstance( BybitApiConfig.MAINNET_DOMAIN, true ).newMarketDataRestClient(); ``` ### Response #### Success Response (200) N/A (Client initialization does not return a direct response in this context). #### Response Example N/A ``` -------------------------------- ### HTTP Request Example for Settlement History Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/options/account/settlement.md Example of an HTTP GET request to the Bybit API to fetch settlement history for options trading. It specifies the endpoint, required headers, and query parameters. ```http GET /v5/option/settlement?category=option&symbol=BTC-24MAR23-16000-P HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Get Account Info - JSON Response Example Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/account-info.md Example JSON response when successfully retrieving spot account information from the Bybit API. It includes details about unified margin status, margin mode, and other account-related fields. ```json { "retCode": 0, "retMsg": "OK", "result": { "unifiedMarginStatus": 3, "marginMode": "PORTFOLIO_MARGIN", "dcpStatus": "DONE", "timeWindow": 60, "smpGroup": 0, "isMasterTrader": false, "spotHedgingStatus": true, "updatedTime": "1672132480000" }, "retExtInfo": {}, "time": 1672132480085 } ``` -------------------------------- ### Trading Examples Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/java.md Illustrates how to execute various trading operations, including placing single and batch orders, and amending orders. ```APIDOC ## Trading Examples ### Description Examples for performing trading operations such as creating single orders (limit, market), creating batch orders, and amending existing orders. ### Method `client.createOrder()` `client.amendOrder()` `client.createBatchOrder()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body For `createOrder` and `amendOrder`: - **category** (String) - Required - Order category (e.g., "option", "linear"). - **symbol** (String) - Required - Trading symbol (e.g., "BTCUSDT"). - **side** (String) - Required - Order side (e.g., "Buy", "Sell"). - **orderType** (String) - Required - Type of order (e.g., "Limit", "Market"). - **qty** (String) - Required - Order quantity. - Other fields like `price`, `orderIv`, `timeInForce`, `orderId`, etc., depending on the operation. For `createBatchOrder`: - **category** (CategoryType) - Required - Batch order category. - **request** (List) - Required - List of individual order requests. ### Request Example ```java // Place a single order using object Map order = Map.of( "category", "option", "symbol", "BTC-29DEC23-10000-P", "side", "Buy", "orderType", "Limit", "orderIv", "0.1", "qty", "0.1", "price", "5" ); client.createOrder(order, System.out::println); // Place a single order using builder pattern var newOrderRequest = TradeOrderRequest.builder() .category(CategoryType.LINEAR) .symbol("XRPUSDT") .side(Side.BUY) .orderType(TradeOrderType.MARKET) .qty("10") .timeInForce(TimeInForce.GOOD_TILL_CANCEL) .positionIdx(PositionIdx.ONE_WAY_MODE) .build(); client.createOrder(newOrderRequest, System.out::println); // Amend order var amendOrderRequest = TradeOrderRequest.builder() .orderId("1523347543495541248") .category(CategoryType.LINEAR) .symbol("XRPUSDT") .price("0.5") .qty("15") .build(); var amendedOrder = client.amendOrder(amendOrderRequest); System.out.println(amendedOrder); // Place batch orders var orderRequests = Arrays.asList( TradeOrderRequest.builder() .category(CategoryType.OPTION) .symbol("BTC-10FEB23-24000-C") .side(Side.BUY) .orderType(TradeOrderType.LIMIT) .qty("0.1") .price("5") .orderIv("0.1") .timeInForce(TimeInForce.GOOD_TILL_CANCEL) .orderLinkId("9b381bb1-401") .mmp(false) .reduceOnly(false) .build(), TradeOrderRequest.builder() .category(CategoryType.OPTION) .symbol("BTC-10FEB23-24000-C") .side(Side.BUY) .orderType(TradeOrderType.LIMIT) .qty("0.1") .price("5") .orderIv("0.1") .timeInForce(TimeInForce.GOOD_TILL_CANCEL) .orderLinkId("82ee86dd-001") .mmp(false) .reduceOnly(false) .build() ); var createBatchOrders = BatchOrderRequest.builder() .category(CategoryType.OPTION) .request(orderRequests) .build(); client.createBatchOrder(createBatchOrders, System.out::println); ``` ### Response #### Success Response (200) - **createOrder / createBatchOrder** (Object) - Confirmation of order placement. - **amendOrder** (Object) - Confirmation of order amendment. #### Response Example ```json { "example": "Order placement or amendment confirmation details" } ``` ``` -------------------------------- ### HTTP Request Example for Transaction Log Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/transaction-log.md Example of an HTTP GET request to the Bybit API for fetching transaction logs. It includes common headers like Host, authentication, and timestamp. This serves as a template for making requests to the /v5/account/transaction-log endpoint. ```http GET /v5/account/transaction-log?accountType=UNIFIED&category=spot¤cy=USDT HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Account Examples Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/java.md Demonstrates how to retrieve account-related information, such as position details and asset information. ```APIDOC ## Account Examples ### Description Examples for fetching account-related data, including user positions and asset details. ### Method `client.getPositionInfo()` `assetClient.getAssetCoinExchangeRecords()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body For `getPositionInfo`: - **category** (CategoryType) - Optional - The category of the position (e.g., LINEAR). - **symbol** (String) - Optional - The trading symbol. For `getAssetCoinExchangeRecords`: - No specific parameters shown in example, typically involves filters or specific coin requests. ### Request Example ```java // Get position information var client = BybitApiClientFactory.newInstance( "YOUR_API_KEY", "YOUR_API_SECRET", BybitApiConfig.TESTNET_DOMAIN ).newAsyncPositionRestClient(); var positionListRequest = PositionDataRequest.builder() .category(CategoryType.LINEAR) .symbol("BTCUSDT") .build(); client.getPositionInfo(positionListRequest, System.out::println); // Get asset information var assetClient = BybitApiClientFactory.newInstance( "YOUR_API_KEY", "YOUR_API_SECRET", BybitApiConfig.TESTNET_DOMAIN ).newAsyncAssetRestClient(); var coinExchangeRecordsRequest = AssetDataRequest.builder().build(); assetClient.getAssetCoinExchangeRecords(coinExchangeRecordsRequest, System.out::println); ``` ### Response #### Success Response (200) - **getPositionInfo** (Object) - Position data for the specified symbol. - **getAssetCoinExchangeRecords** (Object) - Coin exchange records. #### Response Example ```json { "example": "Position details or Asset coin exchange records" } ``` ``` -------------------------------- ### Place and Manage Orders Source: https://context7.com/suenot/bybit-docs-markdown/llms.txt Demonstrates how to place limit and market orders, cancel orders, and retrieve a list of open orders using the SDK. ```APIDOC ## Place Orders with SDK ### Description This section details how to place different types of orders (limit, market), cancel existing orders, and retrieve a list of currently open orders using the Bybit SDK. ### Method POST ### Endpoint /order ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for `place_order`) - **category** (string) - Required - Category of the symbol (e.g., 'spot', 'linear', 'inverse'). - **symbol** (string) - Required - Trading pair symbol (e.g., 'BTCUSDT'). - **side** (string) - Required - Order side ('Buy' or 'Sell'). - **orderType** (string) - Required - Type of order ('Limit' or 'Market'). - **qty** (string) - Required - Order quantity. - **price** (string) - Required for 'Limit' order type - Order price. - **timeInForce** (string) - Optional - Time in force ('GTC', 'IOC', 'FOK', 'PostOnly'). Defaults to 'GTC'. - **orderLinkId** (string) - Optional - Unique ID to trace an order. ### Request Example (Place Limit Order) ```python # Assuming 'session' is an authenticated Bybit API session object limit_order = session.place_order( category="spot", symbol="BTCUSDT", side="Buy", orderType="Limit", qty="0.001", price="35000", timeInForce="GTC", orderLinkId="sdk-order-001" ) ``` ### Request Example (Place Market Order) ```python market_order = session.place_order( category="spot", symbol="BTCUSDT", side="Buy", orderType="Market", qty="0.001" ) ``` ### Request Example (Cancel Order) ```python # 'limit_order' is the response from placing a limit order cancel_result = session.cancel_order( category="spot", symbol="BTCUSDT", orderId=limit_order["result"]["orderId"] ) ``` ### Request Example (Get Open Orders) ```python open_orders = session.get_open_orders( category="spot", symbol="BTCUSDT" ) print(f"Open orders: {len(open_orders['result']['list'])}") ``` ### Response (Place Order) #### Success Response (200) - **result** (object) - **orderId** (string) - The unique identifier for the placed order. - **orderLinkId** (string) - User-defined order ID if provided. - **createdTime** (integer) - Timestamp of order creation. ### Response Example (Place Order) ```json { "retCode": 0, "retMsg": "OK", "result": { "orderId": "1234567890", "orderLinkId": "sdk-order-001", "createdTime": 1678886400000 } } ``` ### Response (Cancel Order) #### Success Response (200) - **result** (object) - **orderId** (string) - The ID of the cancelled order. ### Response Example (Cancel Order) ```json { "retCode": 0, "retMsg": "OK", "result": { "orderId": "1234567890" } } ``` ### Response (Get Open Orders) #### Success Response (200) - **result** (object) - **list** (array) - Array of open order objects. - **orderId** (string) - The unique identifier for the order. - **symbol** (string) - The trading pair. - **side** (string) - Order side ('Buy' or 'Sell'). - **orderType** (string) - Type of order ('Limit', 'Market'). - **qty** (string) - Order quantity. - **price** (string) - Order price. - **orderStatus** (string) - Current status of the order. ### Response Example (Get Open Orders) ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "orderId": "1234567890", "symbol": "BTCUSDT", "side": "Buy", "orderType": "Limit", "qty": "0.001", "price": "35000.00", "orderStatus": "New" } ] } } ``` ``` -------------------------------- ### Get Wallet Balance (JSON Response Example) Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/wallet-balance.md Example JSON response structure for a successful wallet balance query. It includes overall account summary and detailed breakdown per coin, such as equity, wallet balance, and locked funds. ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "accountType": "UNIFIED", "totalEquity": "10.05007099", "totalWalletBalance": "10.05007099", "totalMarginBalance": "10.05007099", "totalAvailableBalance": "10.05007099", "totalPerpUPL": "0", "totalInitialMargin": "0", "totalMaintenanceMargin": "0", "coin": [ { "coin": "USDT", "equity": "10.05007099", "usdValue": "10.05007099", "walletBalance": "10.05007099", "free": "10.05007099", "locked": "0", "borrowAmount": "0", "availableToWithdraw": "10.05007099", "accruedInterest": "0", "totalOrderIM": "0", "totalPositionIM": "0", "unrealisedPnl": "0", "cumRealisedPnl": "0" } ] } ] }, "retExtInfo": {}, "time": 1672132480085 } ``` -------------------------------- ### Place and Manage Orders with Bybit SDK Source: https://context7.com/suenot/bybit-docs-markdown/llms.txt Demonstrates placing limit and market orders, canceling orders, and retrieving open orders. Requires an active session object and order details. Returns order details or status. ```python # Place limit order limit_order = session.place_order( category="spot", symbol="BTCUSDT", side="Buy", orderType="Limit", qty="0.001", price="35000", timeInForce="GTC", orderLinkId="sdk-order-001" ) # Place market order market_order = session.place_order( category="spot", symbol="BTCUSDT", side="Buy", orderType="Market", qty="0.001" ) # Cancel order cancel_result = session.cancel_order( category="spot", symbol="BTCUSDT", orderId=limit_order["result"]["orderId"] ) # Get open orders open_orders = session.get_open_orders( category="spot", symbol="BTCUSDT" ) print(f"Order placed: {limit_order['result']['orderId']}") print(f"Open orders: {len(open_orders['result']['list'])}") ``` -------------------------------- ### HTTP GET Request for Options Positions Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/options/account/positions.md Example of an HTTP GET request to retrieve options positions for a specific base coin. It includes necessary headers for API authentication and specifies the endpoint and parameters. ```http GET /v5/option/position/list?category=option&baseCoin=BTC HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### Monitoring Tools (API & WebSocket) Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/copy-trading/get-started.md Integrate API and WebSocket streams to monitor real-time performance, position status, P&L, and risk exposure. ```APIDOC ## GET /api/v5/position/list ### Description Retrieve a list of current positions. ### Method GET ### Endpoint /api/v5/position/list ### Parameters #### Query Parameters - **api_key** (string) - Required - Your API key. - **sign** (string) - Required - Signature of the request. - **timestamp** (integer) - Required - Current Unix timestamp. - **symbol** (string) - Optional - Trading pair. ### Request Example ```json { "api_key": "YOUR_API_KEY", "sign": "YOUR_SIGNATURE", "timestamp": 1677420000000, "symbol": "BTCUSD" } ``` ### Response #### Success Response (200) - **retCode** (integer) - Return code. - **retMsg** (string) - Return message. - **result** (object) - Response body. - **list** (array) - List of positions. - **symbol** (string) - Trading pair. - **side** (string) - Position side (Buy or Sell). - **size** (string) - Position size. - **positionValue** (string) - Position value. - **unrealisedPnl** (string) - Unrealized Profit and Loss. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "symbol": "BTCUSD", "side": "Buy", "size": "0.001", "positionValue": "30.5", "unrealisedPnl": "0.5" } ] } } ``` ``` ```APIDOC ## GET /api/v5/trade/closed-pnl ### Description Retrieve historical closed Profit and Loss records. ### Method GET ### Endpoint /api/v5/trade/closed-pnl ### Parameters #### Query Parameters - **api_key** (string) - Required - Your API key. - **sign** (string) - Required - Signature of the request. - **timestamp** (integer) - Required - Current Unix timestamp. - **symbol** (string) - Optional - Trading pair. - **startTime** (integer) - Optional - Start time in Unix timestamp format. - **endTime** (integer) - Optional - End time in Unix timestamp format. - **limit** (integer) - Optional - Limit for data retrieval, default is 20. - **cursor** (string) - Optional - Pagination cursor. ### Request Example ```json { "api_key": "YOUR_API_KEY", "sign": "YOUR_SIGNATURE", "timestamp": 1677420000000, "symbol": "BTCUSD", "limit": 10 } ``` ### Response #### Success Response (200) - **retCode** (integer) - Return code. - **retMsg** (string) - Return message. - **result** (object) - Response body. - **list** (array) - List of closed PnL records. - **symbol** (string) - Trading pair. - **closedPnl** (string) - Closed Profit and Loss. - **side** (string) - Position side. - **qty** (string) - Position quantity. - **avgEntryPrice** (string) - Average entry price. - **avgExitPrice** (string) - Average exit price. - **turnover** (string) - Turnover. - **fee** (string) - Trading fee. - **closedAt** (integer) - Timestamp of when the position was closed. - **nextPageCursor** (string) - Cursor for the next page. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "symbol": "BTCUSD", "closedPnl": "1.5", "side": "Buy", "qty": "0.001", "avgEntryPrice": "30000", "avgExitPrice": "30500", "turnover": "30.5", "fee": "0.01", "closedAt": 1677419000000 } ], "nextPageCursor": "some_cursor_string" } } ``` ``` -------------------------------- ### JSON Response Example for Settlement History Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/options/account/settlement.md Example JSON response from the Bybit API when querying settlement history. It shows the structure of the returned data, including category, settlement list, and pagination cursor. ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "option", "list": [ { "symbol": "BTC-24MAR23-16000-P", "side": "Buy", "size": "1", "sessionAvgPrice": "1000.00", "markPrice": "1100.00", "realisedPnl": "100.00", "createdTime": "1672132480085" } ], "nextPageCursor": "" }, "retExtInfo": {}, "time": 1672132480085 } ``` -------------------------------- ### Client Initialization Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/nodejs.md This section demonstrates how to initialize the Bybit API v5 REST client for different environments (mainnet, testnet) and with various configuration options. ```APIDOC ## Client Initialization ### Description Initialize the Bybit API v5 REST client for mainnet, testnet, or public-only access. Options include API keys, testnet flag, receive window, time synchronization, strict parameter validation, and custom base URLs. ### Method N/A (Constructor) ### Endpoint N/A ### Parameters #### Request Body - **key** (string) - Optional - Your Bybit API key. - **secret** (string) - Optional - Your Bybit API secret. - **testnet** (boolean) - Optional - Set to `true` for testnet, `false` for mainnet. Defaults to `false`. - **recv_window** (number) - Optional - Custom receive window in milliseconds. - **enable_time_sync** (boolean) - Optional - Enable automatic time synchronization. Defaults to `false`. - **strict_param_validation** (boolean) - Optional - Enable strict parameter validation. Defaults to `false`. - **baseUrl** (string) - Optional - Custom base URL for API requests. ### Request Example ```javascript // Mainnet client const client = new RestClientV5({ key: 'YOUR_API_KEY', secret: 'YOUR_API_SECRET', testnet: false, recv_window: 5000, enable_time_sync: true, strict_param_validation: true, baseUrl: 'https://api.bybit.com' }); // Testnet client const testnetClient = new RestClientV5({ key: 'YOUR_API_KEY', secret: 'YOUR_API_SECRET', testnet: true }); // Public-only client const publicClient = new RestClientV5({}); ``` ### Response N/A (Constructor returns a client instance) ``` -------------------------------- ### HTTP Request Example for Margin Info Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/margin/margin-info.md Demonstrates how to make an HTTP GET request to the Bybit API to retrieve spot cross-margin trading data. It includes necessary headers for authentication and request parameters like 'coin' and 'vipLevel'. ```http GET /v5/spot-cross-margin-trade/data?coin=BTC&vipLevel=VIP1 HTTP/1.1 Host: api.bybit.com X-BAPI-SIGN: XXXXX X-BAPI-API-KEY: XXXXX X-BAPI-TIMESTAMP: 1672132480085 X-BAPI-RECV-WINDOW: 5000 ``` -------------------------------- ### JSON Response Example for Transaction Log Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/spot/account/transaction-log.md Example JSON response from the Bybit API when querying transaction logs. It showcases the structure of the result, including the list of transactions, details for each transaction, and a cursor for pagination. This helps in parsing and understanding the data received. ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "id": "592324_USDT_1672132500", "symbol": "BTCUSDT", "category": "spot", "side": "Buy", "transactionTime": "1672132500000", "type": "TRADE", "qty": "0.001", "size": "0.001", "currency": "USDT", "tradePrice": "16600", "funding": "0", "fee": "0.00001", "cashFlow": "-16.6", "change": "-16.60001", "cashBalance": "983.39999", "feeRate": "0.001", "bonusChange": "0", "tradeId": "592324", "orderId": "1523445134", "orderLinkId": "test-001" } ], "nextPageCursor": "592324_USDT_1672132500" }, "retExtInfo": {}, "time": 1672132480085 } ``` -------------------------------- ### Go: Fetch Market Data using Bybit SDK Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/sdk/go.md Provides examples for fetching market data using the Bybit Go SDK. Includes retrieving instrument information, order book depth, and kline (candlestick) data. Requires an initialized Bybit HTTP client and relevant parameters. ```go import ( "context" "fmt" "log" "time" "github.com/bybit-exchange/bybit.go.api" ) func main() { // Assume 'client' is an initialized BybitHttpClient // client := bybit.NewBybitHttpClient(...) // Get instruments info paramsInstruments := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", } resultInstruments, err := client.NewMarketDataService(). GetInstrumentsInfo(context.Background(), paramsInstruments) if err != nil { log.Printf("Error getting instruments info: %v", err) return } fmt.Println("Instruments Info:", bybit.PrettyPrint(resultInstruments)) // Get orderbook (depth: 1-200) paramsOrderbook := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", "limit": 25, // Default 25, max 200 } resultOrderbook, err := client.NewMarketDataService(). GetOrderbook(context.Background(), paramsOrderbook) if err != nil { log.Printf("Error getting orderbook: %v", err) return } fmt.Println("Orderbook:", bybit.PrettyPrint(resultOrderbook)) // Get kline/candlestick data paramsKline := map[string]interface{}{ "category": "spot", "symbol": "BTCUSDT", "interval": "D", // Available: 1,3,5,15,30,60,120,240,360,720,D,M,W "limit": 200, // Default 200, max 1000 "start": time.Now().Add(-24*time.Hour).UnixMilli(), } resultKline, err := client.NewMarketDataService(). GetKline(context.Background(), paramsKline) if err != nil { log.Printf("Error getting kline data: %v", err) return } fmt.Println("Kline Data:", bybit.PrettyPrint(resultKline)) } ``` -------------------------------- ### Signature Generation (Python Example) Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/authentication.md This Python code demonstrates how to generate the HMAC SHA256 signature required for authenticated REST API requests. ```APIDOC ## Signature Generation The signature is generated using HMAC SHA256: 1. Create timestamp string (milliseconds) 2. Create parameter string: - For GET requests: Concatenate timestamp + API key + recv_window + query string - For POST requests: Concatenate timestamp + API key + recv_window + request body 3. Sort query parameters alphabetically for GET requests 4. Sign the parameter string using HMAC SHA256 with your API secret Example Python code: ```python import hmac import hashlib import time import json import requests from urllib.parse import urlencode def generate_signature(api_key, api_secret, recv_window, method, params=None): """ Generate signature for API request :param api_key: Your API key :param api_secret: Your API secret :param recv_window: Request valid time window :param method: HTTP method (GET or POST) :param params: Request parameters :return: Dict with authentication headers """ timestamp = str(int(time.time() * 1000)) param_str = "" if method == "GET": if params: param_str = urlencode(sorted(params.items())) else: # POST if params: param_str = json.dumps(params) sign_str = timestamp + api_key + str(recv_window) + param_str signature = hmac.new( bytes(api_secret, "utf-8"), bytes(sign_str, "utf-8"), hashlib.sha256 ).hexdigest() return { "X-BAPI-API-KEY": api_key, "X-BAPI-SIGN": signature, "X-BAPI-SIGN-TYPE": "2", "X-BAPI-TIMESTAMP": timestamp, "X-BAPI-RECV-WINDOW": str(recv_window) } # Example GET request def get_wallet_balance(api_key, api_secret): endpoint = "https://api.bybit.com/v5/account/wallet-balance" params = {"accountType": "UNIFIED"} headers = generate_signature( api_key=api_key, api_secret=api_secret, recv_window=5000, method="GET", params=params ) response = requests.get( endpoint, headers=headers, params=params ) return response.json() # Example POST request def place_order(api_key, api_secret, order_params): endpoint = "https://api.bybit.com/v5/order/create" headers = generate_signature( api_key=api_key, api_secret=api_secret, recv_window=5000, method="POST", params=order_params ) headers["Content-Type"] = "application/json" response = requests.post( endpoint, headers=headers, json=order_params ) return response.json() ``` ``` -------------------------------- ### Bybit V5 Account Info JSON Response Example Source: https://github.com/suenot/bybit-docs-markdown/blob/main/docs/options/account/account-info.md Example JSON response from the Bybit V5 API endpoint for account information. It shows the structure of the returned data, including status codes, messages, and detailed account metrics such as unified margin status, margin mode, equity, balances, PnL, and specific coin details. ```json { "retCode": 0, "retMsg": "OK", "result": { "unifiedMarginStatus": 3, "marginMode": "PORTFOLIO_MARGIN", "optionsEnabled": true, "totalEquity": "1000.00", "totalWalletBalance": "980.00", "totalUnrealizedProfit": "20.00", "totalPnl": "120.00", "totalMaintenanceMargin": "50.00", "totalInitialMargin": "100.00", "totalAvailableBalance": "880.00", "baseCoin": [ { "coin": "BTC", "equity": "1.00", "usdValue": "40000.00", "walletBalance": "0.98", "unrealizedPnl": "0.02", "realizedPnl": "0.10", "cumRealisedPnl": "1.50", "marginBalance": "1.00", "availableBalance": "0.88", "marginRate": "0.1", "maintenanceMargin": "0.05", "initialMargin": "0.10" } ] }, "retExtInfo": {}, "time": 1672132480085 } ```