Understanding the OKX API with Python
In the world of cryptocurrency trading, platforms like Binance and OKEx offer not only a way to trade but also APIs that allow developers to access powerful functionalities such as real-time market data, placing orders automatically, or even pulling historical data. In this article, we'll focus on using the OKX API with Python, showcasing how to connect to the platform, fetch order book data, place trades, and monitor trade history.
The Basics of OKX API Access
OKEx (now rebranded as OKX) offers an Application Programming Interface (API) that can be accessed using RESTful APIs or WebSocket for real-time updates. To use the OKX API with Python, you first need to sign up on the platform and then access their API documentation through your account dashboard.
Step 1: Sign Up and Access API Key
Signing up on OKX involves providing basic personal information and setting up a trading account. Once logged in, navigate to "API" under the "Trade" section (or simply search for "API"). You'll find an option to generate API keys where you can create your key pair with read-only access first for testing purposes. For full access, you might need to contact OKX support due to security reasons.
Step 2: Install and Set Up Python Environment
Ensure that you have Python 3.6 or higher installed on your system. You'll also need the `requests` library for making HTTP requests. If not already installed, add it by running:
```bash
pip install requests
```
Create a new file with a `.py` extension (e.g., `okx_api.py`) to write your Python script.
Step 3: Implementing the API Connection
Let's start by connecting to OKX and fetching an order book for Bitcoin/USDT trading pair. We'll use the public API endpoint as a starting point, which doesn't require API keys for read-only access.
```python
import requests
URL = "https://api.okx.com"
PATH = "/v5/market/orderbook/level2?instId=BTC-USDT&type=Rfq"
HEADERS = {"OKX-API-KEY": "your_api_key", "OKX-ACCESS-SIGN": "your_access_sign",
"OKX-ACCESS-TIMESTAMP": "1609459217.308", "OKX-PAYLOAD": ""}
def fetch_order_book():
response = requests.get(url=URL + PATH, headers=HEADERS)
return response.json()
order_book = fetch_order_book()
print(order_book)
```
Replace `"your_api_key"` and `"your_access_sign"` with your actual API key and access sign obtained from OKX. The timestamp is also a part of the signature calculation, so it's crucial to use the correct format (`1609459217.308`).
Step 4: Placing Trades and Order Types
OKX allows users to place market orders or limit orders. For simplicity, let's focus on placing a market order for buying Bitcoin/USDT using the POST method with `requests`.
```python
TRADE_URL = "/v5/order/place"
MARKET_BUY_PATH = {"side": "buy", "instId": "BTC-USDT", "type": "limit", "price": "70000", "size": "0.1"}
def place_market_order():
response = requests.post(url=URL + TRADE_URL, headers=HEADERS, json=[MARKET_BUY_PATH])
return response.json()
trade_result = place_market_order()
print(trade_result)
```
This script sends a limit order to buy 0.1 BTC at the price of 70000 USDT. The result is a trade ID that can be used for further tracking or cancellation if necessary.
Step 5: Monitoring Trade History
Finally, let's retrieve and print the trading history for the current account using OKX API.
```python
TRADE_HISTORY = "/v5/trade/current"
TRADE_HISTORY_PATH = {"instId": "BTC-USDT"}
def fetch_trades():
response = requests.get(url=URL + TRADE_HISTORY, headers=HEADERS, params=TRADE_HISTORY_PATH)
return response.json()['body']['tradeTicks']
trades = fetch_trades()
print(trades)
```
This will print out a list of trade ticks for the BTC-USDT pair, including information like price, size (quantity), and timestamp.
Conclusion
In this article, we've explored the basics of using OKX API with Python, covering from generating an API key to placing trades and monitoring trade history. This is a brief overview, and there are many more features available in the OKX API such as fetching user account information, setting up stop orders, and streaming real-time data via WebSocket. Always refer to the official OKX API documentation for the most accurate and detailed usage instructions.
As with any cryptocurrency trading platform or exchange's API, it's crucial to understand that your actions are subject to the regulations of both the country in which you reside and the regulatory environment where the exchange is licensed. Furthermore, always ensure to secure your keys properly as they can have significant implications for your account.