OKX API – An Introductory Guide

9 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on April 3, 2023

Table of contents:

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

What is the OKX API?

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

Link: https://www.okx.com

What is OKX?

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

Is OKX API free?

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

The fee structure of OKX 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 OKX users – the regular and VIP ones. For regular users, the fee structure is based on the amount of your total OKB holding (OKX native cryptocurrency). Here is how the SPOT fee tiers look:

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:

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 regular users, while the second one is for VIP users.

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

Why should I use OKX API?

  • OKX API is free
  • OKX 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 OKX API?

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

Is OKX API available in my country?

OKX 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 OKX API?

OKX 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 OKX API?

OKX API is available in the following clients:

How to get started with OKX API?

In order to get started with the OKX 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 at the top of the page: https://www.okx.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 OKX 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 OKX API functionality and simulate two simple trading scripts at the end.

How to get trading pairs info with OKX API?

Trading pairs can be obtained with the OKX API by utilizing the tickers endpoint. With the OKX 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.okx.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 OKX API?

To obtain the Price Data with the OKX 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
{'code' : '0',
 'msg': '',
 'data': [{'instType': 'SWAP',
    'instId': 'BTC-USD-SWAP',
    'last': '56143.2',
    'lastSz': '5',
    'askPx': '56145.4',
    'askSz': '1475',
    'bidPx': '56145.3',
    'bidSz': '538',
    'open24h': '58578.6',
    'high24h': '59012',
    'low24h': '54561.2',
    'volCcy24h': '22600.2617',
    'vol24h.: '12824931',
    'ts': '1620119907853',
    'sodUtc0': '57204.8',
    'sodUtc8': '57653.4'}]} 

How to get historical data with OKX API?

To obtain historical data with the OKX API you will need to decide 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 OKX 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 OKX API?

OKX 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 OKX API?

Order Book data can be obtained with the OKX 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 OKX API?

To obtain the trades data with the OKX 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']
[{'instld': 'BTC-USDT',
  'side': 'sell',
  'sz': '0.00928',
  'px': '54118.4',
  'tradeId.: '177167228',
  'ts': '1620149876536'},
 {'instID': 'BTCUSDT',
  'side': 'buy',
  'sz': '0.00002267',
  'px': '54118.5',
  'tradeId': '177167227',
  'ts': '1620149876291'},

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

There is a slight difference, aside from the price parameter, when launching a market vs a limit order with the OKX 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 OKX 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 OKX python SDK for this.

import okx.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.okx.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 OKX 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 okx.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.okx.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.okx.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 OKX API?

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

import okx.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