How to Use Jupyter Notebook for Derivatives Trading with Python-OKX Library

ยท

Derivatives trading has become increasingly popular among traders seeking leverage and flexibility in their strategies. This comprehensive guide will walk you through using Jupyter Notebook with the python-okx library for trading perpetual swaps on OKX exchange.

Getting Started with Derivatives Trading on OKX

OKX offers three types of derivatives:

For this tutorial, we'll focus on perpetual swap trading using Python in Jupyter Notebook environment.

Core Trading Functions

1. Market Data Retrieval

To begin trading, you'll need access to real-time market data. Here's how to fetch ticker information for perpetual swaps:

import okx.MarketData as MarketData
flag = "1"  # 1 for demo trading, 0 for live trading
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SWAP")
print(result)

๐Ÿ‘‰ Explore advanced trading strategies

2. Available Trading Instruments

Discover which perpetual swap instruments are available for trading:

import okx.PublicData as PublicData
publicDataAPI = PublicData.PublicAPI(flag="1")
result = publicDataAPI.get_instruments(instType="SWAP")
print(result)

2.1 Calculating Contract Nominal Value

Understanding contract specifications is crucial for proper position sizing:

{
  "instType":"SWAP",
  "instId":"LTC-USD-SWAP",
  "ctVal":"10",
  "ctMult":"1",
  "ctValCcy":"USD"
}

Nominal value = ctVal ร— ctMult = 10 ร— 1 = 10 USD

3. Account Balance Check

Monitor your available trading funds:

import okx.Account as Account
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_account_balance()
print(result)

Trading Account Configuration

4. Account Modes and Margin Types

OKX offers four account configurations:

  1. Simple Spot Mode
  2. Single-currency Margin Mode
  3. Multi-currency Margin Mode
  4. Portfolio Margin Mode

Check your current account mode:

result = accountAPI.get_account_config()
if result['code'] == "0":
    acctLv = result["data"][0]["acctLv"]
    print(f"Current account mode: {acctLv}")

5. Leverage Settings

OKX supports up to 125x leverage. Key concepts:

Set leverage for different scenarios:

# Cross-margin leverage setting
result = accountAPI.set_leverage(
    instId="BTC-USDT-SWAP",
    lever="5",
    mgnMode="cross"
)

# Isolated margin (buy/sell mode)
result = accountAPI.set_leverage(
    instId="BTC-USDT-SWAP",
    lever="5",
    mgnMode="isolated"
)

# Long/short position mode
result = accountAPI.set_leverage(
    instId="BTC-USDT-SWAP",
    lever="5",
    posSide="long",
    mgnMode="isolated"
)

๐Ÿ‘‰ Master leverage trading techniques

Placing Orders and Position Management

6. Position Modes

OKX offers two position management styles:

  1. Long/Short Mode (independent positions)
  2. Buy/Sell Mode (net positions)

Set your position mode:

result = accountAPI.set_position_mode(
    posMode="long_short_mode"
)

7. Order Placement Examples

7.1 Limit Order

Buy 100 BTC-USDT perpetual contracts at 19,000 USDT:

result = tradeAPI.place_order(
    instId="BTC-USDT-SWAP",
    tdMode="isolated",
    side="buy",
    posSide="net",
    ordType="limit",
    px="19000",
    sz="100"
)

7.2 Market Order

Buy 100 contracts at market price:

result = tradeAPI.place_order(
    instId="BTC-USDT-SWAP",
    tdMode="isolated",
    side="buy",
    posSide="net",
    ordType="market",
    sz="100"
)

Advanced Order Management

8. Order Status Checks

Query specific order details:

result = tradeAPI.get_order(
    instId="BTC-USDT-SWAP",
    ordId="505073046126960640"
)

9. Order Cancellation

Cancel an existing order:

result = tradeAPI.cancel_order(
    instId="BTC-USDT-SWAP",
    ordId="505073046126960640"
)

10. Order Modification

Amend an existing order:

result = tradeAPI.amend_order(
    instId="BTC-USDT-SWAP",
    ordId="505073046126960640",
    newSz="80"
)

Historical Data and Position Tracking

11. Order History

Retrieve your trading history:

# Last 7 days
result = tradeAPI.get_orders_history(instType="SWAP")

# Last 3 months
result = tradeAPI.get_orders_history_archive(instType="SWAP")

12. Transaction Details

Review your trade executions:

# Recent fills
result = tradeAPI.get_fills()

# Historical fills
result = tradeAPI.get_fills_history(instType="SWAP")

13. Position Monitoring

Track your open positions:

result = accountAPI.get_positions()

FAQ Section

Q: What's the difference between perpetual swaps and futures contracts?

A: Perpetual swaps don't have expiration dates and use funding mechanisms to maintain price alignment with spot markets.

Q: How often does OKX charge funding fees?

A: Funding occurs every 8 hours for perpetual swaps (00:00, 08:00, and 16:00 UTC).

Q: What's the minimum order size for derivatives?

A: Minimum order sizes vary by instrument but typically start at 1 contract.

Q: How does liquidation work on OKX?

A: Positions are liquidated when margin falls below maintenance requirements, with partial liquidation attempts before full liquidation.

Q: Can I use the same API keys for demo and live trading?

A: No, you need separate API keys for demo and live trading environments.

Q: How do I calculate position value?

A: Position value = contract size ร— number of contracts ร— current price.

๐Ÿ‘‰ Discover more trading insights