Derivatives trading has become increasingly accessible through powerful programming tools like Jupyter Notebook, especially when combined with advanced trading platforms such as OKX. This guide walks you through how to seamlessly integrate Jupyter Notebook with the OKX API to execute, monitor, and manage derivatives trades — all from a single, interactive environment.
Whether you're a data scientist, algorithmic trader, or crypto enthusiast, this tutorial equips you with practical code examples and essential insights into perpetual swaps, leverage settings, position modes, and real-time order management.
Understanding Derivatives on OKX
OKX supports three primary types of derivatives for traders:
- Expiry Futures
- Perpetual Swaps
- Options
In this guide, we’ll focus on Perpetual Swaps, one of the most popular instruments due to their lack of expiration and flexible leverage options. However, the same principles apply across other derivative types with minor adjustments.
👉 Get started with real-time derivatives data in your notebook today.
Core Tools: Setting Up the OKX API in Jupyter
To interact with OKX’s derivatives market via Jupyter Notebook, you’ll use the official okx Python SDK. This allows you to retrieve market data, check balances, place orders, and manage positions programmatically.
Prerequisites:
- Python 3.7+
okxlibrary installed (pip install okx)- API key, secret key, and passphrase from your OKX account
- Jupyter Notebook environment
Step-by-Step: Key Functions for Derivatives Trading
1. Retrieve Real-Time Market Data
Stay updated with current market conditions by fetching live tickers for perpetual contracts.
import okx.MarketData as MarketData
flag = "1" # Use "1" for demo trading, "0" for live
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SWAP") # SWAP = Perpetuals
print(result)Replace "SWAP" with "EXPIRY" or "OPTION" to get data for futures or options markets.
2. List Available Trading Pairs
Discover which perpetual contracts are available for trading.
import okx.PublicData as PublicData
publicDataAPI = PublicData.PublicAPI(flag=flag)
result = publicDataAPI.get_instruments(instType="SWAP")
print(result)Calculate Notional Value of a Contract
Each derivative contract has a notional value based on its ctVal (contract value) and ctMult (contract multiplier):
Notional Value = ctVal × ctMult (in ctValCcy)
For example, the LTC-USD-SWAP contract:
{
"instId": "LTC-USD-SWAP",
"ctVal": "10",
"ctMult": "1",
"ctValCcy": "USD"
}→ Notional value = 10 × 1 = 10 USD per contract
This helps assess exposure and risk before placing trades.
3. Check Your Account Balance
Monitor your available funds across all currencies.
import okx.Account as Account
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_account_balance()
print(result)Ensure sufficient margin is available before initiating leveraged positions.
4. Verify Eligible Account Mode for Derivatives
Only certain account modes support derivatives trading:
- ✅ Spot and Futures Mode
- ✅ Multi-Currency Margin Mode
- ✅ Portfolio Margin Mode
Spot-only mode does not allow derivatives trading.
Check your current mode:
result = accountAPI.get_account_config()
if result['code'] == "0":
acctLv = result["data"][0]["acctLv"]
mode_map = {
"1": "Simple mode (Spot only)",
"2": "Single-currency margin",
"3": "Multi-currency margin",
"4": "Portfolio margin"
}
print("Account Mode:", mode_map.get(acctLv, "Unknown"))👉 Switch to a derivatives-enabled account mode now.
5. Set Leverage for Higher Efficiency
Leverage amplifies both gains and losses. OKX allows up to 125x leverage depending on instrument and position size.
Key terms:
- Max Leverage: Highest borrowing multiple allowed.
- Initial Margin Ratio (IMR): Required margin to open a position.
- Maintenance Margin Ratio (MMR): Minimum margin to avoid liquidation.
Example: Setting 5x leverage on BTC-USDT-SWAP:
# Cross-margin mode
accountAPI.set_leverage(
instId="BTC-USDT-SWAP",
lever="5",
mgnMode="cross"
)
# Isolated margin for long position only
accountAPI.set_leverage(
instId="BTC-USDT-SWAP",
lever="5",
posSide="long",
mgnMode="isolated"
)⚠️ Always adjust leverage according to your risk tolerance.
6. Place Orders Using Position Modes
Choose between two position modes:
- Buy/Sell (Net): Single net position per instrument.
- Long/Short: Separate long and short positions.
Switch mode via API:
accountAPI.set_position_mode(posMode="long_short_mode")Place a Limit Order
Buy 100 BTC-USDT-SWAP contracts at $19,000:
tradeAPI.place_order(
instId="BTC-USDT-SWAP",
tdMode="isolated",
side="buy",
posSide="long",
ordType="limit",
px="19000",
sz="100"
)Place a Market Order
Execute immediately at current market price:
tradeAPI.place_order(
instId="BTC-USDT-SWAP",
tdMode="isolated",
side="buy",
posSide="long",
ordType="market",
sz="100"
)7. Monitor and Manage Orders
Get Order Details
tradeAPI.get_order(instId="BTC-USDT-SWAP", ordId="505073046126960640")Cancel an Order
tradeAPI.cancel_order(instId="BTC-USDT-SWAP", ordId="505073046126960640")Amend Order Size
tradeAPI.amend_order(
instId="BTC-USDT-SWAP",
ordId="505073046126960640",
newSz="80"
)8. Retrieve Open and Historical Orders
List open orders:
tradeAPI.get_order_list()Get past orders (last 7 days):
tradeAPI.get_orders_history(instType="SWAP")Archive beyond 7 days:
tradeAPI.get_orders_history_archive(instType="SWAP")9. View Transaction and Position Data
Fetch executed trades:
tradeAPI.get_fills() # Last 3 days
tradeAPI.get_fills_history(instType="SWAP") # Last 3 monthsCheck current positions:
positions = accountAPI.get_positions()
for pos in positions['data']:
print(f"Symbol: {pos['instId']}, PnL: {pos['upl']}")Track unrealized PnL (upl) to evaluate active trade performance.
Frequently Asked Questions (FAQ)
Q: Can I use Jupyter Notebook for live derivatives trading?
A: Yes. With proper API keys and risk controls, Jupyter Notebook can be used for both demo and live trading environments.
Q: What is the difference between isolated and cross margin?
A: Isolated margin allocates specific collateral to a single position. Cross margin uses the entire balance as potential collateral, increasing efficiency but also risk.
Q: How do I avoid liquidation in high-leverage trades?
A: Monitor your maintenance margin ratio (MMR), set stop-losses, and avoid over-leveraging relative to your account size.
Q: Can I automate trading strategies using these APIs?
A: Absolutely. You can build automated bots for arbitrage, trend following, or hedging strategies directly within Jupyter.
Q: Is it safe to store API keys in Jupyter notebooks?
A: Never hardcode sensitive credentials. Use environment variables or secure vaults to protect your keys.
Q: Does OKX support backtesting in Jupyter?
A: While OKX doesn't provide built-in backtesting tools, you can download historical data via APIs and use libraries like pandas or backtrader for strategy testing.
Final Thoughts
Jupyter Notebook offers a powerful platform for executing and analyzing derivatives trades programmatically. By integrating it with the OKX API, traders gain full control over market access, order execution, and portfolio monitoring — all within a flexible, scriptable environment.
Whether you're building a simple alert system or a full algorithmic trading engine, combining Python’s analytical strength with OKX’s robust derivatives infrastructure opens new possibilities for precision and automation.