This tutorial introduces you to the fundamentals of executing spot trades programmatically using the python-okx library within a Jupyter Notebook environment. It provides a step-by-step walkthrough for setting up your development environment, interacting with market data, and managing your trades.
Prerequisites and Setup
Before diving into trading, you need to set up your environment correctly. This involves installing the necessary package and securing your API credentials.
Installing the python-okx Package
The first step is to install the official python-okx package. This library provides a comprehensive interface for interacting with OKX's API. You can install or upgrade it using pip. Simply run the following command in a cell within your Jupyter Notebook or in your system's terminal:
pip install python-okx --upgradeGenerating Your API Keys
To access the API, you must generate a set of API keys from your OKX account. After logging in, navigate to your 'Account' settings and select the 'API' section to create a new key. For practice and testing, it is highly recommended to use the 'Demo Trading' feature found under the 'Assets' tab. This allows you to experiment without risking real funds.
When creating your key, ensure you select the 'Trade' permission from the menu. Once generated, you will be provided with three crucial pieces of information: an API Key, a Secret Key, and a Passphrase. Store these credentials securely. You will use them to authenticate your API requests within your notebook by instantiating them as variables:
api_key = "your_api_key_here"
secret_key = "your_secret_key_here"
passphrase = "your_passphrase_here"Importing Modules and Accessing Market Data
The python-okx library is structured into several modules that correspond to different areas of the OKX API, such as Trade, Account, and MarketData.
Importing the Necessary Modules
To start, you need to import the specific modules you plan to use. For most trading operations, the Trade and MarketData modules are essential. Here’s how to import them:
import okx.Trade as Trade
import okx.MarketData as MarketDataFetching Real-Time Market Data
Accessing current market information is a fundamental step before placing any trades. The MarketData module allows you to retrieve real-time ticker information for various instruments, including spot trading pairs.
The following code snippet demonstrates how to initialize the MarketAPI and fetch ticker data for all spot instruments. The flag parameter is set to '1' for demo (simulated) trading and '0' for live trading.
flag = "1" # Set to 1 for demo trading, 0 for live trading
marketDataAPI = MarketData.MarketAPI(flag=flag, api_key=api_key, secret_key=secret_key, passphrase=passphrase)
result = marketDataAPI.get_tickers(instType="SPOT")
print(result)👉 View real-time market data tools
Managing Your Account and Orders
Understanding your account configuration and balance is crucial for successful trading.
Checking Your Account Balance
Your available and frozen balances for each currency can be retrieved using the Account module. Key parameters to monitor include cashBal, frozenBal for individual currencies, and totalEq for your total equity value.
Understanding Account Modes
The unified trading account offers four distinct modes: Simple, Single-currency margin, Multi-currency margin, and Portfolio margin. The trading mode (tdMode) you must use for spot trading depends on your overall account configuration:
- For Simple and Single-currency margin modes, set
tdMode='cash'. - For Multi-currency and Portfolio margin modes, set
tdMode='cross'.
You can check your current account level (acctLv) through the API to determine which mode you are using.
Placing Spot Orders
You can place different types of orders, such as limit and market orders.
Placing a Limit Order:
A limit order allows you to specify the exact price at which you want to buy or sell. The following example places an order to buy 0.01 BTC at a price of 19,000 USDT.
Placing a Market Order:
A market order executes immediately at the best available current market price. You can specify the quantity of the base currency to buy or sell. Furthermore, the tgtCcy parameter allows you to define the unit of the size parameter (sz). Setting it to the quote currency (e.g., USDT) means you are specifying how much of the quote currency you want to spend or receive, rather than the amount of the base currency.
Using Client Order IDs
When placing an order, you can assign your own unique identifier using the clOrdId parameter. This client-supplied order ID can later be used to cancel, modify, or query the status of the order, providing a reliable way to track your orders with your own system.
Managing Your Orders
The API provides full functionality for order management:
- Checking Order Details: You can retrieve the status and details of a specific order using either the exchange-assigned
ordIdor your ownclOrdId. - Canceling Orders: Open orders can be canceled using either their
ordIdorclOrdId. - Modifying Orders: You can amend certain parameters of existing open orders, again using either identifier.
- Viewing Order Lists: You can fetch a list of your current open orders or query your historical orders from the past 7 days or even the past 3 months.
Frequently Asked Questions
What is the difference between live trading and demo trading?
Live trading uses real funds and executes orders on the actual market, while demo trading uses simulated funds on a test environment. It is crucial to set the flag parameter correctly in your API instance ('0' for live, '1' for demo) to avoid accidental real-money trades during development and testing.
How do I choose the right tdMode for spot trading?
Your choice of tdMode depends on your account configuration. If your account is in Simple or Single-currency margin mode, you must use tdMode='cash'. If it is in Multi-currency or Portfolio margin mode, you must use tdMode='cross'. Using the incorrect mode will result in an API error.
What is the purpose of the tgtCcy parameter?
The tgtCcy parameter defines the currency unit for the order size (sz). For a BTC-USDT pair, setting tgtCcy to the base currency (BTC) means you are specifying how many Bitcoin to buy. Setting it to the quote currency (USDT) means you are specifying how much USDT to spend buying Bitcoin. This provides flexibility in how you define your order amounts.
👉 Explore more trading strategies
Is it safe to store my API keys in a Jupyter Notebook?
For development and testing, it is acceptable, but you should never commit a notebook with live keys to public version control. For production use, consider using environment variables or a secure secrets management service to handle your credentials instead of hard-coding them.
Can I use this library outside of Jupyter Notebook?
Yes, absolutely. The python-okx package is a standard Python library that can be used in any Python environment, including scripts, web applications, and other interactive environments like Google Colab.
What should I do if I get an API error?
First, carefully read the error message and code returned by the API. Common issues include incorrect permissions on your API key, invalid parameter values (like a wrong tdMode), or using demo keys on the live trading environment. The official API documentation provides detailed explanations for error codes.