Exploring the Okex API with Python
The Okex exchange, one of the leading cryptocurrency exchanges globally, offers a powerful and comprehensive set of APIs that allow developers to interact with its trading platform programmatically. This article will guide you through setting up an account on Okex, obtaining API keys, and using these keys to perform various operations, including fetching order book information, placing trades, and more, all from the comfort of a Python script.
Setting Up Your Account
First things first, if you don't have an account with Okex, head over to their website ([https://www.okex.com/](https://www.okex.com/)) and create one. Once your account is up and running, log in and navigate to the [API page](https://www.okex.com/en/fapi/) under 'More APIs' on the left sidebar. Here, you'll find a button that says "Register API"; click it.
You will need to fill out some basic information, such as your name and email address. After submitting this information, Okex will send an email with an activation link to the provided email address. Clicking this link will activate your API account.
Obtaining Your API Keys
Once your API account is activated, you can generate API keys by going back to the 'More APIs' section and clicking "Register API Key" under 'FAPI'. You'll be asked to provide a key name (this could be anything descriptive) and then click on the "Generate ApiKey" button.
You will now have two keys: `access_key` and `secret_key`, which are very important as they grant access to your Okex API account. Store these keys securely; do not share them with others or post them online.
Writing Your First Python Script
Now that you have your API keys, let's write our first script. We will use the `requests` library in Python for sending HTTP requests and fetching data from Okex's APIs. If you haven't installed it yet, run `pip install requests` to do so.
First, import the necessary libraries:
```python
import requests
import time
from datetime import datetime
```
Then, set up your API keys:
```python
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
```
Replace `YOUR_ACCESS_KEY` and `YOUR_SECRET_KEY` with the actual values you obtained.
To sign a request, Okex uses HMAC-SHA256 algorithm, which requires both your access key and secret key. Here's how to generate the signature:
```python
import hmac
import hashlib
import base64
import json
def get_sign(method, uri, query):
timestamp = str(int(time.time()))
message = method + uri + timestamp + query
signature = hmac.new(base64.b64decode(secret_key), message.encode('utf-8'), hashlib.sha256).digest()
return base64.b64encode(signature)
```
This function takes the HTTP method (`method`), endpoint URL (`uri`), and query parameters as inputs and returns a signature for that request.
Fetching Order Book Information
Let's fetch the order book information for Ethereum (ETH/USD) on Okex:
```python
def fetch_orderbook(symbol):
url = "https://fapi.okex.com/api/v1/orderbook/level2?symbol=" + symbol
method = 'GET'
query = ''
signature = get_sign(method, url, query)
headers = {
'Okex-Timestamp': timestamp,
'Okex-API-Key': access_key,
'Okex-Signature': signature.decode('utf-8'),
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
return response.json()
```
Call `fetch_orderbook('ETH-USD')` to get the order book data for Ethereum.
Placing a Trade
To place a trade using Okex's API, you would need a bit more information on how to sign requests with your secret key and add authentication headers. The script below shows an example of placing a limit buy/sell order:
```python
def create_order(symbol, type, side, amount, price):
url = "https://fapi.okex.com/api/v1/trade/" + symbol + "/?type="+str(type)+"&side="+str(side)+"&amount="+str(amount)+"&price="+str(price)
method = 'POST'
query = ''
signature = get_sign(method, url, query)
headers = {
'Okex-Timestamp': timestamp,
'Okex-API-Key': access_key,
'Okex-Signature': signature.decode('utf-8'),
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers)
return response.json()
```
Call `create_order('ETH-USD', 0, 'BUY', amount, price)` to place a limit buy order for the specified symbol and parameters.
Conclusion
Okex API provides developers with a wide array of options to interact with its trading platform using Python, from fetching real-time market data to placing trades. The above examples are just the tip of the iceberg; there's much more you can do with Okex APIs, such as canceling orders, fetching funding rates, and more. Always remember to use API keys responsibly and securely; don't share your keys or store them in insecure places.