How to Trade Derivatives Using Jupyter Notebook

·

Automating derivative trading with code has never been easier. By combining the power of Jupyter Notebook with a robust trading API, you can execute advanced strategies, monitor positions in real time, and manage risk efficiently—all from a single interactive environment. This guide walks you through how to use Jupyter Notebook to trade derivatives on OKX, leveraging Python-based API calls for seamless automation.

Whether you're new to algorithmic trading or looking to refine your workflow, this tutorial delivers practical steps with real code examples—perfect for developers, quants, and tech-savvy traders.


Types of Derivatives Available

OKX supports three major types of derivatives for trading:

Each product offers unique benefits depending on your strategy and market outlook. In this guide, we'll focus on Perpetual Swaps, one of the most popular instruments due to their continuous trading nature and high leverage options.

👉 Start building your automated trading bot today with powerful tools


Fetching Market Data

Before placing any trade, it’s essential to access real-time market data. You can retrieve ticker information using the MarketAPI from the OKX SDK.

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)

This returns live tickers for all perpetual swap contracts. Replace "SWAP" with "EXPIRY" or "OPTION" to fetch data for other derivative types.


Listing Tradable Pairs

To see all available perpetual swap pairs, use the PublicAPI to get instrument details:

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 Notional Value

Each derivative contract has a notional value determined by two key parameters:

Notional Value = ctVal × ctMult (in ctValCcy)

For example, the LTC-USD-SWAP contract has:

So its notional value is 10 USD per contract.


Checking Account Balance

To ensure sufficient funds before trading, 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)

This returns all asset balances across your account, including available margin for derivatives.


Understanding Account Modes for Derivatives Trading

OKX offers four account modes:

  1. Spot Mode
  2. Spot and Futures Mode
  3. Multi-Currency Margin Mode
  4. 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"))

Ensure you're in an eligible mode before placing derivative orders.


Setting Leverage

Leverage amplifies both potential gains and losses. OKX allows up to 125x leverage on perpetual swaps, depending on the asset and position size.

Key terms:

Example: Setting 5x Leverage

You can set leverage at different levels:

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

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

👉 Maximize your trading efficiency with smart leverage control


Placing Orders: Position Modes Explained

There are two position modes for futures and perpetuals:

Switch between them via API:

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

Order Placement Parameters

ScenariosideposSide
Open longbuylong
Open shortsellshort
Close longselllong
Close shortbuyshort

In net mode, posSide="net" is used; otherwise, specify long or short.

Placing a Limit Order

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

Placing a Market Order

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

Monitoring and Managing Orders

Get Details of a Specific Order

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

Cancel an Order

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

Modify an Existing Order

Update order size or price:

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

Retrieving Order History and Trade Fills

Open Orders

result = tradeAPI.get_order_list()

Recent Order History (Last 7 Days)

result = tradeAPI.get_orders_history(instType="SWAP")

Archived Orders (Last 3 Months)

result = tradeAPI.get_orders_history_archive(instType="SWAP")

Transaction Details (Last 3 Days)

result = tradeAPI.get_fills()

Historical Fills (Last 3 Months)

result = tradeAPI.get_fills_history(instType="SWAP")

Checking Open Positions

Retrieve all active positions:

result = accountAPI.get_positions()

Track key metrics like:

This helps monitor risk exposure in real time.


Frequently Asked Questions (FAQ)

What is a perpetual swap?

A perpetual swap is a derivative contract without an expiry date, allowing traders to hold positions indefinitely. It uses a funding rate mechanism to keep the contract price aligned with the underlying index.

Can I automate trading strategies using Jupyter Notebook?

Yes. Jupyter Notebook integrates seamlessly with Python libraries and REST/WebSocket APIs, making it ideal for developing, testing, and deploying algorithmic trading bots.

How do I avoid liquidation when trading with leverage?

Maintain adequate margin by monitoring your maintenance margin ratio (MMR). Avoid over-leveraging, set stop-losses, and regularly check unrealized P&L and liquidation prices.

What’s the difference between cross and isolated margin?

In cross margin, all available balance in your account acts as collateral. In isolated margin, only a fixed amount is allocated to a position—limiting both risk and reward.

Is demo trading available for testing?

Yes. Set flag = "1" in your API configuration to use OKX’s demo trading environment—perfect for testing strategies risk-free.

How secure is API-based trading?

Use strong passwords, enable two-factor authentication (2FA), restrict IP access, and never expose your API keys in public repositories or notebooks.


👉 Unlock advanced trading automation with secure API access

By integrating Jupyter Notebook with OKX’s comprehensive API suite, you gain full control over your derivative trading workflow—from strategy design to execution and risk management. With support for real-time data, order management, and portfolio tracking, this setup empowers both novice and experienced traders to build smarter, faster, and more reliable systems.

Whether you're backtesting strategies or running live trades, the combination of Python and OKX opens endless possibilities in the world of digital asset derivatives.