Learn how to execute spot trading seamlessly by leveraging the python-okx library within a Jupyter Notebook. This guide covers setup, API integration, order placement, and advanced trading functionalities.
1. Setting Up Jupyter Notebook for Python Development
The Jupyter Notebook is a versatile tool for Python development and data analysis. Follow these steps to get started:
- Installation: Run Jupyter Notebook on Windows, macOS, or Linux via
pip install jupyter. - Launch: Start the server with
jupyter notebookin your terminal.
👉 Get started with Jupyter Notebook
2. Installing the python-okx Package
Install the python-okx library directly in your notebook:
!pip install python-okx3. Creating API Keys for Demo Trading
- Sign in to OKX and navigate to Trade > Demo Trading.
- Generate API keys under Profile > API Management.
- Note your
api_key,secret_key, andpassphrasesecurely.
api_key = "xxxxx"
secret_key = "xxxxx"
passphrase = "xxxxxx" 4. Importing OKX Modules
Import relevant modules like Trade or MarketData:
import okx.Trade as Trade
import okx.MarketData as MarketData 5. Accessing Market Data
Retrieve real-time tickers for spot trading:
flag = "1" # Demo trading mode
marketDataAPI = MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_tickers(instType="SPOT")
print(result) 6. Fetching Available Trading Pairs
List all spot instruments:
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)
result = accountAPI.get_instruments(instType="SPOT")
print(result) 7. Checking Account Balance
Monitor your balance for spot trading:
result = accountAPI.get_account_balance()
print(result["data"][0]["details"]) # Shows cashBal and frozenBal 8. Understanding Account Modes
OKX offers four account modes. Check your mode with:
result = accountAPI.get_account_config()
acctLv = result["data"][0]["acctLv"] # Returns 1-4 for different modes 9. Placing Spot Orders
Limit Order Example:
tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="limit",
px="19000",
sz="0.01"
) Market Order Example:
tradeAPI.place_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="market",
sz="100",
tgtCcy="quote_ccy"
) 👉 Master spot trading strategies
10. Managing Orders
- Cancel Order: Use
ordIdorclOrdId. - Amend Order: Adjust
newSzornewPx. - Order History: Fetch 7-day or 3-month records.
FAQ Section
How do I secure my API keys?
Store keys in environment variables or encrypted files—never hardcode them.
What’s the difference between cash and cross margin modes?
cash: Isolated funds for spot trading.cross: Shared margin across positions.
Can I automate trading strategies in Jupyter Notebook?
Yes! Use libraries like pandas for data analysis and scheduling tools like schedule.
Next Steps
Explore advanced features like block trading or portfolio margin by downloading our full Jupyter Notebook example. Join the OKX developer community for support.