How to Use FTX REST API in Python

This article explains how to use the REST API to access FTX in Python so that you can build your trading program. As you go through the article, you can also watch our article tutorial video:

What is FTX?

FTX is an exchange where users can trade various digital assets, such as cryptocurrencies, tokenised stocks and derivatives. Founded in 2019, it is a relatively new exchange, but it is ranked as the third top cryptocurrency spot exchange after Binance and Coinbase on CoinMarketCap at the time of writing. 

When it comes to trading cryptocurrencies, it is no doubt that decentralised exchange (DEX) and decentralised finance (DeFi) will be the future. But central exchanges such as Binance, Coinbase and FTX are still heavily used, especially for fiat on- and off-ramps (converting fiat currencies into cryptocurrencies and visa versa). FTX provides a well-documented API (REST, web socket and FIX) and low trading fees, making it an excellent platform for algorithmic traders. In addition, it publishes a sample client code on Github to use the REST API in Python, so it is straightforward to build trading programs in Python. 

Please note that, depending on where you reside, FTX service might not be available. Please see the details on ftx.com. Also, this article does not explain any trading algorithms or strategies. If you are interested in learning algorithmic trading strategies, the following course on Fixter Academy might be of interest to you.

Binance Trading API – Mastering Trading Strategies

How to set up the environment

Set up the Python environment

In this article, we will use Jupyter Notebook to explore the REST APIs. We’ll also use some packages, such as Pandas and Plotly, so let’s set up the environment first.

Go to the terminal and create a virtual environment first and activate it.

$ mkdir ftx
$ cd ftx
$ python3 -m venv venv
$ source ./venv/bin/activate

Then install necessary packages.

(venv) $ pip install -U pip
(venv) $ pip install jupyter
(venv) $ pip intall pandas plotly python-dotenv requests ciso8601

Create a file called “.env” with the content below in the current directory, which we will update in the next section.

File .env:

FTX_API_KEY=
FTX_API_SECRET=

Set up the API Key

To use the FTX API, you need to create a free account on ftx.com. Click on the REGISTER button on the top right-hand corner and fill in the necessary information. 

Creating an account is straightforward, but you must go through the KYC process (identify verification) before starting trading. Please see more detail on the help page below:

Individual Account KYC

Once you’ve created your account, go to the account settings page and select “Api” on the left-hand side menu.

Click on the “CREATE API KEY” button. New API Key and API Secret are shown. Open the file “.env”, which we created in the previous section and copy and paste the API Key and API Secret values, respectively.

.env

FTX_API_KEY=Os2HGy3D...
FTX_API_SECRET=uRr2aKYw...

After checking that the values are correctly saved in the file .env, close the API key pane.

Get the Python client sample code

FTX publishes sample code to access APIs using Python, C++ and Go on their Github repository. We are going to use the Python REST API client sample code in this article for demonstration purposes.

Copy the file client.py to the current directory as client.py. 

(venv) $ curl https://raw.githubusercontent.com/ftexchange/ftx/master/rest/client.py -o client.py

Alternatively, you can click the “Copy raw contents” to copy the file content to the clipboard, create a new local file client.py and paste the contents from the clipboard. 

How to get data using the FTX REST API

Now we’re ready to start using the REST API. First, start the Jupyter Notebook from the terminal.

(venv) $ jupyter notebook

Your default web browser will automatically open the Jupyter notebook home page, but if it doesn’t, open the URL shown in the Jupyter notebook command logs. 

Create a new notebook on the Jupyter notebook home page by clicking the “New” button on the top right corner and selecting “Python3” from the drop-down menu. 

On the new notebook, let’s import the necessary packages and load the environment variables in the file .env, which we created in the previous section.

from datetime import datetime
from dotenv import load_dotenv
import os
import json
import pandas as pd
import plotly.graph_objects as go
import requests
import time

from client import FtxClient

load_dotenv()

We will use the environment variables later when we create a FtxClient instance.

Get all market data

You can get all market data as shown below. Just getting market data does not require an account on FTX.

endpoint_url = 'https://ftx.com/api/markets'

# Get all market data as JSON
all_markets = requests.get(endpoint_url).json()

# Convert JSON to Pandas DataFrame
df = pd.DataFrame(all_markets['result'])
df.set_index('name', inplace = True)

This is how the DataFrame df looks:

For the details of the response format, please see the API doc – Get markets

Get single market data

You can also get single market data. The following is an example to get BTC/USD (spot) market data. 

base_currency = 'BTC'
quote_currency = 'USD'

# Specify the base and quote currencies to get single market data
request_url = f'{endpoint_url}/{base_currency}/{quote_currency}'

df = pd.DataFrame(requests.get(request_url).json())
df['result']

Get historical data

You can get historical data using the GET request. The following is an example to get daily BTC/USD market data since 2021-01-01.

# 1 day = 60 * 60 * 24 seconds
daily=str(60*60*24)

# Start date = 2021-01-01
start_date = datetime(2021, 1, 1).timestamp()

# Get the historical market data as JSON
historical = requests.get(
    f'{request_url}/candles?resolution={daily}&start_time={start_date}'
).json()

# Convert JSON to Pandas DataFrame
df = pd.DataFrame(historical['result'])

# Convert time to date
df['date'] = pd.to_datetime(
    df['time']/1000, unit='s', origin='unix'
) 

# Remove unnecessar columns
df.drop(['startTime', 'time'], axis=1, inplace=True)
df

For the details, please see the API doc – Get historical prices

Plot the historical data

This step is optional, but it is usually helpful to plot the historical data when analysing it. The following is an example to use Plotly to create a candlestick chart, which is commonly used to visualise price movement in the financial markets.

fig = go.Figure()

fig.update_layout(
    title={
        'text': f"{base_currency}/{quote_currency}",
        'x':0.5,
        'xanchor': 'center'
    },
    xaxis_title="Date",
    yaxis_title="Price",
    xaxis_rangeslider_visible=False
)

fig.add_trace(
    go.Candlestick(
        x=df['date'],
        open=df['open'],
        high=df['high'],
        low=df['low'],
        close=df['close']
    )
)
fig.show()

How to trade using the FTX REST API

To trade on FTX, we need an account and perform the authentication using our API Key and API Secret. This process can be tedious, but thanks to the sample code FTX has provided, we don’t need to code the logic ourselves. 

In the “How to set up the environment” section above, we created API Key and API Secret and saved them in the local file .env. Then, we have already loaded the values using python-dotenv’ s load_dotenv() in the example above, so we can access them using the os.getenv() function.

We only need to pass these two values as arguments to create a client, as shown below.

ftx_client = FtxClient(
    api_key=os.getenv("FTX_API_KEY"), 
    api_secret=os.getenv("FTX_API_SECRET")
)

You will need to deposit some funds into your account in advance to buy some assets.

Place an order

You can place an order using the place_order() function in the sample code. The following is an example of placing a limit order to buy 0.0001 BTC at 90% of the current price.

# Get the current price
market = requests.get(request_url).json()
market_ask = market['result']['ask']
print(f"{base_currency}/{quote_currency} asking price = {market_ask}")

# Place an order
try:
    bo_result = ftx_client.place_order(
        market=f"{base_currency}/{quote_currency}", 
        side="buy",
        price=market_ask*0.9,
        size=0.0001
    )
    print(bo_result)
except Exception as e:
    print(f'Error making order request: {e}')

Output:

BTC/USD asking price = 61865.0
{'id': 94071380298, 'clientId': None, 'market': 'BTC/USD', 'type': 'limit', 'side': 'buy', 'price': 55678.0, 'size': 0.0001, 'status': 'new', 'filledSize': 0.0, 'remainingSize': 0.0001, 'reduceOnly': False, 'liquidation': None, 'avgFillPrice': None, 'postOnly': False, 'ioc': False, 'createdAt': '2021-11-07T13:21:42.937268+00:00', 'future': None}

Cancel an order

You can cancel the order you’ve just made by specifying the order ID as shown below.

try:
    co_result = ftx_client.cancel_order(
        order_id=bo_result['id']
    )
    print(co_result)
except Exception as e:
    print(f'Error cancelling order request: {e}')

If the order has not been filled yet, you should get the following message:

Order queued for cancellation

Summary

FTX is one of the largest exchanges, where users can trade various digital assets, such as cryptocurrencies, tokenised stocks and derivatives. It provides a well-documented API (REST, web socket and FIX) and low trading fees, making it an excellent platform for algorithmic traders. In addition, it publishes a sample client code on Github to use the REST API in Python, so it is straightforward to build trading programs in Python. 

In this article, we looked at:

  • how to get current and historical market data
  • how to create a candlestick chart
  • how to place an order
  • how to cancel an order

I hope this article has helped you to get started with trading on FTX in Python. You can find more information about the API on the API documentation

Related Course

To boost your understanding of cryptocurrency trading, you may also want to check out our crypto trading bot courses on the Finxter Computer Science Academy: