### API Best Practices and Getting Started Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/introduction.md Recommended practices for using the OKX API securely and efficiently, along with a step-by-step guide to getting started with API integration. ```APIDOC ## Best Practices 1. Always use secure API key storage. 2. Implement rate limiting on your side. 3. Use WebSocket for real-time data. 4. Handle errors gracefully. 5. Keep track of your API key permissions. ## Getting Started 1. Create an OKX account. 2. Generate API keys. 3. Set up authentication. 4. Test in demo environment. 5. Move to production. ``` -------------------------------- ### Example Authenticated Request Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/authentication.md A Python example demonstrating how to construct and send an authenticated GET request to the `/api/v5/account/balance` endpoint. ```APIDOC ## Example Request This example shows how to make an authenticated GET request to the `/api/v5/account/balance` endpoint. ### Method GET ### Endpoint `/api/v5/account/balance` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```python import requests import time from datetime import datetime import hmac import base64 # API credentials api_key = "YOUR-API-KEY" secret_key = "YOUR-SECRET-KEY" passphrase = "YOUR-PASSPHRASE" def sign(timestamp, method, request_path, body, secret_key): message = timestamp + method + request_path + body mac = hmac.new( bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256' ) d = mac.digest() return base64.b64encode(d).decode() # Request details timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z' method = 'GET' request_path = '/api/v5/account/balance' body = '' # Generate signature signature = sign(timestamp, method, request_path, body, secret_key) # Headers headers = { 'OK-ACCESS-KEY': api_key, 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': passphrase } # Make request url = 'https://www.okx.com' + request_path response = requests.get(url, headers=headers) print(response.json()) ``` ### Response #### Success Response (200) - **code** (string) - "0" indicates success. - **data** (array) - An array of account balance objects. #### Response Example ```json { "code": "0", "data": [ { "adjEq": "100.5", "availEq": "100.5", "accountType": "6", "totalEq": "100.5", "isoEq": "100.5", "usdEq": "100.5" } ] } ``` ``` -------------------------------- ### OKX PHP SDK WebSocket Server Setup Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/php.md Demonstrates how to configure and start a WebSocket server using the OKX PHP SDK for receiving real-time data. It includes options for logging, server address, heartbeat, and data refresh intervals. ```php config([ // Включить логирование 'log' => true, // Адрес и порт демона (по умолчанию 0.0.0.0:2207) 'global' => '127.0.0.1:2207', // Время сердцебиения (по умолчанию 20 секунд) 'ping_time' => 20, // Время мониторинга подписок (по умолчанию 2 секунды) 'listen_time' => 2, // Время обновления данных (по умолчанию 0.1 секунды) 'data_time' => 0.1, // Размер очереди сообщений (по умолчанию 100) 'queue_count' => 100, ]); // Запуск сервера $okex->start(); ``` -------------------------------- ### Example Authenticated GET Request (Python) Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/authentication.md This Python script demonstrates how to make an authenticated GET request to the OKX API. It includes generating the current timestamp, constructing the request path and body, signing the request using the provided `sign` function, and setting the necessary authentication headers. ```python import requests import time from datetime import datetime # Assume sign function is defined as above def sign(timestamp, method, request_path, body, secret_key): message = timestamp + method + request_path + body mac = hmac.new( bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256' ) d = mac.digest() return base64.b64encode(d).decode() # API credentials api_key = "YOUR-API-KEY" secret_key = "YOUR-SECRET-KEY" passphrase = "YOUR-PASSPHRASE" # Request details timestamp = datetime.utcnow().isoformat()[:-3] + 'Z' method = 'GET' request_path = '/api/v5/account/balance' body = '' # Generate signature signature = sign(timestamp, method, request_path, body, secret_key) # Headers headers = { 'OK-ACCESS-KEY': api_key, 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': passphrase } # Make request url = 'https://www.okx.com' + request_path response = requests.get(url, headers=headers) print(response.json()) ``` -------------------------------- ### Install OKX PHP SDK Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/php.md Installs the OKX PHP SDK using Composer. This is the primary method for adding the SDK to your PHP project, ensuring all dependencies are managed correctly. ```bash composer require lin/okex ``` -------------------------------- ### Start OKXPublicWebSocketClient - Python Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/trading/ws-public.md Demonstrates how to instantiate and start the OKXPublicWebSocketClient asynchronously. It requires the asyncio library for running asynchronous operations and assumes the client is defined elsewhere. ```python import asyncio # Assume OKXPublicWebSocketClient is defined elsewhere # from okx_websocket import OKXPublicWebSocketClient async def main(): client = OKXPublicWebSocketClient() await client.start() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install OKX Python SDK Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/python.md Installs the official OKX Python SDK using pip. Requires Python version 3.9 or higher and websockets version 6.0 or higher for WebSocket functionality. ```bash pip install python-okx ``` -------------------------------- ### Create API Key Response Example - JSON Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/broker/dma.md Example JSON response after successfully creating an API key for a sub-account, including key details and permissions. ```json { "code": "0", "msg": "", "data": [ { "subAcct": "sub-account-1", "label": "api-key-1", "apiKey": "0123456789ABCDEF", "secretKey": "0123456789ABCDEF0123456789ABCDEF", "passphrase": "passphrase123", "perm": "read_only,trade", "ip": "1.2.3.4", "ts": "1597026383085" } ] } ``` -------------------------------- ### Asset Currencies API Example Source: https://github.com/suenot/okx-docs-markdown/blob/main/repos/website/broker.html Example of how to call the OKX OpenAPI endpoint for retrieving currency information using an access token. ```APIDOC ## GET /api/v5/asset/currencies ### Description Retrieves a list of supported currencies on the OKX platform. ### Method GET ### Endpoint https://www.okx.com/api/v5/asset/currencies ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication. Example: "Bearer eyJhbGciOiJIUzUxMiIsImNpZCI6ImFhIn0.eyJqdGkiOiJleDExMDE2Mzg4NDM3ODg1MzIxMzMzNUVGMkVGRTNGOUM2Y1BJWiIsInVpZCI6IlEybEZxMnY2N0VybnVMZ0o1cFYzdUE9PSIsIm1pZCI6InFGbG5lVEc4dnlJeDNMSnNSa29qZ0E9PSIsImlhdCI6MTYzODg0Mzc4OCwiZXhwIjoxNjM4ODQ3Mzg4LCJzdWIiOiIxMC4yNTQuMjcuMTIwIiwiYW95IjoiOSIsInZlciI6IjEiLCJkZXYiOiIzMmNmOWM2My02NzM3LTRhYjUtYjFhYi04ODU4YWU2NTkxODUiLCJndHkiOiJhdXRob3JpemUifQ.bWXsgN7hTszxmdFB9xhr0Qh67HQWIp2zoxoqMCUzw2y1MBFPm38nNJJY9coljkivgAQPso81YUnHoLsFOLjxGg" - **TERMID** (string) - Conditional - Device ID for client device initiated requests. ### Request Example ```bash curl -H "Content-Type:application/json" \ -H "Authorization:Bearer eyJhbGciOiJIUzUxMiIsImNpZCI6ImFhIn0.eyJqdGkiOiJleDExMDE2Mzg4NDM3ODg1MzIxMzMzNUVGMkVGRTNGOUM2Y1BJWiIsInVpZCI6IlEybEZxMnY2N0VybnVMZ0o1cFYzdUE9PSIsIm1pZCI6InFGbG5lVEc4dnlJeDNMSnNSa29qZ0E9PSIsImlhdCI6MTYzODg0Mzc4OCwiZXhwIjoxNjM4ODQ3Mzg4LCJzdWIiOiIxMC4yNTQuMjcuMTIwIiwiYW95IjoiOSIsInZlciI6IjEiLCJkZXYiOiIzMmNmOWM2My02NzM3LTRhYjUtYjFhYi04ODU4YWU2NTkxODUiLCJndHkiOiJhdXRob3JpemUifQ.bWXsgN7hTszxmdFB9xhr0Qh67HQWIp2zoxoqMCUzw2y1MBFPm38nNJJY9coljkivgAQPso81YUnHoLsFOLjxGg" \ -H "TERMID:32cf9c63-6737-4ab5-b1ab-8858ae659185" \ https://www.okx.com/api/v5/asset/currencies ``` ### Response #### Success Response (200) - **code** (string) - "0" for success - **data** (array) - List of currency objects - **currency** (string) - Currency symbol - **name** (string) - Full currency name - **chain** (string) - Blockchain network - **enableDeposit** (boolean) - Whether deposit is enabled - **enableWithdraw** (boolean) - Whether withdrawal is enabled - **minDeposit** (string) - Minimum deposit amount - **maxWithdraw** (string) - Maximum withdrawal amount - **prettyWithdrawType** (string) - Withdrawal type display - **areaPreferential** (boolean) - Whether the area is preferential - **isTop** (boolean) - Whether it is a top currency - **fundTransferLimit** (string) - Fund transfer limit - **currencyUnitInt** (string) - Integer part of currency unit - **currencyUnitDecimal** (string) - Decimal part of currency unit - **currencyUnitScale** (string) - Scale of currency unit - **withdrawMinType** (string) - Type of minimum withdrawal - **chainDeposit** (boolean) - Whether chain deposit is enabled - **chainWithdraw** (boolean) - Whether chain withdrawal is enabled - **supportSubAccounts** (boolean) - Whether sub-accounts are supported - **contractUnitInt** (string) - Integer part of contract unit - **contractUnitDecimal** (string) - Decimal part of contract unit - **contractUnitScale** (string) - Scale of contract unit - **disclaimer** (string) - Disclaimer for the currency - **unit** (string) - Unit of the currency - **depositTip** (string) - Tip for deposit - **withdrawTip** (string) - Tip for withdrawal - **specialTag** (string) - Special tag for the currency - **feeDiscount** (string) - Fee discount for the currency - **buyable** (boolean) - Whether the currency is buyable - **sellable** (boolean) - Whether the currency is sellable - **bankBuyable** (boolean) - Whether bank buy is enabled - **bankSellable** (boolean) - Whether bank sell is enabled - **tokenInfo** (object) - Token information - **contractAddr** (string) - Contract address - **decimals** (string) - Number of decimal places - **symbol** (string) - Token symbol - **assetLogo** (string) - URL for the asset logo - **assetName** (string) - Name of the asset - **fee** (string) - Fee associated with the currency - **minWithdrawalFee** (string) - Minimum withdrawal fee - **maxWithdrawalFee** (string) - Maximum withdrawal fee - **withdrawQuotaDaily** (string) - Daily withdrawal quota - **withdrawQuotaMonthly** (string) - Monthly withdrawal quota - **withdrawQuotaDailyRemaining** (string) - Remaining daily withdrawal quota - **withdrawQuotaMonthlyRemaining** (string) - Remaining monthly withdrawal quota - **withdrawQuotaDailyLeft** (string) - Daily withdrawal quota left - **withdrawQuotaMonthlyLeft** (string) - Monthly withdrawal quota left - **withdrawQuotaDailyUsed** (string) - Daily withdrawal quota used - **withdrawQuotaMonthlyUsed** (string) - Monthly withdrawal quota used - **withdrawRemark** (string) - Remark for withdrawal - **depositRemark** (string) - Remark for deposit - **precision** (string) - Precision for the currency - **depositTipDetail** (string) - Detailed tip for deposit - **withdrawTipDetail** (string) - Detailed tip for withdrawal - **hideDeposit** (boolean) - Whether to hide deposit - **hideWithdraw** (boolean) - Whether to hide withdrawal - **depositEnableTime** (string) - Time when deposit was enabled - **withdrawEnableTime** (string) - Time when withdrawal was enabled - **depositUnit** (string) - Deposit unit - **withdrawUnit** (string) - Withdrawal unit - **depositMinUnit** (string) - Minimum deposit unit - **withdrawMaxUnit** (string) - Maximum withdrawal unit - **depositTag** (string) - Deposit tag - **withdrawTag** (string) - Withdrawal tag - **depositAddressUrl** (string) - Deposit address URL - **withdrawAddressUrl** (string) - Withdrawal address URL - **depositNetworkList** (array) - List of deposit networks - **chain** (string) - Blockchain network - **depositRule** (string) - Deposit rule - **depositTip** (string) - Tip for deposit - **depositMinAmount** (string) - Minimum deposit amount - **depositMaxAmount** (string) - Maximum deposit amount - **depositRemark** (string) - Remark for deposit - **depositTag** (string) - Deposit tag - **depositEnable** (boolean) - Whether deposit is enabled - **depositMemo** (string) - Deposit memo - **depositMinFee** (string) - Minimum deposit fee - **depositMaxFee** (string) - Maximum deposit fee - **depositFeeRate** (string) - Deposit fee rate - **depositCharge** (string) - Deposit charge - **depositChargeRate** (string) - Deposit charge rate - **depositInfo** (string) - Deposit info - **withdrawNetworkList** (array) - List of withdrawal networks - **chain** (string) - Blockchain network - **withdrawRule** (string) - Withdrawal rule - **withdrawTip** (string) - Tip for withdrawal - **withdrawMinAmount** (string) - Minimum withdrawal amount - **withdrawMaxAmount** (string) - Maximum withdrawal amount - **withdrawRemark** (string) - Remark for withdrawal - **withdrawTag** (string) - Withdrawal tag - **withdrawEnable** (boolean) - Whether withdrawal is enabled - **withdrawMemo** (string) - Withdrawal memo - **withdrawMinFee** (string) - Minimum withdrawal fee - **withdrawMaxFee** (string) - Maximum withdrawal fee - **withdrawFeeRate** (string) - Withdrawal fee rate - **withdrawCharge** (string) - Withdrawal charge - **withdrawChargeRate** (string) - Withdrawal charge rate - **withdrawInfo** (string) - Withdrawal info - **withdrawQuotaDaily** (string) - Daily withdrawal quota - **withdrawQuotaMonthly** (string) - Monthly withdrawal quota - **withdrawQuotaDailyRemaining** (string) - Remaining daily withdrawal quota - **withdrawQuotaMonthlyRemaining** (string) - Remaining monthly withdrawal quota - **withdrawQuotaDailyLeft** (string) - Daily withdrawal quota left - **withdrawQuotaMonthlyLeft** (string) - Monthly withdrawal quota left - **withdrawQuotaDailyUsed** (string) - Daily withdrawal quota used - **withdrawQuotaMonthlyUsed** (string) - Monthly withdrawal quota used #### Response Example ```json { "code": "0", "data": [ { "currency": "BTC", "name": "Bitcoin", "chain": "BTC", "enableDeposit": true, "enableWithdraw": true, "minDeposit": "0.00001", "maxWithdraw": "100", "prettyWithdrawType": "0.00001", "areaPreferential": false, "isTop": true, "fundTransferLimit": "100", "currencyUnitInt": "1", "currencyUnitDecimal": "0", "currencyUnitScale": "", "withdrawMinType": "0.00001", "chainDeposit": true, "chainWithdraw": true, "supportSubAccounts": true, "contractUnitInt": "1", "contractUnitDecimal": "0", "contractUnitScale": "", "disclaimer": "", "unit": "BTC", "depositTip": "", "withdrawTip": "", "specialTag": "", "feeDiscount": "", "buyable": true, "sellable": true, "bankBuyable": false, "bankSellable": false, "tokenInfo": { "contractAddr": "", "decimals": "", "symbol": "" }, "assetLogo": "https://okx.com/cdn/logo/btc.png", "assetName": "BTC", "fee": "0.0005", "minWithdrawalFee": "0.00001", "maxWithdrawalFee": "0.0005", "withdrawQuotaDaily": "100", "withdrawQuotaMonthly": "1000", "withdrawQuotaDailyRemaining": "100", "withdrawQuotaMonthlyRemaining": "1000", "withdrawQuotaDailyLeft": "100", "withdrawQuotaMonthlyLeft": "1000", "withdrawQuotaDailyUsed": "0", "withdrawQuotaMonthlyUsed": "0", "withdrawRemark": "", "depositRemark": "", "precision": "8", "depositTipDetail": "", "withdrawTipDetail": "", "hideDeposit": false, "hideWithdraw": false, "depositEnableTime": "", "withdrawEnableTime": "", "depositUnit": "BTC", "withdrawUnit": "BTC", "depositMinUnit": "0.00001", "withdrawMaxUnit": "100", "depositTag": "", "withdrawTag": "", "depositAddressUrl": "", "withdrawAddressUrl": "", "depositNetworkList": [ { "chain": "BTC", "depositRule": "", "depositTip": "", "depositMinAmount": "0.00001", "depositMaxAmount": "100", "depositRemark": "", "depositTag": "", "depositEnable": true, "depositMemo": "", "depositMinFee": "0.00001", "depositMaxFee": "0.0005", "depositFeeRate": "0.0005", "depositCharge": "", "depositChargeRate": "", "depositInfo": "" } ], "withdrawNetworkList": [ { "chain": "BTC", "withdrawRule": "", "withdrawTip": "", "withdrawMinAmount": "0.00001", "withdrawMaxAmount": "100", "withdrawRemark": "", "withdrawTag": "", "withdrawEnable": true, "withdrawMemo": "", "withdrawMinFee": "0.00001", "withdrawMaxFee": "0.0005", "withdrawFeeRate": "0.0005", "withdrawCharge": "", "withdrawChargeRate": "", "withdrawInfo": "", "withdrawQuotaDaily": "100", "withdrawQuotaMonthly": "1000", "withdrawQuotaDailyRemaining": "100", "withdrawQuotaMonthlyRemaining": "1000", "withdrawQuotaDailyLeft": "100", "withdrawQuotaMonthlyLeft": "1000", "withdrawQuotaDailyUsed": "0", "withdrawQuotaMonthlyUsed": "0" } ] } ] } ``` ``` -------------------------------- ### Python SDK Account Operations Examples Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/python.md Provides Python code examples for common account operations using the OKX SDK, including retrieving account balances, positions, and transaction history. ```python # Получение баланса аккаунта result = accountAPI.get_account_balance() print(result) # Получение позиций result = accountAPI.get_positions() print(result) # Получение истории транзакций result = accountAPI.get_account_bills() print(result) ``` -------------------------------- ### Python SDK Market Data Examples Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/python.md Shows examples of fetching market data using the OKX Python SDK, including retrieving tickers, order books, and historical candlestick data. Requires a configured marketDataAPI client. ```python # Получение тикера result = marketDataAPI.get_ticker( instId="BTC-USDT" ) print(result) # Получение книги ордеров result = marketDataAPI.get_orderbook( instId="BTC-USDT", sz="20" ) print(result) # Получение исторических свечей result = marketDataAPI.get_candlesticks( instId="BTC-USDT", bar="1D" ) print(result) ``` -------------------------------- ### Query API Key Response Example - JSON Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/broker/dma.md Example JSON response for the 'Query Sub-account API Key' endpoint, showing details of a queried API key. ```json { "code": "0", "msg": "", "data": [ { "subAcct": "sub-account-1", "label": "api-key-1", "apiKey": "0123456789ABCDEF", "perm": "read_only,trade", "ip": "1.2.3.4", "ts": "1597026383085" } ] } ``` -------------------------------- ### OKX WebSocket Account Channel Push Data Example Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/trading/ws-private.md An example of the data structure received when subscribed to the 'account' channel on the OKX WebSocket API. This data provides details about account equity, margin information, and specific currency balances. ```json { "arg": { "channel": "account", "ccy": "BTC" }, "data": [{ "uTime": "1597026383085", "totalEq": "41624.92", "isoEq": "3624.92", "adjEq": "41624.92", "ordFroz": "0", "imr": "4162.49", "mmr": "3329.99", "notionalUsd": "", "mgnRatio": "41.624924", "details": [{ "ccy": "BTC", "eq": "1.23", "cashBal": "1.23", "uTime": "1597026383085", "isoEq": "0", "availEq": "1.23", "disEq": "1.23", "availBal": "1.23", "frozenBal": "0", "ordFrozen": "0", "liab": "0", "upl": "0", "uplLiab": "0", "crossLiab": "0", "isoLiab": "0", "mgnRatio": "", "interest": "0", "twap": "0", "maxLoan": "", "eqUsd": "41624.92", "notionalLever": "0" }] }] } ``` -------------------------------- ### Basic OKX PHP SDK Setup Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/php.md Demonstrates how to initialize the OKX PHP SDK client for both live trading and the testnet environment. Requires API keys and passphrase for authenticated access. ```php config([ 'log' => true, ]); // Подписка на публичные каналы $okex->subscribe([ ["channel" => "tickers", "instId" => "BTC-USDT"], ["channel" => "books", "instId" => "BTC-USDT"], ["channel" => "candle5m", "instId" => "BTC-USDT"], ]); // Подписка на приватные каналы $okex->keysecret([ 'key' => 'your-api-key', 'secret' => 'your-secret-key', 'passphrase' => 'your-passphrase', ]); $okex->subscribe([ // Публичные каналы ["channel" => "tickers", "instId" => "BTC-USDT"], ["channel" => "books", "instId" => "BTC-USDT"], // Приватные каналы ["channel" => "account", "ccy" => "BTC"], ["channel" => "positions", "instType" => "FUTURES"], ["channel" => "orders", "instType" => "SPOT"], ]); // Получение данных while(true) { $data = $okex->getSubscribe(); print_r($data); sleep(1); } ``` -------------------------------- ### Sub-account List Response Example - JSON Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/broker/dma.md Example JSON response structure for the 'Get Sub-account List' endpoint, showing details of a sub-account. ```json { "code": "0", "msg": "", "data": [ { "subAcct": "sub-account-1", "label": "test", "acctLv": "1", "uid": "123456789", "ts": "1597026383085" } ] } ``` -------------------------------- ### Sub-account Fee Rates Response Example - JSON Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/broker/dma.md Example JSON response for the 'Get Sub-account Fee Rates' endpoint, detailing taker and maker fees for a specific instrument type. ```json { "code": "0", "msg": "", "data": [ { "subAcct": "sub-account-1", "instType": "SPOT", "taker": "0.0015", "maker": "0.001", "ts": "1597026383085" } ] } ``` -------------------------------- ### Get Sub-Account Fee Rates Response Example Source: https://github.com/suenot/okx-docs-markdown/blob/main/repos/website/broker.html This example shows the structure of a successful response from the OKX API when requesting sub-account trading fee rates. It includes pagination details, a list of sub-accounts, and their respective fee rates categorized by type. ```json { "code": "0", "data": [ { "details": [ { "feeRates": [ { "marker": "-0.0008", "taker": "-0.001", "type": "1" }, { "marker": "-0.0005", "taker": "-0.0007", "type": "2" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "3" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "4" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "5" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "6" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "7" }, { "marker": "-0.0002", "taker": "-0.0005", "type": "8" }, { "marker": "-0.0002", "taker": "-0.0003", "type": "9" } ], "mainAcct": "", "subAcct": "subaccount111ad", "ts": "1658287703000", "uid": "335748406955877155" } ], "page": "1", "totalPage": "1" } ], "msg": "" } ``` -------------------------------- ### Broker Program Overview Source: https://github.com/suenot/okx-docs-markdown/blob/main/repos/website/broker.html Information on joining the OKX Broker Program to offer cryptocurrency services and earn rebates. ```APIDOC ## Broker Program ### Description If your business platform offers cryptocurrency services, you can apply to join the OKX Broker Program, become our partner broker, enjoy exclusive broker services, and earn high rebates through trading fees generated by OKX users. ### How to Apply [Details on application process would go here, if available in the source text] ``` -------------------------------- ### Python SDK Public WebSocket Example Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/python.md Demonstrates how to connect to and subscribe to public WebSocket channels using the OKX Python SDK. This includes setting up message handlers, subscribing to specific channels like tickers and candles, and maintaining the connection. ```python import asyncio from okx.websocket import PublicWebsocket async def public_ws_example(): # Инициализация WebSocket клиента ws = PublicWebsocket() # Определение callback функции async def on_message(message): print(f"Received message: {message}") # Установка callback ws.on_message = on_message # Подключение к WebSocket await ws.connect() # Подписка на каналы await ws.subscribe([ { "channel": "tickers", "instId": "BTC-USDT" }, { "channel": "candle1m", "instId": "BTC-USDT" } ]) # Держим соединение активным while True: await asyncio.sleep(1) # Запуск WebSocket клиента asyncio.run(public_ws_example()) ``` -------------------------------- ### Account Configuration Source: https://github.com/suenot/okx-docs-markdown/blob/main/repos/website/best_practice.html Manage account settings, including account mode and leverage. ```APIDOC ## Account Configuration ### Description Manage and retrieve account-specific configurations. ### Method GET ### Endpoint `/api/v5/account/config` ### Parameters #### Query Parameters - **ccy** (string) - Optional - Currency ### Response #### Success Response (200) - **code** (string) - API error code - **msg** - API error message - **data** (object) - Account configuration data - **acctNums** (array) - Account numbers - **grandTotalAsset** (string) - Total asset value #### Response Example ```json { "code": "0", "msg": "", "data": { "acctNums": [ { "type": "SPOT", "lever": "0" } ], "grandTotalAsset": "10000.00" } } ``` ``` -------------------------------- ### Initialize OKX V5 REST Client in Java Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/java.md Set up the OkxV5RestClient for both live and demo trading environments. This requires your API key, secret key, and passphrase. Use the 'sandbox(true)' option for the test network. ```java import xyz.felh.okx.client.*; import xyz.felh.okx.model.*; // Создание клиента для live trading OkxV5RestClient client = new OkxV5RestClient.Builder() .apiKey("YOUR-API-KEY") .secretKey("YOUR-SECRET-KEY") .passphrase("YOUR-PASSPHRASE") .build(); // Создание клиента для demo trading OkxV5RestClient testnetClient = new OkxV5RestClient.Builder() .apiKey("YOUR-API-KEY") .secretKey("YOUR-SECRET-KEY") .passphrase("YOUR-PASSPHRASE") .sandbox(true) .build(); ``` -------------------------------- ### Get Withdrawal Payment Methods - HTTP GET Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/funding/withdrawal.md Retrieves the available withdrawal payment methods for a specified currency. Requires the currency (ccy) as a parameter. Returns a list of available payment methods. ```http GET /api/v5/asset/withdrawal-payment-methods # Request Parameters # ccy: String (Required) - Currency ``` -------------------------------- ### Place Order Source: https://github.com/suenot/okx-docs-markdown/blob/main/repos/website/best_practice.html Submit a new order to the trading system. ```APIDOC ## Place Order ### Description Submit a new order for trading. ### Method POST ### Endpoint `/api/v5/order` ### Parameters #### Request Body - **instId** (string) - Required - Instrument ID - **tdMode** (string) - Required - Trading mode (CROSS, ISOLATED) - **side** (string) - Required - Order side (buy, sell) - **ordType** (string) - Required - Order type (limit, market, etc.) - **sz** (string) - Required - Order size - **price** (string) - Optional - Order price (required for limit orders) ### Response #### Success Response (200) - **code** (string) - API error code - **msg** - API error message - **data** (array) - Order placement data - **ordId** (string) - Order ID - **clOrdId** (string) - Client Order ID #### Response Example ```json { "code": "0", "msg": "Success", "data": [ { "ordId": "123456789", "clOrdId": "my-order-123" } ] } ``` ``` -------------------------------- ### API Key Creation and Authentication Headers Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/authentication.md This section details how to create an API key on the OKX website and lists the required headers for authenticated API requests. ```APIDOC ## API Key Creation To access private endpoints, you need to create an API key through the OKX website: 1. Log in to your OKX account 2. Navigate to "API Management" 3. Click "Create API Key" 4. Select permissions: Read, Trade, Withdraw 5. Configure IP whitelist (recommended) 6. Save your API credentials: API Key, Secret Key, Passphrase ## Required Headers for Authentication All authenticated endpoints require the following HTTP headers: - **OK-ACCESS-KEY**: Your API key - **OK-ACCESS-SIGN**: Signature - **OK-ACCESS-TIMESTAMP**: UTC timestamp - **OK-ACCESS-PASSPHRASE**: Your API passphrase ### Timestamp Format - Must be in ISO format: YYYY-MM-DDThh:mm:ss.sssZ - Server accepts requests within ±30 seconds of server time. - Use `/api/v5/public/time` to synchronize time. ``` -------------------------------- ### Python SDK Authentication and Client Initialization Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/sdk/python.md Demonstrates how to authenticate with the OKX API using API keys, secret keys, and passphrases. It also shows the initialization of various API clients for account, market data, public data, and trading operations. ```python import okx.Account as Account import okx.MarketData as MarketData import okx.PublicData as PublicData import okx.Trade as Trade import okx.SubAccount as SubAccount import okx.Funding as Funding import okx.SpreadTrading as SpreadTrading import okx.BlockTrading as BlockTrading # Конфигурация для live trading api_key = "YOUR-API-KEY" secret_key = "YOUR-SECRET-KEY" passphrase = "YOUR-PASSPHRASE" flag = "0" # 0: live trading, 1: demo trading # Инициализация клиентов accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag) marketDataAPI = MarketData.MarketDataAPI(api_key, secret_key, passphrase, False, flag) publicDataAPI = PublicData.PublicDataAPI(api_key, secret_key, passphrase, False, flag) tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag) ``` -------------------------------- ### Get Withdrawal History - HTTP GET Source: https://github.com/suenot/okx-docs-markdown/blob/main/docs/funding/withdrawal.md Retrieves the withdrawal history from an OKX account. Supports filtering by currency, withdrawal ID, client ID, transaction ID, type, state, and pagination parameters (after, before, limit). Returns a list of withdrawal records. ```http GET /api/v5/asset/withdrawal-history # Request Parameters # ccy: String (Optional) - Currency, e.g., BTC # wdId: String (Optional) - Withdrawal ID # clientId: String (Optional) - Client-supplied ID # txId: String (Optional) - Hash record of the withdrawal # type: String (Optional) - Withdrawal type (3: internal, 4: on-chain) # state: String (Optional) - Status (-3: canceling, -2: canceled, -1: failed, 0: pending, 1: sending, 2: sent, 3: awaiting email verification, 4: awaiting manual verification, 5: awaiting identity verification) # after: String (Optional) - Pagination of data to return records earlier than the requested wdId # before: String (Optional) - Pagination of data to return records newer than the requested wdId # limit: String (Optional) - Number of results per request, maximum 100, default 100 # Response Example { "code": "0", "msg": "", "data": [ { "ccy": "BTC", "chain": "BTC-Bitcoin", "amt": "0.1", "ts": "1597026383085", "from": "", "to": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh", "txId": "e5ea63a68ab5b8ea676486f36bb46c58639ad6a31cf27f40d1f074109960f6f5", "state": "2", "wdId": "67485", "clientId": "" } ] } ```