### Clone Repository and Install Dependencies Source: https://github.com/okxapi/python-okx/blob/master/README.md Set up the development environment by cloning the repository, navigating into the directory, and installing project dependencies. Then, install the package in editable mode. ```bash # Clone the repository git clone https://github.com/okxapi/python-okx.git cd python-okx # Install dependencies pip install -r requirements.txt pip install -e . ``` -------------------------------- ### Install python-okx Package Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Install or upgrade the python-okx library from PyPi. ```python ! pip install python-okx --upgrade ``` -------------------------------- ### Install python-okx Source: https://github.com/okxapi/python-okx/blob/master/README.md Install the library using pip. Ensure you have Python version 3.7 or higher. ```bash pip install python-okx ``` -------------------------------- ### Get System Time Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the current system time from the OKX servers. ```python ts = publicAPI.get_system_time() ``` -------------------------------- ### Get Account Configuration Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve the current account configuration. Requires authentication. ```python # --- Account configuration --- config = accountAPI.get_account_config() ``` -------------------------------- ### Get Tickers for SWAP Instruments Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Initialize the MarketData API and retrieve ticker information for SWAP instruments. You can change 'SWAP' to 'FUTURES' or 'OPTION' to get data for other derivative types. ```python import okx.MarketData as MarketData flag = "1" # live trading: 0, demo trading: 1 marketDataAPI = MarketData.API(flag = flag) result = marketDataAPI.get_tickers(instType = "SWAP") print(result) ``` -------------------------------- ### Get Index Components Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the components that make up a specific index. ```python marketAPI.get_index_components(index="BTC-USDT") ``` -------------------------------- ### Get order list Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieve a list of current open orders. ```APIDOC ## GET /api/v5/trade/orders-pending ### Description Retrieve a list of current open orders. ### Method GET ### Endpoint /api/v5/trade/orders-pending ### Response #### Success Response (200) - **code** (string) - Response code - **data** (array) - Data object - **ordId** (string) - Order ID #### Response Example ```json { "code": "0", "data": [ { "ordId": "505073046126960640" } ] } ``` ``` -------------------------------- ### Initialize Funding API and Get Currencies Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Initialize the Funding API with your credentials and fetch available currencies. Set the 'flag' to '1' for demo trading or '0' for live trading. ```python import okx.Funding as Funding flag = "1" # live trading:0 , demo trading:1 fundingAPI = Funding.FundingAPI(api_key, secret_key, passphrase, False, flag) result = fundingAPI.get_currencies() print(result) ``` -------------------------------- ### Get AI-Recommended Parameters for Spot Grid Source: https://context7.com/okxapi/python-okx/llms.txt Fetches AI-recommended parameters for a spot grid trading bot. Specify the instrument ID and duration. ```python ai_params = gridAPI.grid_ai_param( algoOrdType="grid", # "grid"=spot, "contract_grid"=futures, "moon_grid" instId="BTC-USDT", direction="", duration="7D" ) ``` -------------------------------- ### Get positions Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieve current position information for the account. ```APIDOC ## GET /api/v5/account/positions ### Description Retrieve current position information for the account. ### Method GET ### Endpoint /api/v5/account/positions ### Response #### Success Response (200) - **code** (string) - Response code - **data** (array) - Data object - **upl** (string) - Unrealized Profit and Loss #### Response Example ```json { "code": "0", "data": [ { "upl": "100.50" } ] } ``` ``` -------------------------------- ### Get Price Limit Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves the maximum and minimum tradable prices for a given instrument. ```python publicAPI.get_price_limit(instId="BTC-USDT-SWAP") ``` -------------------------------- ### Get Public Borrow Rate Summary Source: https://context7.com/okxapi/python-okx/llms.txt Fetches a summary of public borrow rates for a specified currency. ```python # --- Public borrow rate summary --- savingsAPI.get_public_borrow_info(ccy="USDT") ``` -------------------------------- ### Place a Market Order Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Place a market order for a specified instrument ('BTC-USDT') with a given size ('sz'). This example demonstrates a buy order in 'cash' trading mode. It includes error handling for unsuccessful order requests. ```python # market order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="market", sz="0.01" ) print(result) if result["code"] == "0": print("Successful order request,order_id = ",result["data"][0]["ordId"]) else: print("Unsuccessful order request,error_code = ", result["data"][0]["sCode"], ", Error_message = ", result["data"][0]["sMsg"]) ``` -------------------------------- ### Get Account Balance Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Initialize the Account API and retrieve your account balance. Ensure the 'flag' is set correctly for live or demo trading. ```python import okx.Account as Account flag = "1" # live trading: 0, demo trading: 1 accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag) result = accountAPI.get_account_balance() print(result) ``` -------------------------------- ### Get all supported currencies Source: https://context7.com/okxapi/python-okx/llms.txt Fetch a list of all currencies supported by the funding API. Can be filtered by a specific currency. ```python currencies = fundingAPI.get_currencies(ccy="BTC") ``` -------------------------------- ### Lightning deposit Source: https://context7.com/okxapi/python-okx/llms.txt Get information for a lightning network deposit. Requires currency and amount. ```python fundingAPI.get_deposit_lightning(ccy="BTC", amt="0.001") ``` -------------------------------- ### API Credentials Placeholder Source: https://github.com/okxapi/python-okx/blob/master/README.md A placeholder for API credentials that need to be filled in before running examples. ```python api_key = "" secret_key = "" passphrase = "" ``` -------------------------------- ### Get Account Balance Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve account balance for a specific currency. Requires authentication. ```python import okx.Account as Account accountAPI = Account.AccountAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1" ) # --- Balance --- result = accountAPI.get_account_balance(ccy="USDT") # {"code":"0","data":[{"adjEq":"","details":[{"availBal":"1000","ccy":"USDT",...}],...}]} ``` -------------------------------- ### Get Option Summary Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves a summary of options expiring on a specific date for a given underlying asset. ```python publicAPI.get_opt_summary(uly="BTC-USD", expTime="20241227") ``` -------------------------------- ### Place a Limit Order Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Place a limit order for a specified instrument ('BTC-USDT') with a given price ('px') and size ('sz'). This example demonstrates a buy order in 'cash' trading mode. It includes error handling for unsuccessful order requests. ```python # limit order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="limit", px="19000", sz="0.01" ) print(result) if result["code"] == "0": print("Successful order request,order_id = ",result["data"][0]["ordId"]) else: print("Unsuccessful order request,error_code = ", result["data"][0]["sCode"], ", Error_message = ", result["data"][0]["sMsg"]) ``` -------------------------------- ### Get Supported Coins for Trading Data Source: https://context7.com/okxapi/python-okx/llms.txt Fetches a list of cryptocurrencies for which trading data analytics are available. ```python tradingDataAPI.get_support_coin() ``` -------------------------------- ### Initialize MarketData API and Get Tickers Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Initialize the MarketData API and fetch ticker information for a specified instrument type, such as 'SPOT'. The 'flag' parameter determines whether to use live ('0') or demo ('1') trading environment. ```python import okx.MarketData as MarketData flag = "1" # live trading: 0, demo trading: 1 marketDataAPI = MarketData.MarketAPI(flag=flag) result = marketDataAPI.get_tickers(instType="SPOT") print(result) ``` -------------------------------- ### Initialize PublicData API and Get Instruments Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Initialize the PublicData API to fetch details about available trading instruments, such as those for 'SPOT' trading. The 'flag' parameter is used to select the trading environment (live or demo). ```python import okx.PublicData as PublicData flag = "1" # live trading: 0, demo trading: 1 PublicDataAPI = PublicData.PublicAPI(flag=flag) result = PublicDataAPI.get_instruments( instType="SPOT" ) print(result) ``` -------------------------------- ### Get order details Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve details for a specific order. Requires instrument ID and order ID. ```python tradeAPI.get_order(instId="BTC-USDT", ordId=ord_id) ``` -------------------------------- ### Get Instruments for SWAP Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Initialize the PublicData API and fetch details for SWAP instruments. This is useful for understanding available trading pairs. The 'flag' parameter distinguishes between live and demo trading. ```python import okx.PublicData as PublicData if __name__ == '__main__': flag = "1" # live trading: 0, demo trading: 1 publicDataAPI = PublicData.PublicAPI(flag = flag) result = publicDataAPI.get_instruments(instType = "SWAP") print(result) ``` -------------------------------- ### Get Funding Rate (Perpetual Swaps) Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the current funding rate for a perpetual swap instrument. Includes the next funding time. ```python funding = publicAPI.get_funding_rate(instId="BTC-USDT-SWAP") ``` -------------------------------- ### Get Open Interest by Expiry Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves open interest data for options, grouped by expiry date, for a specified currency and period. ```python tradingDataAPI.get_interest_volume_expiry(ccy="ETH", period="1D") ``` -------------------------------- ### Get Options Open Interest + Volume Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves open interest and trading volume for options of a specified currency and period. ```python tradingDataAPI.get_options_interest_volume(ccy="BTC", period="8H") ``` -------------------------------- ### Get Options Put/Call Ratio Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the ratio of put options volume to call options volume for a given currency and period. ```python tradingDataAPI.get_put_call_ratio(ccy="BTC", period="1D") ``` -------------------------------- ### Get Open Interest by Strike Source: https://context7.com/okxapi/python-okx/llms.txt Fetches open interest data for options, grouped by strike price, for a specific expiry date, currency, and period. ```python tradingDataAPI.get_interest_volume_strike(ccy="BTC", expTime="20241227", period="8H") ``` -------------------------------- ### Get Open Orders List Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieves a list of all currently open orders for the account. No specific parameters are required. ```python result = tradeAPI.get_order_list() print(result) ``` -------------------------------- ### Get all SPOT tickers Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve a list of all available tickers for spot trading instruments. The 'instType' parameter must be set to 'SPOT'. ```python tickers = marketAPI.get_tickers(instType="SPOT") ``` -------------------------------- ### Get Margin Lending Ratio Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the margin lending ratio for a given currency and period. This indicates the ratio of margin lent to borrowed. ```python tradingDataAPI.get_margin_lending_ratio(ccy="BTC", period="1H") ``` -------------------------------- ### Convert API Operations Source: https://context7.com/okxapi/python-okx/llms.txt This section details the methods for executing instant crypto-to-crypto conversions, including getting quotes and managing currency pairs. ```APIDOC ## get_currencies ### Description Lists all currency pairs that are supported for instant crypto-to-crypto conversions. ### Method GET ### Endpoint /api/v5/convert/currencies ### Request Example ```python currencies = convertAPI.get_currencies() ``` ``` ```APIDOC ## get_currency_pair ### Description Retrieves details for a specific currency conversion pair. ### Method GET ### Endpoint /api/v5/convert/currency-pair ### Parameters #### Query Parameters - **fromCcy** (string) - Required - The currency to convert from (e.g., BTC). - **toCcy** (string) - Required - The currency to convert to (e.g., USDT). ### Request Example ```python pair = convertAPI.get_currency_pair(fromCcy="BTC", toCcy="USDT") ``` ``` ```APIDOC ## estimate_quote ### Description Requests a quote for a crypto-to-crypto conversion based on the specified parameters. ### Method POST ### Endpoint /api/v5/convert/quote ### Parameters #### Request Body - **baseCcy** (string) - Required - The base currency for the quote (e.g., BTC). - **quoteCcy** (string) - Required - The quote currency for the quote (e.g., USDT). - **side** (string) - Required - The side of the conversion ('buy' or 'sell'). - **rfqSz** (string) - Required - The size of the quote request. - **rfqSzCcy** (string) - Required - The currency of the quote size (e.g., BTC). - **clQReqId** (string) - Optional - Client-defined request ID. ### Response #### Success Response (200) - **data** (array) - List of quote details. - **quoteId** (string) - Unique identifier for the quote. - **quotePrice** (string) - The quoted price. - **expiryTime** (string) - Timestamp when the quote expires. ### Request Example ```python quote = convertAPI.estimate_quote( baseCcy="BTC", quoteCcy="USDT", side="sell", rfqSz="0.01", rfqSzCcy="BTC", clQReqId="my_req_001" ) ``` ``` -------------------------------- ### Get Account Configuration and Determine Account Mode Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieve your account configuration to determine the active account mode (Simple, Single-currency margin, Multi-currency margin, or Portfolio margin). Only margin modes support derivatives trading. ```python import okx.Account as Account flag = "1" # live trading: 0, demo trading: 1 accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag) result = accountAPI.get_account_config() print(result) if result['code'] == "0": acctLv = result["data"][0]["acctLv"] if acctLv == "1": print("Simple mode") elif acctLv == "2": print("Single-currency margin mode") elif acctLv == "3": print("Multi-currency margin mode") elif acctLv == "4": print("Portfolio margin mode") ``` -------------------------------- ### Get Contracts Open Interest + Volume Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the open interest and trading volume for contracts of a given currency over a specified period. ```python tradingDataAPI.get_contracts_interest_volume(ccy="BTC", period="1D") ``` -------------------------------- ### Initialize AccountAPI using .env file Source: https://github.com/okxapi/python-okx/blob/master/README.md Load API credentials from a .env file for secure management. Ensure the .env file is in your project root and contains OKX_API_KEY, OKX_API_SECRET, OKX_PASSPHRASE, and optionally OKX_FLAG. ```bash OKX_API_KEY=your-api-key-here OKX_API_SECRET=your-api-secret-here OKX_PASSPHRASE=your-passphrase-here OKX_FLAG=1 ``` ```python import os from dotenv import load_dotenv from okx import Account load_dotenv() account = Account.AccountAPI( api_key=os.getenv('OKX_API_KEY'), api_secret_key=os.getenv('OKX_API_SECRET'), passphrase=os.getenv('OKX_PASSPHRASE'), flag=os.getenv('OKX_FLAG', '1'), debug=False ) ``` -------------------------------- ### WsPrivateAsync Usage Source: https://context7.com/okxapi/python-okx/llms.txt Demonstrates how to initialize `WsPrivateAsync`, subscribe to various private channels (account, orders, positions), and place, amend, and cancel orders via WebSocket. ```APIDOC ## WebSocket — Private Channels — `okx.websocket.WsPrivateAsync` Authenticates and subscribes to private account channels (orders, positions, balance updates) and supports placing/amending/cancelling orders directly over WebSocket for ultra-low latency. ```python import asyncio import json from okx.websocket.WsPrivateAsync import WsPrivateAsync WS_PRIVATE_URL = "wss://ws.okx.com:8443/ws/v5/private" # live WS_PRIVATE_DEMO = "wss://wspap.okx.com:8443/ws/v5/private" # demo def handle_private(msg: str): data = json.loads(msg) print("Private event:", data) async def main(): ws = WsPrivateAsync( apiKey="YOUR_API_KEY", passphrase="YOUR_PASSPHRASE", secretKey="YOUR_SECRET", url=WS_PRIVATE_DEMO, debug=False ) await ws.start() # Subscribe to account balance updates (auto-logins before subscribing) await ws.subscribe( params=[{"channel": "account", "ccy": "USDT"}], callback=handle_private ) # Subscribe to order updates for SPOT await ws.subscribe( params=[{"channel": "orders", "instType": "SPOT", "instId": "BTC-USDT"}], callback=handle_private ) # Subscribe to position updates for SWAP await ws.subscribe( params=[{"channel": "positions", "instType": "SWAP", "instId": "BTC-USDT-SWAP"}], callback=handle_private ) # Place an order over WebSocket (lower latency than REST) await ws.place_order( args=[{ "instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit", "sz": "0.001", "px": "30000" }], callback=handle_private, id="req_001" ) # Amend an order over WebSocket await ws.amend_order( args=[{"instId": "BTC-USDT", "ordId": "123456", "newPx": "31000"}], callback=handle_private ) # Cancel an order over WebSocket await ws.cancel_order( args=[{"instId": "BTC-USDT", "ordId": "123456"}], callback=handle_private ) # Mass cancel by instrument family (business channel) await ws.mass_cancel( args=[{"instType": "OPTION", "instFamily": "BTC-USD"}], callback=handle_private ) await asyncio.sleep(60) await ws.stop() asyncio.run(main()) ``` ``` -------------------------------- ### Initialize AccountAPI with Hardcoded Credentials Source: https://github.com/okxapi/python-okx/blob/master/README.md Instantiate the AccountAPI class with your API key, secret key, and passphrase. Set 'flag' to '1' for demo trading or '0' for live trading. ```python from okx import Account account = Account.AccountAPI( api_key="your-api-key-here", api_secret_key="your-api-secret-key-here", passphrase="your-passphrase-here", flag="1", # 0 = live trading, 1 = demo trading debug=False ) ``` -------------------------------- ### Initialize Funding API Source: https://context7.com/okxapi/python-okx/llms.txt Instantiate the FundingAPI client with your API credentials. The 'flag' parameter can be used for different environments. ```python import okx.Funding as Funding fundingAPI = Funding.FundingAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1" ) ``` -------------------------------- ### Get Past Orders (Last 7 Days/3 Months) Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Fetch historical order data. Use 'get_orders_history' for recent orders (e.g., last 7 days) and 'get_orders_history_archive' for older data (e.g., last 3 months). Specify 'instType' as needed. ```python result = tradeAPI.get_orders_history( instType="SPOT" ) print(result) ``` ```python result = tradeAPI.get_orders_history_archive( instType="SPOT" ) print(result) ``` -------------------------------- ### Initialize Market Data API Source: https://context7.com/okxapi/python-okx/llms.txt Instantiate the MarketAPI client. No API key is needed for public market data endpoints. ```python import okx.MarketData as MarketData marketAPI = MarketData.MarketAPI(flag="0") # no credentials needed ``` -------------------------------- ### Get Greeks Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve Greek values for a specified currency. Requires authentication. ```python greeks = accountAPI.get_greeks(ccy="BTC") ``` -------------------------------- ### Get Details for a Specific Currency Pair Source: https://context7.com/okxapi/python-okx/llms.txt Fetches detailed information for a specific convertible currency pair, specifying the base and quote currencies. ```python pair = convertAPI.get_currency_pair(fromCcy="BTC", toCcy="USDT") ``` -------------------------------- ### Place an algo order (TP/SL on a SWAP) Source: https://context7.com/okxapi/python-okx/llms.txt Place an algorithmic order with take-profit and stop-loss conditions on a swap instrument. Requires instrument ID, trade mode, side, order type, size, and TP/SL trigger prices. ```python tradeAPI.place_algo_order( instId="BTC-USDT-SWAP", tdMode="cross", side="sell", ordType="conditional", sz="1", tpTriggerPx="35000", tpOrdPx="-1", # market price on trigger slTriggerPx="28000", slOrdPx="-1", posSide="long" ) ``` -------------------------------- ### Get Positions History Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve historical positions data. Requires authentication. ```python # --- Positions history --- history = accountAPI.get_positions_history(instType="SWAP", instId="BTC-USDT-SWAP", limit="20") ``` -------------------------------- ### Get Funding account balance Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve the balance for a specific currency in your funding account. Returns available balance, total balance, and frozen balance. ```python balance = fundingAPI.get_balances(ccy="USDT") ``` -------------------------------- ### Asyncio and Websockets Documentation Links Source: https://github.com/okxapi/python-okx/blob/master/README.md Links to external documentation for asyncio, websockets, and related GitHub issues for troubleshooting WebSocketAPI usage. ```python https://docs.python.org/3/library/asyncio-dev.html https://websockets.readthedocs.io/en/stable/intro.html https://github.com/aaugustin/websockets https://github.com/Rapptz/discord.py/issues/1996 https://github.com/aaugustin/websockets/issues/587 ``` -------------------------------- ### ETH Staking API Source: https://context7.com/okxapi/python-okx/llms.txt Interact with ETH staking services to get product information, stake ETH, redeem BETH, check balances, and view history. ```APIDOC ## eth_product_info ### Description Retrieves information about ETH staking products, including rates and minimum staking amounts. ### Method ```python ethAPI.eth_product_info() ``` ### Response Example ```json { "code": "0", "data": [ { "ccy": "ETH", "rate": "0.038", "minStakingAmt": "0.01", ... } ] } ``` ## eth_purchase ### Description Stakes ETH and receives BETH in return. ### Method ```python ethAPI.eth_purchase(amt="0.1") ``` ## eth_redeem ### Description Redeems BETH back into ETH. ### Method ```python ethAPI.eth_redeem(amt="0.05") ``` ## eth_balance ### Description Retrieves the current staked balance of ETH. ### Method ```python ethAPI.eth_balance() ``` ## eth_purchase_redeem_history ### Description Fetches the history of purchase and redeem operations. ### Method ```python ethAPI.eth_purchase_redeem_history(type="purchase", status="success", limit="20") ``` ## eth_apy_history ### Description Retrieves the historical APY data for a specified number of past days. ### Method ```python ethAPI.eth_apy_history(days="30") ``` ### Response Example ```json { "code": "0", "data": [ { "date": "2024-01-01", "apy": "0.038" }, ... ] } ``` ``` -------------------------------- ### Get Open Interest Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves the open interest for a specified instrument type and ID. ```python publicAPI.get_open_interest(instType="SWAP", instId="BTC-USDT-SWAP") ``` -------------------------------- ### Get Positions Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieves current position information for the account. The output varies based on whether the account is in net mode or long/short mode. ```python result = accountAPI.get_positions() print(result) ``` -------------------------------- ### Initialize OKX API Clients Source: https://context7.com/okxapi/python-okx/llms.txt Initialize Trade, Account, and MarketData API clients. Supports hard-coded credentials or loading from a .env file. Use flag="1" for demo and flag="0" for live trading. ```python import os from dotenv import load_dotenv import okx.Trade as Trade import okx.Account as Account import okx.MarketData as MarketData # Option 1: Hard-coded tradeAPI = Trade.TradeAPI( api_key="YOUR_API_KEY", api_secret_key="YOUR_SECRET", passphrase="YOUR_PASSPHRASE", flag="1", # "1" = demo, "0" = live debug=False ) # Option 2: .env file (OKX_API_KEY, OKX_API_SECRET, OKX_PASSPHRASE, OKX_FLAG) load_dotenv() accountAPI = Account.AccountAPI( api_key=os.getenv("OKX_API_KEY"), api_secret_key=os.getenv("OKX_API_SECRET"), passphrase=os.getenv("OKX_PASSPHRASE"), flag=os.getenv("OKX_FLAG", "1"), debug=False ) # Public endpoints require no credentials (pass defaults) marketAPI = MarketData.MarketDataAPI(flag="0") ``` -------------------------------- ### Get order book (depth 20) Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve the order book for a specific instrument, showing bid and ask prices up to a specified depth. Requires instrument ID and size (depth). ```python book = marketAPI.get_orderbook(instId="BTC-USDT", sz="20") ``` -------------------------------- ### Get Fixed-Loan Borrowing Quote Source: https://context7.com/okxapi/python-okx/llms.txt Request a quote for fixed-loan borrowing. Requires authentication. ```python # --- Fixed-loan borrowing --- quote = accountAPI.get_fix_loan_borrowing_quote(type="1", ccy="USDT", amt="1000", term="30D") ``` -------------------------------- ### Get a Conversion Quote (RFQ) Source: https://context7.com/okxapi/python-okx/llms.txt Requests a real-time quote for a crypto-to-crypto conversion. Requires specifying base and quote currencies, side, size, and a unique request ID. ```python quote = convertAPI.estimate_quote( baseCcy="BTC", quoteCcy="USDT", side="sell", rfqSz="0.01", rfqSzCcy="BTC", clQReqId="my_req_001" ) quote_id = quote["data"][0]["quoteId"] ``` -------------------------------- ### Get Interest Accrued Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve accrued interest for margin trading. Requires authentication. ```python # --- Interest accrued --- interest = accountAPI.get_interest_accrued(ccy="USDT", mgnMode="cross") ``` -------------------------------- ### Place a Market Order Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb This snippet demonstrates how to place a market order for a given instrument. It includes parameters for instrument ID, trade mode, side, order type, and size. ```APIDOC ## Place Order ### Description Place an order. ### Method `POST` ### Endpoint `/api/v5/trade/order` ### Parameters #### Query Parameters - **instId** (string) - Required - Instrument ID, e.g., BTC-USDT - **tdMode** (string) - Required - Trading Mode: cash, cross, isolated - **side** (string) - Required - Order side: buy, sell - **ordType** (string) - Required - Order type: market, limit, etc. - **sz** (string) - Required - Size of the order - **tgtCcy** (string) - Optional - Target currency for market orders: quote_ccy or base_ccy - **clOrdId** (string) - Optional - Client-defined order ID ### Request Example ```python # market order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="market", sz="100", ) print(result) ``` ### Request Example with tgtCcy ```python # market order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="market", sz="100", tgtCcy="quote_ccy" # this determines the unit of the sz parameter. base_ccy is the default value ) print(result) ``` ### Request Example with clOrdId ```python # market order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="market", sz="100", clOrdId="003" # you can define your own client defined order ID ) print(result) ``` ``` -------------------------------- ### Proxy Support Source: https://context7.com/okxapi/python-okx/llms.txt Shows how to configure a proxy for API requests by passing a `proxy` parameter to the API class constructor. ```APIDOC ## Proxy Support All API classes accept an optional `proxy` parameter, passed directly to `httpx`. ```python import okx.Trade as Trade tradeAPI = Trade.TradeAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1", proxy="http://127.0.0.1:7890" # HTTP/SOCKS5 proxy URL ) result = tradeAPI.get_order_list(instType="SPOT") ``` ``` -------------------------------- ### Get Past Trades (Last 3 Days/3 Months) Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Retrieve historical trade data. Use 'get_fills' for recent trades (e.g., last 3 days) and 'get_fills_history' for older data (e.g., last 3 months). Specify 'instType' as needed. ```python result = tradeAPI.get_fills( instType="SPOT" ) print(result) ``` ```python result = tradeAPI.get_fills_history( instType="SPOT" ) print(result) ``` -------------------------------- ### Get Conversion History Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves the history of conversion trades, with an option to limit the number of results. ```python history = convertAPI.get_convert_history(limit="20") ``` -------------------------------- ### Run Unit Tests Source: https://github.com/okxapi/python-okx/blob/master/README.md Execute unit tests to verify the functionality of the library during development. ```bash pytest test/unit/ -v ``` -------------------------------- ### Get Mark Price Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the current mark price for a specified instrument type and ID. ```python publicAPI.get_mark_price(instType="SWAP", instId="BTC-USDT-SWAP") ``` -------------------------------- ### Place a limit order (spot) Source: https://context7.com/okxapi/python-okx/llms.txt Use this to place a limit order on the spot market. Requires instrument ID, trade mode, side, order type, size, and price. ```python result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="limit", sz="0.001", px="30000" ) ``` -------------------------------- ### Initialize Trade API Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Initializes the Trade API client for live or demo trading. Ensure you have your API credentials and passphrase set up. ```python import okx.Trade as Trade flag = "1" # live trading: 0, demo trading: 1 tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag) ``` -------------------------------- ### Get Maximum Tradable Size Source: https://context7.com/okxapi/python-okx/llms.txt Query the maximum tradable size for an instrument. Requires authentication. ```python # --- Maximum tradable size --- accountAPI.get_max_order_size(instId="BTC-USDT-SWAP", tdMode="cross") ``` -------------------------------- ### Initialize ETH Staking API Source: https://context7.com/okxapi/python-okx/llms.txt Initializes the ETH Staking API client with API credentials and a flag. Used for managing ETH staking operations. ```python from okx.Finance.EthStaking import EthStakingAPI ethAPI = EthStakingAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1" ) ``` -------------------------------- ### Get Positions Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve current positions for a specified instrument type and ID. Requires authentication. ```python # --- Positions --- positions = accountAPI.get_positions(instType="SWAP", instId="BTC-USDT-SWAP") ``` -------------------------------- ### Place a Market Order Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Use this to place a market order. Ensure 'instId', 'tdMode', 'side', 'ordType', and 'sz' are correctly specified. ```python # market order result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cash", side="buy", ordType="market", sz="100", ) print(result) ``` -------------------------------- ### Launch Spot Grid Bot Source: https://context7.com/okxapi/python-okx/llms.txt Launches a spot grid trading bot with specified parameters including price range, number of grids, run type, and investment amount. ```python result = gridAPI.grid_order_algo( instId="BTC-USDT", algoOrdType="grid", maxPx="35000", minPx="25000", gridNum="10", runType="1", # 1=arithmetic, 2=geometric quoteSz="1000" # invest 1000 USDT ) algo_id = result["data"][0]["algoId"] ``` -------------------------------- ### Get Sub-Account Trading Balance Source: https://context7.com/okxapi/python-okx/llms.txt Fetches the trading balance for a specific sub-account. Requires the sub-account name. ```python subAccountAPI.get_account_balance(subAcct="trader1") ``` -------------------------------- ### Get Option Trades by Family Source: https://context7.com/okxapi/python-okx/llms.txt Fetches trade data for options within a specific instrument family. ```python marketAPI.get_option_trades(instFamily="BTC-USD") ``` -------------------------------- ### Place an algo order (TP/SL on a SWAP) Source: https://context7.com/okxapi/python-okx/llms.txt Places an algorithmic order with Take Profit (TP) and Stop Loss (SL) conditions for a swap instrument. Requires instrument ID, trade mode, side, order type, size, TP/SL trigger prices, TP/SL order prices, and position side. ```APIDOC ## Place an algo order (TP/SL on a SWAP) ### Description Places an algorithmic order with Take Profit (TP) and Stop Loss (SL) conditions for a swap instrument. Requires instrument ID, trade mode, side, order type, size, TP/SL trigger prices, TP/SL order prices, and position side. ### Method ```python tradeAPI.place_algo_order( instId="BTC-USDT-SWAP", tdMode="cross", side="sell", ordType="conditional", sz="1", tpTriggerPx="35000", tpOrdPx="-1", # market price on trigger slTriggerPx="28000", slOrdPx="-1", posSide="long" ) ``` ``` -------------------------------- ### Manage Flexible Loans with Python Source: https://context7.com/okxapi/python-okx/llms.txt Utilize the `FlexibleLoanAPI` for managing flexible loans, including querying supported currencies, collateral assets, loan amounts, and transaction history. Requires API credentials. ```python from okx.Finance.FlexibleLoan import FlexibleLoanAPI loanAPI = FlexibleLoanAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1" ) ``` ```python loanAPI.borrow_currencies() ``` ```python loanAPI.collateral_assets(ccy="BTC") ``` ```python max_loan = loanAPI.max_loan( borrowCcy="USDT", supCollateral=[{"ccy": "BTC", "amt": "0.1"}] ) ``` ```python loanAPI.adjust_collateral(type="add", collateralCcy="BTC", collateralAmt="0.05") loanAPI.adjust_collateral(type="reduce", collateralCcy="BTC", collateralAmt="0.02") ``` ```python loanAPI.max_collateral_redeem_amount(ccy="BTC") ``` ```python loan_info = loanAPI.loan_info() # {"code":"0","data":[{"borrowAmt":"1000","ccy":"USDT","rate":"0.00005",...}]} ``` ```python loanAPI.loan_history(type="borrow", limit="20") ``` ```python loanAPI.interest_accrued(ccy="USDT", limit="50") ``` -------------------------------- ### Get order details Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves the details of a specific order using its instrument ID and order ID. ```APIDOC ## Get order details ### Description Retrieves the details of a specific order using its instrument ID and order ID. ### Method ```python tradeAPI.get_order(instId="BTC-USDT", ordId=ord_id) ``` ``` -------------------------------- ### Place Multiple Orders Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb This snippet demonstrates how to place multiple orders simultaneously. It requires a list of order objects, each containing order details. ```APIDOC ## Place Multiple Orders ### Description Place orders in a batch. ### Method `POST` ### Endpoint `/api/v5/trade/batch-orders` ### Parameters #### Request Body - **orders** (array) - Required - A list of order objects, each with parameters like instId, tdMode, side, ordType, px, sz. ### Request Example ```python place_orders = [ {"instId":"BTC-USDT", "tdMode":"cash", "side":"buy", "ordType" : "limit","px":"1000","sz":"0.01"}, {"instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit", "px": "1000", "sz": "0.02"} ] result = tradeAPI.place_multiple_orders(place_orders) print(result) ``` ``` -------------------------------- ### Place a Limit Order (Spot Trading) Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb This snippet shows how to place a limit order for spot trading, specifically in cross-margin or portfolio margin mode. It includes parameters for instrument ID, trade mode, side, order type, price, and size. ```APIDOC ## Spot trading under multi-currency/porfolio margin mode ### Description Place a limit order for spot trading under multi-currency or portfolio margin mode. ### Method `POST` ### Endpoint `/api/v5/trade/order` ### Parameters #### Query Parameters - **instId** (string) - Required - Instrument ID, e.g., BTC-USDT - **tdMode** (string) - Required - Trading Mode: cross, isolated - **side** (string) - Required - Order side: buy, sell - **ordType** (string) - Required - Order type: limit - **px** (string) - Required - Price of the order - **sz** (string) - Required - Size of the order ### Request Example ```python # cross-margin spot trading result = tradeAPI.place_order( instId="BTC-USDT", tdMode="cross", side="buy", ordType="limit", px="1000", sz="0.01" ) print(result) if result["code"] == "0": print("Successful order request,order_id = ",result["data"][0]["ordId"]) else: print("Unsuccessful order request,error_code = ",result["data"][0]["sCode"], ", Error_message = ", result["data"][0]["sMsg"]) ``` ``` -------------------------------- ### Get Fee Rates Source: https://context7.com/okxapi/python-okx/llms.txt Retrieve fee rates for a specified instrument type and ID. Requires authentication. ```python # --- Fee rates --- fees = accountAPI.get_fee_rates(instType="SPOT", instId="BTC-USDT") ``` -------------------------------- ### Initialize Grid Trading API Source: https://context7.com/okxapi/python-okx/llms.txt Initializes the Grid API client with API credentials and a flag. Used for managing automated grid trading bots. ```python import okx.Grid as Grid gridAPI = Grid.GridAPI( api_key="KEY", api_secret_key="SECRET", passphrase="PASS", flag="1" ) ``` -------------------------------- ### Get transaction details (last 3 months) Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieve transaction details for the last 3 months. ```APIDOC ## GET /api/v5/trade/fills-history ### Description Retrieve transaction details for the last 3 months. ### Method GET ### Endpoint /api/v5/trade/fills-history ### Parameters #### Query Parameters - **instType** (string) - Required - Instrument type, e.g., SPOT, SWAP, FUTURES, OPTIONS ### Response #### Success Response (200) - **code** (string) - Response code - **data** (array) - Data object - **tradeId** (string) - Trade ID #### Response Example ```json { "code": "0", "data": [ { "tradeId": "123456789" } ] } ``` ``` -------------------------------- ### Easy convert (swap small balances) Source: https://context7.com/okxapi/python-okx/llms.txt Convert small balances of specified currencies into another currency. First, retrieve the list of supported currencies for conversion. ```python currency_list = tradeAPI.get_easy_convert_currency_list() tradeAPI.easy_convert(fromCcy=["USDC", "DAI"], toCcy="USDT") ``` -------------------------------- ### Get transaction details (last 3 days) Source: https://github.com/okxapi/python-okx/blob/master/example/trade_derivatives_en.ipynb Retrieve transaction details for the last 3 days. ```APIDOC ## GET /api/v5/trade/fills ### Description Retrieve transaction details for the last 3 days. ### Method GET ### Endpoint /api/v5/trade/fills ### Parameters #### Query Parameters - **instType** (string) - Required - Instrument type, e.g., SPOT, SWAP, FUTURES, OPTIONS ### Response #### Success Response (200) - **code** (string) - Response code - **data** (array) - Data object - **tradeId** (string) - Trade ID #### Response Example ```json { "code": "0", "data": [ { "tradeId": "123456789" } ] } ``` ``` -------------------------------- ### Place Multiple Orders in Batch Source: https://github.com/okxapi/python-okx/blob/master/example/get_started_en.ipynb Submit multiple orders simultaneously using the 'place_multiple_orders' function. Each order in the list must be a dictionary with required parameters. ```python place_orders = [ {"instId":"BTC-USDT", "tdMode":"cash", "side":"buy", "ordType" : "limit","px":"1000","sz":"0.01"}, {"instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit", "px": "1000", "sz": "0.02"} ] result = tradeAPI.place_multiple_orders(place_orders) print(result) ``` -------------------------------- ### Get Lending History Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves the history of lending activities for a specified currency, with an option to limit the number of results. ```python # --- Lending history --- savingsAPI.get_lending_history(ccy="USDT", limit="20") ``` -------------------------------- ### Get Bills for a Sub-Account Source: https://context7.com/okxapi/python-okx/llms.txt Fetches billing records for a specific sub-account and currency, with options to limit the number of records. ```python subAccountAPI.bills(subAcct="trader1", ccy="USDT", limit="50") ``` -------------------------------- ### Spot Manual Borrow/Repay Source: https://context7.com/okxapi/python-okx/llms.txt Manually borrow or repay assets for spot trading. Requires authentication. ```python # --- Spot borrow / repay --- accountAPI.spot_manual_borrow_repay(ccy="USDT", side="borrow", amt="500") ``` -------------------------------- ### Get Insurance Fund Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves data from the insurance fund, filterable by instrument type, underlying asset, and limit. ```python publicAPI.get_insurance_fund(instType="SWAP", uly="BTC-USD", limit="10") ``` -------------------------------- ### Subscribe to Public Data Streams via WebSocket (Python) Source: https://context7.com/okxapi/python-okx/llms.txt Connect to OKX public WebSocket channels for real-time data like tickers, candles, and order books using `WsPublicAsync`. Handles automatic reconnection and provides a callback for message processing. ```python import asyncio from okx.websocket.WsPublicAsync import WsPublicAsync # Public WebSocket URLs WS_PUBLIC_URL = "wss://ws.okx.com:8443/ws/v5/public" # live WS_PUBLIC_DEMO = "wss://wspap.okx.com:8443/ws/v5/public" # demo def handle_message(msg: str): print("Received:", msg) async def main(): ws = WsPublicAsync(url=WS_PUBLIC_URL, debug=False) await ws.start() # Subscribe to BTC-USDT ticker await ws.subscribe( params=[{"channel": "tickers", "instId": "BTC-USDT"}], callback=handle_message ) # Subscribe to BTC-USDT-SWAP 1m candles await ws.subscribe( params=[{"channel": "candle1m", "instId": "BTC-USDT-SWAP"}], callback=handle_message ) # Subscribe to order book (depth 400) await ws.subscribe( params=[{"channel": "books", "instId": "BTC-USDT"}], callback=handle_message ) # Subscribe to funding rate await ws.subscribe( params=[{"channel": "funding-rate", "instId": "BTC-USDT-SWAP"}], callback=handle_message ) # Keep running await asyncio.sleep(30) # Unsubscribe await ws.unsubscribe( params=[{"channel": "tickers", "instId": "BTC-USDT"}], callback=handle_message ) await ws.stop() asyncio.run(main()) ``` -------------------------------- ### Easy convert (swap small balances) Source: https://context7.com/okxapi/python-okx/llms.txt Facilitates the conversion of small balances between specified currencies. First, retrieve the list of supported currencies, then initiate the conversion. ```APIDOC ## Easy convert (swap small balances) ### Description Facilitates the conversion of small balances between specified currencies. First, retrieve the list of supported currencies, then initiate the conversion. ### Method ```python currency_list = tradeAPI.get_easy_convert_currency_list() tradeAPI.easy_convert(fromCcy=["USDC", "DAI"], toCcy="USDT") ``` ``` -------------------------------- ### Get Index Tickers Source: https://context7.com/okxapi/python-okx/llms.txt Retrieves ticker information for index instruments. You can filter by quote currency and instrument ID. ```python marketAPI.get_index_tickers(quoteCcy="USD", instId="BTC-USD") ```