Trading in the cryptocurrency market has evolved from manual exchanges to algorithmic and automated systems. One powerful way to implement advanced trading strategies is by using Jupyter Notebook in combination with a robust exchange API—such as OKX. This guide walks you through setting up spot trading in Jupyter Notebook, integrating real-time market data, placing orders, managing balances, and more—all through clean, executable Python code.
Whether you're a data scientist, developer, or crypto trader, this tutorial helps you harness the power of interactive coding for efficient and precise spot trading.
Setting Up Your Environment
Before diving into trading logic, ensure your development environment supports Python and Jupyter Notebook.
👉 Get started with advanced trading tools today
Jupyter Notebook is an open-source web application that allows you to create and share documents containing live code, equations, visualizations, and narrative text. It's ideal for testing trading algorithms, analyzing market trends, and executing trades programmatically.
You can install Jupyter via pip:
pip install notebookThen launch it:
jupyter notebookInstalling the OKX Python SDK
To interact with the OKX exchange programmatically, use the official python-okx library.
Run this command inside a Jupyter cell or terminal:
!pip install python-okxThis installs all necessary modules for account management, market data access, and trade execution.
Creating API Keys on OKX
To authenticate your requests, generate secure API keys from your OKX account.
- Log in to your OKX account and navigate to Trade > Demo Trading to test without risk.
- Go to Profile > API to create new keys.
- Click Create API and choose whether to assign it to a main or sub-account.
- Enable Trade permissions under Permissions.
- Safely store the generated API Key, Secret Key, and Passphrase.
Now define them in your notebook:
api_key = "your_api_key_here"
secret_key = "your_secret_key_here"
passphrase = "your_passphrase_here"🔒 Never share or commit these values publicly. Use environment variables in production.
Importing Essential OKX Modules
The python-okx SDK includes modular access to different parts of the platform:
Trade– Place and manage ordersMarketData– Fetch real-time pricingAccount– Check balances and configurationsFunding– Deposit/withdraw assets
Import the required modules:
import okx.Trade as Trade
import okx.MarketData as MarketData
import okx.Account as AccountInitialize the trade interface:
flag = "1" # "1" for demo trading, "0" for live
tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)Fetching Real-Time Market Data
Stay informed with up-to-the-second pricing across all spot pairs.
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SPOT")
print(result)This returns active spot trading pairs like BTC-USDT, ETH-USDT, etc., including best bid/ask prices and 24-hour volume.
Listing Available Spot Trading Pairs
Want to know which coins you can trade?
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_instruments(instType="SPOT")
for instrument in result['data']:
print(instrument['instId'])This outputs all available spot pairs supported by OKX.
Checking Your Account Balance
Monitor your holdings before placing any trade.
result = accountAPI.get_account_balance()
print(result)For spot trading in cash mode, check:
cashBal: Available balancefrozenBal: Locked fundstotalEq: Total equity in quote currency
Understanding Margin Modes
OKX supports four margin modes:
- Spot Mode
- Spot & Futures Mode
- Multi-currency Margin Mode
- Portfolio Margin Mode
Use tdMode when placing orders:
"cash"for isolated spot trading"cross"for cross-margin positions
👉 Explore powerful trading automation features
Checking Current Account Mode
Identify your active margin level using acctLv:
result = accountAPI.get_account_config()
if result['code'] == "0":
acctLv = result["data"][0]["acctLv"]
modes = {
"1": "Simple Mode",
"2": "Single-currency Margin",
"3": "Multi-currency Margin",
"4": "Portfolio Margin"
}
print("Current Mode:", modes.get(acctLv, "Unknown"))Placing Spot Orders
Limit Order
Buy 0.01 BTC at $19,000:
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="limit",
px="19000",
sz="0.01"
)
if result["code"] == "0":
print("Order placed successfully! Order ID:", result["data"][0]["ordId"])
else:
print("Failed:", result["data"][0]["sMsg"])Market Order
Buy $100 worth of BTC at current market price:
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
tgtCcy="quote_ccy"
)
print(result)Here, tgtCcy="quote_ccy" means sz refers to USDT (quote currency). For sell orders, it defaults to base currency (BTC).
Using Custom Client Order ID (clOrdId)
Assign your own identifier:
result = tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
clOrdId="my_buy_order_001"
)Use clOrdId later to retrieve or cancel the order.
Managing Orders
Get Order Details
By ordId:
result = tradeAPI.get_order(instId="BTC-USDT", ordId="497819823594909696")By clOrdId:
result = tradeAPI.get_order(instId="BTC-USDT", clOrdId="my_buy_order_001")Cancel an Order
result = tradeAPI.cancel_order(instId="BTC-USDT", ordId="489093931993509888")Supports clOrdId too.
Amend (Modify) an Order
Change order size:
result = tradeAPI.amend_order(
instId="BTC-USDT",
ordId="489103565508685824",
newSz="0.012"
)View Open and Historical Orders
Open Orders
result = tradeAPI.get_order_list()
print(result)Recent Orders (Last 7 Days)
result = tradeAPI.get_orders_history(instType="SPOT")Archived Orders (Last 3 Months)
result = tradeAPI.get_orders_history_archive(instType="SPOT")Frequently Asked Questions (FAQ)
Q: Can I use Jupyter Notebook for live trading?
A: Yes, but ensure secure handling of API keys and test strategies thoroughly in demo mode first.
Q: What does flag = "1" mean?
A: It enables demo trading. Set to "0" for live market execution.
Q: Is automated trading allowed on OKX?
A: Yes, via API access. Just comply with rate limits and terms of service.
Q: How do I protect my API keys in Jupyter?
A: Use environment variables or .env files instead of hardcoding credentials.
Q: Can I run this script outside Jupyter?
A: Absolutely. The same code works in any Python environment—scripts, web apps, or cloud functions.
Q: Does OKX support WebSocket for real-time updates?
A: Yes. The python-okx library also supports WebSocket streaming for live order books and trades.
👉 Unlock full potential with OKX API trading tools
With Jupyter Notebook and the OKX API, you gain precision control over your spot trading strategy. From fetching market data to executing complex order workflows—all within a flexible, reproducible environment—you're equipped to build smarter trading systems.
Start experimenting in demo mode, refine your logic, then scale confidently into live markets.