Python Script to Query OKX Portfolio Positions for Quantitative Trading

·

Prerequisites and Setup

To retrieve your portfolio data from OKX, you'll need to:

  1. Install the ccxt library:

    pip install ccxt pandas
  2. Obtain your API credentials from OKX:

    • apiKey
    • secret
    • password (if enabled)

Complete Code Implementation

import ccxt
import pandas as pd
from datetime import datetime
import traceback
from IPython.display import clear_output

# Initialize OKX exchange connection
exchange = ccxt.okex({
    'apiKey': 'your_api_key_here',
    'secret': 'your_secret_here',
    'password': 'your_password_here',
    'timeout': 30000,
    'enableRateLimit': True,
    'proxies': {
        'http': 'http://127.0.0.1:10809',
        'https': 'http://127.0.0.1:10809',
    }
})

# Chinese column mappings for better readability
cn_columns = {
    'instId': 'Instrument',
    'entryPrice': 'Entry Price',
    'markPx': 'Mark Price',
    'liqPx': 'Liquidation Price',
    'unrealizedPnl': 'P&L',
    'percentage': 'ROI'
}

# Main monitoring loop
while True:
    conversion_rate = 7.2755  # USD to CNY conversion
    try:
        balance_data = exchange.fetchBalance()
        usd_balance = balance_data["total"]["USDT"] * conversion_rate
        
        positions = exchange.fetchPositions()
        position_df = pd.DataFrame([{**item["info"], **item} for item in positions])
        
        if position_df.shape[0] > 0:  # Show current positions
            position_df = position_df[cn_columns.keys()].rename(columns=cn_columns)
            position_df['Timestamp'] = datetime.now().strftime('%H:%M:%S')
            position_df['USD Balance'] = usd_balance
            position_df['Liquidation Price'] = position_df['Liquidation Price'].astype(float).round(2)
            position_df['ROI'] = position_df['ROI'].apply(lambda x: f"{float(x):.2f}%")
            
            clear_output(wait=True)
            display(position_df)
        else:  # Show watchlist if no positions
            watchlist = ["BTC/USDT", "ETH/USDT", "SOL/USDT"]
            tickers = [exchange.fetch_ticker(symbol=asset) for asset in watchlist]
            market_df = pd.DataFrame(tickers)[["symbol", "datetime", "last"]]
            market_df['datetime'] = pd.to_datetime(market_df['datetime']) + pd.Timedelta(hours=8)
            market_df['datetime'] = market_df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
            market_df['USD Balance'] = usd_balance
            
            clear_output(wait=True)
            display(market_df)
            
    except Exception as e:
        traceback.print_exc()
        break

Key Features

  1. Real-time Portfolio Monitoring: Continuously tracks your OKX positions
  2. Balance Conversion: Automatically converts USDT balance to local currency
  3. Position Analysis: Displays critical metrics including:

    • Entry and mark prices
    • Liquidation risk levels
    • Unrealized P&L

👉 Learn advanced quantitative trading strategies

FAQ Section

How often does the script update position data?

The script updates continuously in real-time, refreshing with each loop iteration (typically every few seconds).

What if I don't have any open positions?

When no positions are held, the script automatically displays market data for BTC, ETH, and SOL as default watchlist assets.

Is my API information secure?

Yes, the credentials are only used locally in your script. Never share your API keys or store them in version control.

👉 Secure API key management guide

Best Practices for Quantitative Trading

  1. Risk Management: Always set stop-loss orders
  2. Diversification: Spread capital across multiple assets
  3. Backtesting: Validate strategies before live implementation
  4. Monitoring: Use scripts like this to maintain position awareness

For developers interested in expanding this solution, consider adding: