Jupyter Notebook is a powerful tool widely used for data analysis, algorithmic development, and automation tasks. For traders and developers, it offers an interactive environment to execute financial strategies, analyze market data, and automate trading operations. This guide walks you through the steps to perform spot trading on a cryptocurrency exchange using the OKX API within a Jupyter Notebook.
Setting Up Jupyter Notebook
Before diving into trading, ensure you have Jupyter Notebook installed and running on your system. Jupyter supports Windows, macOS, and Linux operating systems. You can install it via Python’s package manager, pip, by running:
pip install notebookOnce installed, launch Jupyter Notebook from your terminal or command prompt:
jupyter notebookThis command starts a local server and opens the notebook interface in your default web browser.
Installing the Required Python Package
To interact with the OKX API, you need the official Python library. Install it directly in your Jupyter Notebook cell or terminal using:
pip install python-okxThis package provides a comprehensive set of modules for accessing account data, market data, and executing trades.
Generating API Keys
API keys are essential for authenticating your requests. Follow these steps to create them:
- Log in to your OKX account.
- Navigate to Profile > API Management.
- Click Create API Key.
- Select Trade under Permissions to enable trading capabilities.
- Securely store the generated API key, secret key, and passphrase.
In your Jupyter Notebook, initialize these credentials as variables:
api_key = "your_api_key_here"
secret_key = "your_secret_key_here"
passphrase = "your_passphrase_here"Importing OKX Modules
The python-okx library includes multiple modules corresponding to different API services. Key modules include:
Tradefor order managementMarketDatafor real-time pricesAccountfor balance and configurationFundingfor deposits and withdrawals
To import the Trade module, use:
import okx.Trade as TradeRetrieving Market Data
Access real-time market data to inform your trading decisions. The following code fetches tickers for all spot trading pairs:
import okx.MarketData as MarketData
flag = "1" # Use "0" for live trading, "1" for demo
market_data_api = MarketData.MarketAPI(flag=flag)
tickers = market_data_api.get_tickers(instType="SPOT")
print(tickers)Checking Available Trading Pairs
List all available spot instruments to identify tradable assets:
import okx.Account as Account
account_api = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
instruments = account_api.get_instruments(instType="SPOT")
print(instruments)Viewing Account Balance
Monitor your account balance to manage funds effectively. The response includes total equity (totalEq) and detailed balances per currency (cashBal, frozenBal):
balance = account_api.get_account_balance()
print(balance)Understanding Account Modes
OKX supports four account modes:
- Simple/Spot Mode: Basic trading with no margin.
- Single-Currency Margin: Margin trading per currency.
- Multi-Currency Margin: Cross-currency margin.
- Portfolio Margin: Advanced risk management.
Check your current mode using:
config = account_api.get_account_config()
if config['code'] == "0":
acct_lv = config["data"][0]["acctLv"]
modes = {
"1": "Simple mode",
"2": "Single-currency margin",
"3": "Multi-currency margin",
"4": "Portfolio margin"
}
print(modes.get(acct_lv, "Unknown mode"))For spot trading in simple mode, set tdMode="cash". In margin modes, use tdMode="cross".
Placing Spot Orders
Limit Orders
Specify a price to buy or sell an asset. Example: Buy 0.01 BTC at 19,000 USDT.
trade_api = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)
order = trade_api.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="limit",
px="19000",
sz="0.01"
)
print(order)Market Orders
Execute orders at the current market price. Example: Buy BTC worth 100 USDT.
order = trade_api.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
tgtCcy="quote_ccy" # Size in quote currency (USDT)
)
print(order)Using Client Order ID
Assign a custom ID (clOrdId) to track orders easily:
order = trade_api.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
clOrdId="my_custom_id_003"
)Managing Orders
Checking Order Details
Retrieve order status using ordId or clOrdId:
order_details = trade_api.get_order(instId="BTC-USDT", ordId="497819823594909696")
print(order_details)Canceling Orders
Cancel an open order by its ID:
cancel_result = trade_api.cancel_order(instId="BTC-USDT", ordId="489093931993509888")
print(cancel_result)Modifying Orders
Amend order parameters like size or price:
amend_result = trade_api.amend_order(
instId="BTC-USDT",
ordId="489103565508685824",
newSz="0.012"
)
print(amend_result)Reviewing Order History
Recent Orders (7 Days)
Fetch order history from the past week:
recent_orders = trade_api.get_orders_history(instType="SPOT")
print(recent_orders)Historical Orders (3 Months)
Access archived orders up to three months old:
old_orders = trade_api.get_orders_history_archive(instType="SPOT")
print(old_orders)Advanced Integration and Automation
Jupyter Notebook enables complex strategies like backtesting, automated trading, and real-time analytics. Combine market data APIs with order execution to build algorithmic systems. For instance, create a loop that monitors prices and executes trades based on technical indicators.
👉 Explore advanced trading strategies
Frequently Asked Questions
Q: Is Jupyter Notebook free to use?
A: Yes, Jupyter Notebook is open-source and free for personal and commercial use.
Q: Can I trade on live markets using the demo flag?
A: No. Setting flag="1" limits actions to the demo environment. Use flag="0" for live trading.
Q: How do I secure my API keys?
A: Never share keys or commit them to version control. Use environment variables or encrypted secrets.
Q: What order types are available?
A: OKX supports limit, market, stop-limit, and trailing orders, among others.
Q: How can I handle API rate limits?
A: Implement error handling and retry logic with exponential backoff to avoid exceeding limits.
Q: Where can I find complete API documentation?
A: Refer to the official OKX API documentation for detailed endpoints and parameters.
Conclusion
Jupyter Notebook provides a flexible environment for traders to automate spot trading strategies using the OKX API. By following this guide, you can set up your environment, authenticate requests, execute orders, and manage your portfolio programmatically. Always test strategies in a demo environment before deploying live capital.