How to Perform Spot Trading Using Jupyter Notebook with OKX API

·

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:

👉 Get started with Jupyter Notebook


2. Installing the python-okx Package

Install the python-okx library directly in your notebook:

!pip install python-okx

3. Creating API Keys for Demo Trading

  1. Sign in to OKX and navigate to Trade > Demo Trading.
  2. Generate API keys under Profile > API Management.
  3. Note your api_key, secret_key, and passphrase securely.
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


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?

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.