Learn how to execute spot trades by leveraging Python library functions in Jupyter Notebook—an ideal environment for algorithmic trading and data analysis.
1. Running Python Snippets in Jupyter Notebook
Jupyter Notebook is a versatile tool for Python-based development and data analysis. It runs on Windows, macOS, or Linux. To get started:
- Install Jupyter via
pip install jupyterlab. - Launch the server with
jupyter notebookin your terminal.
👉 Explore Jupyter Notebook setup
2. Installing the python-okx Package
- Open Jupyter Notebook.
- Run
!pip install python-okxin a code cell or terminal.
3. Creating API Keys
- Log in to your OKX account and navigate to Demo Trading under the Trade tab.
- Generate API keys in the API Management section.
- Securely store your
api_key,secret_key, andpassphrase.
Code Example:
api_key = "xxxxx"
secret_key = "xxxxx"
passphrase = "xxxxxx" 4. Importing OKX Modules
The python-okx library supports REST API modules like:
TradeMarketDataAccount
Example:
import okx.Trade as Trade 5. Accessing Market Data
Fetch real-time tickers for spot instruments:
import okx.MarketData as MarketData
marketDataAPI = MarketData.MarketAPI(flag="1") # Demo mode
result = marketDataAPI.get_tickers(instType="SPOT")
print(result) 6. Retrieving Trading Pairs
List available spot instruments:
import okx.Account as Account
accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, "1")
result = accountAPI.get_instruments(instType="SPOT")
print(result) 7. Checking Account Balance
result = accountAPI.get_account_balance()
print(result["data"]["details"]["BTC"]["cashBal"]) # Example: BTC balance 8. Margin Trading Modes
OKX supports four margin modes:
- Simple Spot (
acctLv = "1") - Single-Currency Margin (
acctLv = "2") - Multi-Currency Margin (
acctLv = "3") - Portfolio Margin (
acctLv = "4")
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"
)10. Managing Orders
- Cancel Order: Use
ordIdorclOrdId. - Modify Order: Adjust
newSzornewPx. - View History: Fetch 7-day or 3-month archives.
FAQ
Q1: Is Jupyter Notebook free to use?
A: Yes! It’s open-source and supports Python/R/Julia.
Q2: How secure are OKX API keys?
A: API keys are encrypted. Never share your secret_key.
Q3: Can I backtest strategies in Jupyter?
A: Absolutely—use libraries like pandas and backtrader.
Final Notes
This guide covers essential steps for spot trading via OKX APIs in Jupyter Notebook. For further details, refer to the OKX API Documentation. Happy trading!