Derivatives trading has become a cornerstone of modern financial strategies, especially in the digital asset space. With powerful tools like Jupyter Notebook and robust APIs such as python-okx, traders can build automated, data-driven workflows to execute sophisticated trading strategies. This guide walks you through using Jupyter Notebook to trade derivatives—specifically perpetual contracts—on a leading exchange platform, leveraging real-time data, precise calculations, and programmatic order execution.
Whether you're analyzing market trends, calculating contract values, or placing algorithmic trades, this tutorial ensures you have the foundational knowledge to operate efficiently and securely.
Accessing Market Data
Before placing any trade, understanding current market conditions is essential. The MarketData module from the python-okx library allows you to fetch live or demo trading data seamlessly.
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)Replace "SWAP" with "FUTURES" or "OPTION" to retrieve data for other derivative types. This flexibility enables comprehensive cross-market analysis directly within your notebook.
👉 Discover how to analyze real-time crypto markets using code-based tools
Retrieving Tradable Instruments
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)Each instrument includes critical parameters such as ctVal (contract value) and ctMult (contract multiplier), which are key to calculating nominal contract value.
Calculating Nominal Value of Derivatives Contracts
The nominal value determines exposure per contract and is calculated as:
Nominal Value = ctVal * ctMult (in ctValCcy)For example, given the LTC-USD-SWAP contract:
{
"instType": "SWAP",
"instId": "LTC-USD-SWAP",
"ctVal": "10",
"ctMult": "1",
"ctValCcy": "USD"
}The nominal value is 10 * 1 = 10 USD.
This calculation applies universally across delivery, perpetual, and options contracts, enabling consistent risk assessment.
Checking Account Balance and Configuration
Accurate trading requires awareness of your financial position. Retrieve your current balance:
import okx.Account as Account
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_account_balance()
print(result)Ensure you're in the correct account mode for derivatives trading by checking acctLv:
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 mode"))Only modes 2–4 support derivatives trading.
Setting Leverage Strategically
Leverage amplifies both gains and losses. Platforms support up to 125x leverage, depending on the instrument. Key concepts include:
- Maximum Leverage: Highest multiplier allowed.
- Initial Margin Rate (IMR): Minimum margin required to open a position.
- Maintenance Margin Rate (MMR): Threshold below which liquidation occurs.
For a $3,000 ETHUSDT perpetual contract at 75x leverage:
- IMR = 1/75 ≈ 1.3%
- MMR ≥ 0.8%
Use the following code to set leverage:
# Cross-margin mode
accountAPI.set_leverage(instId="BTC-USDT-SWAP", lever="5", mgnMode="cross")
# Isolated margin, long position only
accountAPI.set_leverage(
instId="BTC-USDT-SWAP",
lever="5",
posSide="long",
mgnMode="isolated"
)Note: posSide is only valid in isolated margin mode with long/short position mode enabled.Managing Position Modes
Two primary position modes exist:
- Long/Short Mode: Separate long and short positions.
- Buy/Sell (Net) Mode: Net position per contract.
Switch modes via API:
accountAPI.set_position_mode(posMode="long_short_mode")Or adjust settings via the web interface under Settings.
Order Placement Scenarios
| Action | side | posSide |
|---|---|---|
| Open long | buy | long |
| Open short | sell | short |
| Close long | sell | long |
| Close short | buy | short |
Placing Limit Orders
Buy 100 BTC-USDT-SWAP 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"
)Placing Market Orders
Execute immediately at current market price:
result = tradeAPI.place_order(
instId="BTC-USDT-SWAP",
tdMode="isolated",
side="buy",
posSide="net",
ordType="market",
sz="100"
)Always verify response codes:
if result["code"] == "0":
print("Order successful, ID:", result["data"][0]["ordId"])
else:
print("Failed:", result["data"][0]["sMsg"])👉 Learn how to automate your first crypto trade with simple scripts
Monitoring and Managing Orders
Querying Order Details
Retrieve status using ordId or clOrdId:
result = tradeAPI.get_order(instId="BTC-USDT-SWAP", ordId="505073046126960640")
print(result)Canceling Orders
Cancel pending orders programmatically:
result = tradeAPI.cancel_order(instId="BTC-USDT-SWAP", ordId="505073046126960640")Amending Orders
Modify quantity or price:
result = tradeAPI.amend_order(
instId="BTC-USDT-SWAP",
ordId="505073046126960640",
newSz="80"
)Viewing Active and Historical Orders
Fetch open orders:
result = tradeAPI.get_order_list()Retrieve recent history (last 7 days):
result = tradeAPI.get_orders_history(instType="SWAP")For older records (up to 3 months):
result = tradeAPI.get_orders_history_archive(instType="SWAP")Transaction Details and Position Tracking
Get recent fills:
result = tradeAPI.get_fills()Access archived fills:
result = tradeAPI.get_fills_history(instType="SWAP")Check current positions:
result = accountAPI.get_positions()In net mode, only net exposure is shown. In long/short mode, positions are displayed independently. Track unrealized P&L via the upl parameter.
Frequently Asked Questions
Q: What types of derivatives can I trade using the OKX API?
A: You can trade three main types: delivery futures, perpetual swaps, and options. Each supports full API integration for automation.
Q: How do I switch between net and long/short position modes?
A: Use the set_position_mode(posMode="long_short_mode") or "net_mode" function. Note that switching may require closing existing positions.
Q: Can I use custom order IDs?
A: Yes. Use the clOrdId parameter when placing or querying orders for easier tracking in your system.
Q: Is it safe to store API keys in Jupyter Notebooks?
A: Never hardcode sensitive credentials. Use environment variables or secure secret managers to protect your keys.
Q: What happens if my margin falls below MMR?
A: Your position will be partially or fully liquidated to prevent negative equity. Monitor marginRatio regularly.
Q: Can I backtest strategies before live trading?
A: Yes. Use historical market data from the MarketData API in Jupyter to simulate and refine strategies risk-free.
👉 Start building intelligent trading systems with secure API access
Core Keywords
- derivatives trading
- Jupyter Notebook
- python-okx
- perpetual contracts
- API trading
- leverage settings
- contract nominal value
- automated trading
By combining interactive computing with powerful financial APIs, traders gain unprecedented control over their strategies. From market analysis to execution and monitoring, Jupyter Notebook serves as an ideal environment for next-generation digital asset trading.