OKEx API – An Introductory Guide

9 min read

Get 10-day Free Algo Trading Course

Last Updated on November 24, 2021

Table of contents:

  1. What is the OKEx API?
  2. What is OKEx?
  3. Is OKEx API free?
  4. Why should I use OKEx API?
  5. Why shouldn’t I use the OKEx API?
  6. Is OKEx API available in my country?
  7. What are the alternatives to using OKEx API?
  8. What clients are available for the OKEx API?
  9. How to get started with OKEx API?
  10. How to get trading pairs info with OKEx API?
  11. How to get Price Data with OKEx API?
  12. How to get historical data with OKEx API?
  13. How to access technical indicators such as the 20 SMA with the OKEx API?
  14. How to get Order Book data with OKEx API?
  15. How to get Trades Data with OKEx API?
  16. How to execute a trade on ETH when BTC hits a certain price with the OKEx API?
  17. How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the OKEx API?
  18. How to cancel orders with OKEx API?
  19. Full code

What is the OKEx API?

OKEx API is a method that allows traders to automatically trade cryptocurrencies on OKEx via code.

What is OKEx?

OKEx is an online cryptocurrency exchange platform that allows traders to trade over 250 coins and tokens. OKEx comes equipped with its own Cloud service and the ability to partake in Spot, Margin, and Futures trading.

Is OKEx API free?

Signing up for OKEx and testing out its API is completely free. The fees come in when you start trading with the OKEx API.

The fee structure of OKEx is more complex than most other online cryptocurrency exchanges. The first thing that dictates the fees is the type of user you are.

There are mainly two types of OKEx users – the regular and VIP ones. For regular users, the fee structure is based on the amount of your total OKB holding (OKEx native cryptocurrency). Here is how the SPOT fee tiers look:

<td style="text-align: center" data-sheets-value="{"1":2,"2":"< 500 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 5,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 5,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 5,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 5,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 5,000,000
Tier Total OKB holding 30-day trading volume(USD) Maker fee Taker fee
24h withdrawal limit (BTC)
Lv 1 0.08% 0.10% 500
Lv 2 ≥ 500 0.08% 0.10% 500
Lv 3 ≥ 1,000 0.07% 0.09% 500
Lv 4 ≥ 1,500 0.07% 0.09% 500
Lv 5 ≥ 2,000 0.06% 0.08% 500

For the VIP users, the fee structure is dictated by your monthly trading volume expressed in USD. There are 7 tiers for the VIP users and all follow a maker/taker fee structure. Below you can see how the fee structure looks:

Tier 30-day trading volume(USD) Maker fee Taker fee
24h withdrawal limit (BTC)
VIP 1 ≥ 5,000,000 0.06% 0.08% 600
VIP 2 ≥ 10,000,000 0.04% 0.08% 800
VIP 3 ≥ 50,000,000 0.02% 0.07% 1,000
VIP 4 ≥ 100,000,000 0.00% 0.06% 1,200
VIP 5 ≥ 200,000,000 0.00% 0.05% 1,500
VIP 6 ≥ 500,000,000 -0.01% 0.04% 1,800
VIP 7 ≥ 1,000,000,000 -0.01% 0.03% 2,000

 

The same thing goes for the Futures market but the fee structures are different. Below you will find two tables where the first one is for the regular users, while the second one is for the VIP users.

<td style="text-align: center" data-sheets-value="{"1":2,"2":"< 500 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 50,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 50,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 50,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 50,000,000 <td style="text-align: center" data-sheets-value="{"1":2,"2":"< 50,000,000
Tier Total OKB holding 30-day trading volume(USD) Maker fee Taker fee
24h withdrawal limit (BTC)
Lv 1 0.02% 0.05% 500
Lv 2 ≥ 500 0.02% 0.05% 500
Lv 3 ≥ 1,000 0.02% 0.04% 500
Lv 4 ≥ 1,500 0.02% 0.04% 500
Lv 5 ≥ 2,000 0.02% 0.03% 500

 

Tier 30-day trading volume(USD) Maker fee Taker fee
24h withdrawal limit (BTC)
VIP 1 ≥ 50,000,000 0.02% 0.03% 600
VIP 2 ≥ 100,000,000 0.01% 0.03% 800
VIP 3 ≥ 200,000,000 0.01% 0.03% 1,000
VIP 4 ≥ 600,000,000 0.00% 0.03% 1,200
VIP 5 ≥ 1,000,000,000 0.00% 0.03% 1,500
VIP 6 ≥ 1,500,000,000 -0.01% 0.03% 1,800
VIP 7 ≥ 2,000,000,000 -0.01% 0.03% 2,000

 

For a more detailed understanding of the OKEx fee structure and the way it operates please visit the following link where they explain it thoroughly with examples: https://www.okex.com/fees.html

Why should I use OKEx API?

  • OKEx API is free
  • OKEx API is efficient
  • Has many available cryptocurrencies
  • Features Options, Futures and Margin trading
  • Offers educational materials
  • Has Fiat support
  • Has competitive fees
  • No withdrawal and deposit fees

Why shouldn’t I use OKEx API?

  • Some people experience trouble with the customer service
  • Has withdrawal transfer limitations

Is OKEx API available in my country?

OKEx strives to be available worldwide but because of some strict regulations and jurisdiction issues it is not available in the following countries:

Hong Kong, Cuba, Iran, North Korea, Crimea, Sudan, Malaysia, Syria, United States (including all USA territories), Bangladesh, Bolivia, Ecuador, and Kyrgyzstan. 

What are the alternatives to using OKEx API?

OKEx can be replaced with other websites that can be more suitable for your needs. Here are some of them:

What clients are available for the OKEx API?

OKEx API is available in the following clients:

How to get started with OKEx API?

In order to get started with the OKEx API and launch those trading strategies, we first need to go over to their website and obtain the API Key.

Go to the following link and click the blue “Sign up” button that is found on the top of the page: https://www.okex.com

Then input your email address, create a password and click the Sign up button.

Then enter a 6-digit code that will be sent over to your email account. After that, you will be welcomed to the OKEx website. Now, go over to your profile icon in the upper right corner and select API on the dropdown menu.

You will now be prompted to enable 2FA via mobile number or Google Authenticator. After that, go to the API section and click the “+Create V5 API Key” Button.

Then you can specify how your API Key instance will operate on your account. You can add different permissions, names and etc.

Then you will obtain the API Key and Secret Key that you should store in a safe and secure place for later use. That’s it! Now we will explore the OKEx API functionality and simulate two simple trading scripts at the end.

How to get trading pairs info with OKEx API?

Trading pairs can be obtained with the OKEx API by utilizing the tickers endpoint. With the OKEx API, you need to specify the ticker type that you want to obtain i.e. Spot, Swap, Futures, or Option.

Let us import the relevant libraries and obtain all the spot trading pairs. For cleaning purposes, we will put the data into a pandas data frame, delete the instType aka “SPOT” column and print the last 5 values transposed.

import requests
import pandas as pd

url = 'https://www.okex.com'
tickers = pd.DataFrame((requests.get(url+'/api/v5/market/tickers?instType=SPOT').json())['data'])
tickers = tickers.drop('instType', axis=1)
tickers.tail().T

Here we see that the SPOT market has 505 trading pairs which is a decent number. To check for the rest just change the “SPOT” in the endpoint to your interest (i.e. “FUTURES”).

How to get Price Data with OKEx API?

To obtain the Price Data with the OKEx API you need to specify the instrument id in the required endpoint. The instrument id consists of the trading pair + the market it belongs to. Let us code it out:

ticker = requests.get(url+'/api/v5/market/ticker?instId=BTC-USD-SWAP').json()
ticker

How to get historical data with OKEx API?

To obtain historical data with the OKEx API you will need to decide on which endpoint to use as there are 4 endpoints for historical data. Then you can request the data via the chosen endpoint.

Here are the 4 endpoints listed and explained:

  • Get Candlesticks – retrieves the latest 1440 data entries grouped by the specified candlestick bar
  • Get Candlesticks History (top currencies only) – retrieves history candlestick charts from recent years.
  • Get Index Candlesticks – retrieves candlestick charts of the index.
  • Get Mark Price Candlesticks – retrieves the candlestick charts of mark price.

I’ll go with the second one and obtain the BTC-USD data over the last years with the preset candlesticks. I’ll clean the response and put it into a pandas data frame.

historical = pd.DataFrame((requests.get(url+'/api/v5/market/history-candles?instId=BTC-USDT-SWAP').json())['data'])
historical

Here we see that the OKEx API returns us data that isn’t labeled in an informative way. Let’s look at what the documentation says and rename the columns accordingly.

We will also convert the Unix time to date time and sort the value in ascending order by it.

historical.columns= ["Date","Open","High","Low","Close","Vol","volCcy"]
historical['Date'] = pd.to_datetime(historical['Date'], unit='ms')
historical.set_index('Date', inplace=True)
historical.sort_values(by='Date')
historical

Great, we could use an indicator now and do something with this data.

How to access technical indicators such as the 20 SMA with the OKEx API?

OKEx API doesn’t feature indicator creation but we can do that on our own by utilizing the pandas library or a more sophisticated btalib library that is built for indicators.

Let us create a simple 20 SMA on our data and put it all in a nice graph:

historical['20 SMA'] = historical.Close.rolling(20).mean()
historical.tail()
import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(x = historical.index,
                                    open = historical['Open'],
                                    high = historical['High'],
                                    low = historical['Low'],
                                    close = historical['Close'],
                                    ),
                     go.Scatter(x=historical.index, y=historical['20 SMA'], line=dict(color='purple', width=1))])


fig.show()

How to get Order Book data with OKEx API?

Order Book data can be obtained with the OKEx API by using the Get Order Book endpoint and specifying the instrument id and the order book depth to retrieve the data. The API returns data split in the bid and ask values.

book = requests.get(url+'/api/v5/market/books?instId=BTC-USD-SWAP&sz=10').json()
book['data']

If you want to split the bids and asks into their own data frames you can do the following:

ask = pd.DataFrame(book['data'][0]['asks'])
bid = pd.DataFrame(book['data'][0]['bids'])

ask

We again have numbers instead of informative columns. Let’s take the first row and explain what each number means:

  • 0 = the depth price
  • 1 = the size at the price
  • 2 = the number of liquidated orders at the price
  • 3 = the number of orders at the price

Now, let’s take the 0, 1 and 3 from both data frames and merge them into a single one.

bid.pop(2)
ask.pop(2)
df = pd.merge(bid, ask, left_index=True, right_index=True)
df = df.rename({"0_x":"Bid Price","1_x":"Bid Size", "3_x":"Bid Amount",
                "0_y":"Ask Price","1_y":"Ask Size", "3_y":"Ask Amount"}, axis='columns')
df.head()

How to get Trades Data with OKEx API?

To obtain the trades data with the OKEx API you will need to execute a request on the Get Trades endpoint. Here is how you can do it:

trades = requests.get(url+'/api/v5/market/trades?instId=BTC-USDT').json()
trades['data']

How to fire a market order vs a limit order with OKEx?

There is a slight difference, aside from the price parameter, when launching a market vs a limit order with the OKEx SDK that we’re going to use.

The difference is when you specify the size (sz) parameter. When using a market order the size will be specified by the second symbol of your ticker and vice-versa.

To illustrate this, both of the following orders will buy $20 worth of ETH but the market order will focus on the USDC part while the limit order will focus on the ETH part. This is the reason why the sz parameter isn’t the same.

# Limit Order
tradeAPI.place_order(instId='ETH-USDC', tdMode='cash', side='buy',
                     ordType='limit', sz='0.0093', px='2159.00')
# Market Order
tradeAPI.place_order(instId='ETH-USDC', tdMode='cash', side='buy',
                     ordType='market', sz='20')

How to execute a trade on BTC when ETH hits a certain price with the OKEx API?

In the first example, I will show you how to properly and securely launch orders with specified requirements. The thing that we want to do is to launch a trade on BTC when ETH hits a certain price (e.g. $3000).

In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping around.

When the price is executed we will wait for a few seconds and then check if the order was really filled. This additional step is very important to have in your trading strategies as the exchange server may encounter some troubles.

Now that we have the main idea in mind it is time to set up the trade. Take note that we will be using the OKEx python SDK for this.

import okex.Trade_api as Trade
import requests, time

api_key = ""
secret_key = ""
passphrase = ""
instId = "ETH-USDC"
flag = '0'

tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)

while True:
    try:
        ticker = requests.get('http://www.okex.com/api/v5/market/ticker?instId=BTC-USDC').json()
        print(ticker['data'][0]['bidPx'])
    except Exception as e:
        print(f'Unable to obtain ticker: {e}')
    
    if float(ticker['data'][0]['bidPx']) >= 32000.00:
        try: 
           result = tradeAPI.place_order(instId=instId, tdMode='cash', side='buy',
                                           ordType='limit', sz='0.005', px='2000.00')
           ordId = result['data'][0]['ordId']
        except Exception as e:
            print(f'Unable to execute order: {e}')

        time.sleep(2)

        try:
            check = tradeAPI.get_orders(instId, ordId)
        except Exception as e:
            print(f'Unable to check order: {e}')

        if check['data'][0]['state'] == 'canceled':
            print('Order was canceled.')
            break
        else:
            print('Order was executed!')
            break 
    else:
        print('Requirement not reached.')
        time.sleep(15)

How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the OKEx API?

The main task will be to execute an ETH trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain the prices of the two cryptos and calculate the percentage change between the two.

If the percentage change is less than 5%, the program will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.

After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Now that the logic is set, it is time to code it out:

import okex.Trade_api as Trade
import requests, time

api_key = ""
secret_key = ""
passphrase = ""
instId = "ETH-USDC"
flag = '0'

tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)

while True:
    try:
        old = requests.get('http://www.okex.com/api/v5/market/ticker?instId=BTC-USDC').json()
        print(old['data'][0]['bidPx'])
    except Exception as e:
        print(f'Unable to obtain ticker: {e}')

    time.sleep(300)

    try:
        new = requests.get('http://www.okex.com/api/v5/market/ticker?instId=BTC-USDC').json()
        print(new['data'][0]['bidPx'])
    except Exception as e:
        print(f'Unable to obtain ticker: {e}')
    
    percent = ((float(new['data'][0]['bidPx']) - float(old['data'][0]['bidPx'])) / float(old['data'][0]['bidPx'])) * 100

    if percent >= 5:
        try: 
           result = tradeAPI.place_order(instId=instId, tdMode='cash', side='buy',
                                           ordType='limit', sz='0.005', px='2000.00')
           ordId = result['data'][0]['ordId']
        except Exception as e:
            print(f'Unable to execute order: {e}')

        time.sleep(2)

        try:
            check = tradeAPI.get_orders(instId, ordId)
        except Exception as e:
            print(f'Unable to check order: {e}')

        if check['data'][0]['state'] == 'canceled':
            print('Order was canceled.')
            break
        else:
            print('Order was executed!')
            break 
    else:
        print(f'Requirement not reached. Percentage move at {percent}')

How to cancel orders with OKEx API?

To cancel an order with the OKEx API all you need to do is to access the Cancel Order endpoint. Here is an example code from the OKEx API SDK documentation:

import okex.Trade_api as Trade

tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)
tradeAPI.cancel_order(instId, ordId, clOrdId)

Full code

GitHub Link

Igor Radovanovic