python-okx

repository·master·Indexed 21 days ago

https://github.com/okxapi/python-okx

An unofficial Python wrapper for the OKX exchange v5 API. It provides access to Rest API endpoints and both Public and Private WebSocket implementations. The library includes modules for Trade, Account, MarketData, PublicData, Funding, and others, supporting both live trading (flag 0) and demo trading (flag 1). It enables users to manage account balances, place and amend limit or market orders, handle algo orders (trigger and conditional), and retrieve market tickers and order history.

Tokens
5.2K
Snippets
17
Records
20
Agent score
75%

What's inside python-okx

  1. Configure API credentials

    master

    You can authenticate with the OKX API using either hardcoded credentials or an environment file.

    Hardcoded Credentials

    Pass the credentials directly to the Account.AccountAPI constructor.

    Create a .env file in your project root with the following keys:

    • OKX_API_KEY
    • OKX_API_SECRET
    • OKX_PASSPHRASE
    • OKX_FLAG (Use 0 for live trading, 1 for demo trading)

    Then use python-dotenv to load them into your environment.

    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
    )
  2. Set up a local development environment

    master

    If you are contributing to the project or developing locally, follow these steps:

    1. Clone the repository.
    2. Install development dependencies from dev_requirements.txt.
    3. Install the package in editable mode.
    4. Run the unit tests using pytest.
    # Clone the repository
    git clone https://github.com/okxapi/python-okx.git
    cd python-okx
    
    # Install dependencies
    pip install -r dev_requirements.txt
    pip install -e .
    
    # Run tests
    pytest test/unit/ -v
  3. Initialize API clients

    master

    To interact with OKX, you must initialize an API client with your credentials. Most clients require an api_key, secret_key, passphrase, and a flag to distinguish between trading modes.

    Trading Flag:

    • 0: Live trading
    • 1: Demo trading
    import okx.Funding as Funding
    import okx.MarketData as MarketData
    import okx.Account as Account
    import okx.Trade as Trade
    
    api_key = "xxxxx"
    secret_key = "xxxxx"
    passphrase = "xxxxxx"
    flag = "1"  # 1 for demo, 0 for live
    
    # Example: Funding API
    fundingAPI = Funding.FundingAPI(api_key, secret_key, passphrase, False, flag)
    
    # Example: Market Data API (Public)
    marketDataAPI = MarketData.MarketAPI(flag=flag)
    
    # Example: Account API
    accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
    
    # Example: Trade API
    tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)
  4. Initialize OKX API modules

    master

    The okx library is organized into several modules based on functionality. To interact with different parts of the OKX ecosystem, import the specific module required for your task.

    Available modules include:

    • okx.Trade: Order placement and management
    • okx.Account: Account balances, configuration, and positions
    • okx.MarketData: Market tickers and price information
    • okx.PublicData: Instrument information and trading pairs
    • okx.Funding: Currency and funding information
    • okx.BlockTrading, okx.Convert, okx.Earning, okx.SubAccount, okx.Status, okx.NDBroker, okx.FDBroker
    import okx.Trade as Trade
    import okx.Account as Account
    import okx.MarketData as MarketData
    import okx.PublicData as PublicData
    import okx.Funding as Funding
  5. Configure API credentials and trading mode

    master

    To use the API, you must provide your api_key, secret_key, and passphrase.

    When initializing API classes, use the flag parameter to switch between environments:

    • flag = "0": Live trading
    • flag = "1": Demo trading
    api_key = "xxxxx"
    secret_key = "xxxxx"
    passphrase = "xxxxxx"
    flag = "1"  # demo trading
    
    # Example initialization
    from okx.Funding import FundingAPI
    fundingAPI = FundingAPI(api_key, secret_key, passphrase, False, flag)
  6. Run RestAPI and WebSocketAPI examples

    master

    After installing and configuring credentials, you can run the provided examples to explore functionality:

    RestAPI Examples

    • Spot trading: Run example/get_started_en.ipynb
    • Derivative trading: Run example/trade_derivatives_en.ipynb

    WebSocketAPI Examples

    • Private channels: Run test/WsPrivateTest.py
    • Public channels: Run test/WsPublicTest.py

    Note: Ensure you use the correct URLs for the environment (Live vs Demo) and update your API credentials in the example files.

  7. Manage account balance and trading capacity

    master

    Use the Account module to check your balance, account configuration (mode), and maximum tradable amounts for specific pairs.

    import okx.Account as Account
    accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, "1")
    
    # Get account balance
    balance = accountAPI.get_account_balance()
    
    # Get maximum tradable amount for a pair
    # instId: instrument ID (e.g., BTC-USDT)
    # tdMode: trading mode (e.g., 'cash', 'cross')
    max_size = accountAPI.get_max_avail_size(instId="BTC-USDT", tdMode="cash")
    
    # Get account configuration (acctLv)
    # acctLv values:
    # 1: Simple mode
    # 2: Single-currency margin mode
    # 3: Multi-currency margin mode
    # 4: Portfolio margin mode
    config = accountAPI.get_account_config()
  8. Retrieve order history and fills

    master

    Use TradeAPI to fetch open orders, specific order details, past order history, and transaction fills.

    # Get details of a specific order by ordId or clOrdId
    tradeAPI.get_order(instId="BTC-USDT", ordId="497819823594909696")
    
    # Get list of currently open orders
    tradeAPI.get_order_list()
    
    # Get past orders (history)
    tradeAPI.get_orders_history(instType="SPOT")
    tradeAPI.get_orders_history_archive(instType="SPOT")
    
    # Get transaction fills (last 3 days or history)
    tradeAPI.get_fills(instType="SPOT")
    tradeAPI.get_fills_history(instType="SPOT")
  9. Manage account configuration and leverage

    master

    Before trading derivatives, ensure your account is in a compatible margin mode. Only the following modes are eligible for derivatives:

    • Single-currency margin
    • Multi-currency margin
    • Portfolio margin

    You can check your current mode via AccountAPI.get_account_config() and the acctLv parameter:

    • 1: Simple mode
    • 2: Single-currency margin mode
    • 3: Multi-currency margin mode
    • 4: Portfolio margin mode

    Use AccountAPI.set_leverage() to adjust leverage for specific instruments. You can set leverage for cross-margin or isolated-margin positions.

    import okx.Account as Account
    
    accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
    
    # Set leverage to 5x for cross-margin BTC-USDT SWAP
    result = accountAPI.set_leverage(
        instId = "BTC-USDT-SWAP",
        lever = "5",
        mgnMode = "cross"
    )
    
    # Set leverage to 5x for an isolated-margin long position
    result = accountAPI.set_leverage(
        instId = "BTC-USDT-SWAP",
        lever = "5",
        posSide = "long",
        mgnMode = "isolated"
    )