Trading derivatives has become increasingly accessible thanks to powerful tools like Jupyter Notebook, which allows traders and developers to automate strategies, analyze market data, and execute trades programmatically. This guide walks you through how to use Jupyter Notebook with the OKX API to trade derivatives efficiently and effectively.
Whether you're a beginner exploring algorithmic trading or an experienced developer building complex strategies, this tutorial provides actionable insights into leveraging Python-based notebooks for real-time derivative trading.
Types of Derivatives Available on OKX
OKX supports three main types of derivatives:
- Futures contracts
- Perpetual contracts
- Options
👉 Discover how to automate your derivative trading strategy in minutes.
In this guide, we focus specifically on perpetual contracts, one of the most popular instruments due to their flexibility and lack of expiration date. These contracts allow traders to maintain long or short positions indefinitely, making them ideal for both short-term speculation and long-term hedging.
To explore all derivative types available on OKX and understand their unique features, refer to the official documentation.
Accessing Market Data via API
One of the first steps in algorithmic trading is retrieving real-time market data. With OKX’s MarketData API, you can fetch live tickers for any instrument type.
import okx.MarketData as MarketData
flag = "1" # Live trading: 0, demo trading: 1
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SWAP")
print(result)You can replace instType with "FUTURES" or "OPTION" depending on your trading focus. This flexibility ensures seamless integration across different derivative products.
Retrieving Tradable Pairs
To identify available trading pairs, use the PublicData API:
import okx.PublicData as PublicData
if __name__ == '__main__':
flag = "1"
publicDataAPI = PublicData.PublicAPI(flag=flag)
result = publicDataAPI.get_instruments(instType="SWAP")
print(result)Calculating Contract Value Using ctVal and ctMult
Each derivative contract has two key parameters:
ctVal: Contract valuectMult: Contract multiplier
The notional value of a derivative is calculated as:
ctVal × ctMult (unit: ctValCcy)
For example, consider the LTC-USD-SWAP contract:
"instType": "SWAP",
"instId": "LTC-USD-SWAP",
"ctVal": "10",
"ctMult": "1",
"ctValCcy": "USD"Its notional value is 10 × 1 = 10 USD. This calculation helps assess position size and risk exposure accurately.
Checking Account Balance
Before placing trades, verify your account balance using the Account API:
import okx.Account as Account
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_account_balance()
print(result)This returns all asset balances, enabling you to manage funds dynamically within your notebook environment.
Supported Account and Margin Modes for Derivatives
OKX offers four account modes under its Unified Trading Account system:
- Spot mode
- Spot & Futures mode
- Multi-currency margin mode
- Portfolio margin mode
Only the last three support derivatives trading. To check your current mode:
result = accountAPI.get_account_config()
if result['code'] == "0":
acctLv = result["data"][0]["acctLv"]
mode_map = {
"1": "Simple mode",
"2": "Single-currency margin mode",
"3": "Multi-currency margin mode",
"4": "Portfolio margin mode"
}
print(mode_map.get(acctLv, "Unknown"))👉 Learn how to switch between margin modes and optimize your trading setup.
Ensure your account is configured correctly before initiating derivative trades.
Setting Leverage Programmatically
Leverage amplifies both potential gains and losses. OKX allows up to 125x leverage on perpetual contracts.
Key terms:
- Leverage: Multiplier for borrowed capital
- Initial Margin Ratio (IMR): Required margin to open a position
- Maintenance Margin Ratio (MMR): Minimum margin to avoid liquidation
For example, 75x leverage implies an IMR of ~1.3% and MMR of 0.8%.
You can set leverage via API in various scenarios:
# Cross-margin leverage for BTC-USDT-SWAP
result = accountAPI.set_leverage(
instId="BTC-USDT-SWAP",
lever="5",
mgnMode="cross"
)
# Isolated margin with long/short differentiation
result = accountAPI.set_leverage(
instId="BTC-USDT-SWAP",
lever="5",
posSide="long",
mgnMode="isolated"
)Note: The posSide parameter is required only in isolated margin mode when using long/short position mode.Managing Position Modes: Long/Short vs Buy/Sell
OKX supports two position modes:
- Buy/Sell (Net mode): Net position per contract
- Long/Short: Separate long and short positions
Switch modes via API:
result = accountAPI.set_position_mode(posMode="long_short_mode")Or adjust settings directly on the OKX platform.
| Action | Side | PosSide |
|---|---|---|
| Open long | buy | long |
| Open short | sell | short |
| Close long | sell | long |
| Close short | buy | short |
This distinction is crucial when managing multiple positions simultaneously.
Placing a Limit Order
result = tradeAPI.place_order(
instId="BTC-USDT-SWAP",
tdMode="isolated",
side="buy",
posSide="net",
ordType="limit",
px="19000",
sz="100"
)Placing a Market Order
result = tradeAPI.place_order(
instId="BTC-USDT-SWAP",
tdMode="isolated",
side="buy",
posSide="net",
ordType="market",
sz="100"
)Monitoring and Managing Orders
Retrieve order details using ordId or clOrdId:
result = tradeAPI.get_order(instId="BTC-USDT-SWAP", ordId="505073046126960640")Cancel or amend orders similarly:
tradeAPI.cancel_order(instId="BTC-USDT-SWAP", ordId="...")
tradeAPI.amend_order(
instId="BTC-USDT-SWAP",
ordId="...",
newSz="80"
)Access open and historical orders:
tradeAPI.get_order_list()
tradeAPI.get_orders_history(instType="SWAP") # Last 7 days
tradeAPI.get_orders_history_archive(instType="SWAP") # Last 3 monthsTracking Trade Execution and Positions
Get transaction fills:
tradeAPI.get_fills() # Last 3 days
tradeAPI.get_fills_history(instType="SWAP") # Last 3 monthsCheck current positions:
result = accountAPI.get_positions()Monitor unrealized PnL via the upl field in the response.
Frequently Asked Questions
Q: Can I use Jupyter Notebook for live derivative trading?
A: Yes. Jupyter Notebook integrates seamlessly with OKX APIs, allowing live data streaming, strategy backtesting, and real-time trade execution.
Q: What are the risks of high leverage in perpetual contracts?
A: High leverage increases both profit potential and liquidation risk. Always monitor your maintenance margin and use stop-loss mechanisms.
Q: How do I switch between net and long/short position modes?
A: Use the set_position_mode API function or change it manually in your OKX account settings.
Q: Is demo trading supported?
A: Yes. Set flag = "1" in your API configuration to use the demo environment without risking real funds.
Q: Can I automate full trading strategies in Jupyter?
A: Absolutely. You can build complete algorithmic systems—from signal generation to order execution—within a single notebook.
Q: Are there rate limits on OKX APIs?
A: Yes. Review OKX API rate limits to avoid throttling during high-frequency operations.
👉 Start building your automated trading bot today with OKX’s powerful API tools.
By combining Jupyter Notebook’s interactive development environment with OKX’s robust derivatives ecosystem, traders gain a significant edge in speed, precision, and scalability. Whether you're analyzing BTC volatility or executing ETH hedges, this setup empowers data-driven decision-making at every step.