How to Trade Spot Using Jupyter Notebook: A Comprehensive Guide

·

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:

👉 Explore Jupyter Notebook setup


2. Installing the python-okx Package

  1. Open Jupyter Notebook.
  2. Run !pip install python-okx in a code cell or terminal.

3. Creating API Keys

  1. Log in to your OKX account and navigate to Demo Trading under the Trade tab.
  2. Generate API keys in the API Management section.
  3. Securely store your api_key, secret_key, and passphrase.

Code Example:

api_key = "xxxxx"  
secret_key = "xxxxx"  
passphrase = "xxxxxx"  

4. Importing OKX Modules

The python-okx library supports REST API modules like:

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:

  1. Simple Spot (acctLv = "1")
  2. Single-Currency Margin (acctLv = "2")
  3. Multi-Currency Margin (acctLv = "3")
  4. 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


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.

👉 Advanced API examples


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!