FTX API – A Complete Guide

11 min read

Get 10-day Free Algo Trading Course

Last Updated on June 10, 2021

Table of contents:

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

What is FTX API?

FTX API is a method that allows us to automatically trade cryptocurrencies on FTX via code.

What is FTX?

FTX is a robust cryptocurrency derivatives exchange platform.

With FTX you can trade various assets like Futures, Options, FTX Leveraged Tokens, Spot Markets, Prediction Markets, FTX MOVE contracts, and more.

FTX was founded by Alameda Research and launched on May 8, 2019. Since then it became one of the top 5 derivatives exchanges that is picked by many traders of various backgrounds.

Is FTX free?

The creation of your FTX account is free while the trading fees tend to vary depending on your monthly trading volume. Simply said, the more you trade the lower do the fees get.

An example would be the following: If you earned the monthly trading volume over $5,000,000 you would pay only 0.010% maker fee and 0.055% taker fee. The full table can be viewed below:

A nice thing about the exchange is that it doe not have any deposit, withdrawal, and futures settlement fees. It also features staking which provides discounts to FTT holders in the range from 3% to 60%.

The exchange also features a referral program, a Backtop Liquidity Provider program for market makers, and a VIP program for professional traders.

With the referral program, each user will get an affiliate link. When a user signs up with your referral code you will receive 25-40% of their trading fees, and they will get a 5% fee rebate.

With the Backstop Liquidity Provider Program, you pledge to take on the positions from accounts that are near bankrupt.

With the VIP Program, you get various things like lower fees, account manager, flexible API limits, and more. Here is an FTX table that shows the requirements for a VIP program:

Why should I use FTX?

  • FTX is easy to use
  • No deposit fees
  • Has low fees
  • FTX is beginner-friendly
  • Has a good API
  • You don’t need KYC to trade on it
  • Features good derivatives for trading
  • Guarantees liquidity
  • So far it wasn’t hacked or experienced malicious use

Why shouldn’t I use the FTX?

  • FTX is a new exchange
  • It is not available in all countries
  • FTX is an unregulated exchange
  • Doesn’t feature a trading test server

Is FTX available in my country?

As of 2021, FTX does not onboard or provide services to personal accounts of current residents of the United States of America, Cuba, Crimea and Sevastopol, Iran, Syria, North Korea, or Antigua and Barbuda.

What are the alternatives to using FTX?

FTX API can be replaced with some alternatives and they are the following:

  • Coinbase
  • Gemini
  • Binance
  • BitMex
  • Kraken.io
  • Crypto.com
  • CoinPaymets
  • GoCoin
  • Coinomi
  • Cryptopay
  • Blocknomics
  • Blockchain

What clients are available for the FIX API?

FTX API is available in the following clients:

  • Python
  • JavaScript
  • C#

How to get started with FTX?

In order to get started with the FTX API, you will first need to go over to their website to create an account. The website is found on the following link: https://ftx.com/

In the upper right column you will see a big blue “Register” button, go ahead and click it.

A sign-up pop-up will appear and you will need to enter your email address and create a password. Be sure to verify that you’re not a robot and agree with the terms of service, after hopefully reading some of it.

After that, you will be asked by the exchange if you wish to take a quick overview of its features. We covered all of them in this article but a more detailed analysis won’t hurt.

After that, you will be asked to complete a two-factor authorization to improve the safety of your account. Be sure to do that.

Okay, let us obtain the API key now. Click on your blue profile icon that is found in the upper right corner and then go to “Settings”. When there scroll down until you see the “API Keys” header.

Now click the CREATE API KEY button and be sure to copy and paste your API Key and API secret in a secure place. The API Secret won’t be shown again after you close the dialog.

You can freely edit your API Key permissions by changing its settings to read-only, whitelisting your IP address, and more.

That’s pretty much it. We are now ready to get our hands dirty and explore all the things that their API can do. We will start off by exploring the public APIs and finish off with two trading scenario examples.

How to get Price Data with FTX?

Price data can be obtained by calling the required REST API endpoints. Before we start I should mention that the API rate limit is set to 30 requests per second. If you exceed this limit you will get HTTP 429 errors.

If you want faster market and account data be sure to explore the websocket API. Now, let us import the relevant libraries and see what markets are available in the FTX exchange.

We will also want to arrange the data in a pandas data frame for a better look and sense of the data.

import pandas as pd
import requests

markets = requests.get('https://ftx.com/api/markets').json()
df = pd.DataFrame(markets['result'])
df.set_index('name', inplace = True)
df.T

If you want to obtain data for a specific market all you need to do is to pass the symbol of that specific market you want to look into:

markets = pd.DataFrame(requests.get('https://ftx.com/api/markets/BTC-0924').json())
markets = markets.drop(['success'], axis=1)
markets

How to get Futures Data with FTX?

Futures data can be obtained through the FTX API futures endpoint as follows:

futures = requests.get('https://ftx.com/api/futures').json()
df = pd.DataFrame(futures['result'])
df.set_index('name', inplace = True)
df.tail().T

If you want to get a Futures Stats with the FTX API you can do the following:

futures = requests.get('https://ftx.com/api/futures/YFI-0326/stats').json()
futures

To get the Index Weights of a Future with the FTX API do the following:

futures_weight = requests.get('https://ftx.com/api/indexes/ALT/weights').json()
futures_weight

Have in mind that this endpoint only applies to index futures like EXCH, ALT, MID, DRAGON, etc.

To get all the expired futures you can call the following endpoint:

futures_exp = requests.get('https://ftx.com/api/expired_futures').json()
futures_exp = pd.DataFrame(futures_exp['result'])
futures_exp.set_index(futures_exp['description'], inplace=True)
futures_exp.head().T

How to get historical data with FTX?

Historical price data from the FTX API can be obtained by utilizing their REST API endpoint. The endpoint has the following parameters that should be filled for a successful API request:

  • market_name
  • resolution – window length expressed in seconds
  • limit – optional with a 5000 limit
  • start_time – optional (unix)
  • end_time – optional (unix)

Let us obtain the daily prices of our BTC-0924 asset from the beginning of this year up to the current day. We will also arrange our data into a data frame and drop the startTime column as we know what it is (1.1.2021).

historical = requests.get('https://ftx.com/api/markets/BTC-0924/candles?resolution=3600&start_time=1609462800').json()
historical = pd.DataFrame(historical['result'])
historical.drop(['startTime'], axis = 1, inplace=True)
historical.head()

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

Technical indicators like the 20SMA can be easily accessed by the pandas library. For more technical indicators such as the RSI be sure to check out the btalib library.

In order to calculate the 20-day simple moving average, we will need to convert our timestamp to the usual format.

historical['time'] = pd.to_datetime(historical['time'], unit='ms')
historical.set_index('time', inplace=True)
historical['20 SMA'] = historical.close.rolling(20).mean()
historical.tail()

Now we shall graph the data by creating a OHLC chart with the Plotly library. The cools thing about this chart is that its interactive. In order to create it do the following:

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 FTX?

In order to get the order book data we can write the request as follows:

orderbook = requests.get('https://ftx.com/api/markets/BTC-0924/orderbook').json()
orderbook

As this response is quite messy we will tidy it up by creating two separate data frames for each of the two and merging them together for a better look.

Have in mind that the order book depth is set to 20 by default and that it can go up to 100.

orderbook_asks = pd.DataFrame(orderbook['result']['asks'])
orderbook_bids = pd.DataFrame(orderbook['result']['bids'])

print(orderbook_bids.head())
print(orderbook_asks.head())

And now, let us merge them and name the columns as follows:

df = pd.merge(orderbook_bids , orderbook_asks , left_index=True, right_index=True)
df = df.rename({"0_x":"Bid Price","1_x":"Bid Amount",
                "0_y":"Ask Price","1_y":"Ask Amount"}, axis='columns')
df.head()

If you want to see some basic stats you can use the describe function like this:

df.describe()

How to get Trades with FTX?

To get all of the trades for a specific asset with the FTX API you can write the following code:

orderbook = requests.get('https://ftx.com/api/markets/BTC-0924/trades').json()
orderbook = pd.DataFrame(orderbook['result'])
orderbook.drop(['id','time'], axis = 1, inplace = True)
orderbook.head()

The Get trades endpoint also has the start and end date parameters that you can play around with. Have in mind that the default limit of orders is set to 20 while it can go up to 100. This can be tweaked by the limit parameter.

How to get Leveraged Tokens data with FTX?

Leveraged Tokens list from the FTX API can be obtained as follows:

tokens = requests.get('https://ftx.com/api/lt/tokens').json()
tokens = pd.DataFrame(tokens['result'])
tokens.set_index('name', inplace =True)
tokens.head().T

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

In the first example, I will show you how to properly and securely launch an order with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price.

To be precise, we will buy BTC for their current market price if the price of ETH reaches $2k.

Before we create the main loop I will show you the main building blocks of the order structure.

Let us go ahead and see how the Authentication request should look like when using the FTX exchange API:

import time
import hmac
from requests import Request

ts = int(time.time() * 1000)
request = Request('GET', '<api_endpoint>')
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
signature = hmac.new('YOUR_API_SECRET'.encode(), signature_payload, 'sha256').hexdigest()

request.headers['FTX-KEY'] = 'YOUR_API_KEY'
request.headers['FTX-SIGN'] = signature
request.headers['FTX-TS'] = str(ts)

# Only include line if you want to access a subaccount. Remember to URI-encode the subaccount name if it contains special characters!
# request.headers['FTX-SUBACCOUNT'] = 'my_subaccount_nickname'

As you can see the FTX API has a “nonce” feature (ts) which is a number that must not be repeated and must be increased between order requests. This feature prevents potential hackers who have captured our previous request to simply replay that request.

In the request we simply provide the type of request we want to use (GET/POST) and the order endpoint with its parameters. The order parameters are the following:

  • market – the thing you want to buy or sell (e.g. BTC/USD or XRP-PERP)
  • side – buy or sell
  • price – pass “null” if you want to do a market order
  • type – limit or market
  • size – the amount you want to buy
  • reduceOnly – optional
  • ioc – optional
  • postOnly – optional
  • clientId – optional

Then the order details are encoded and the headers are set up. As we now know how an order is built, let us go ahead and create our main order loop for the specified task.

Have in mind that I’ll be using their client.py that can be found on their GitHub on the following link:

ftx/client.py at master · ftexchange/ftx · GitHub

import time
import hmac
from requests import Request
import requests
import json
from client import FtxClient
import json, urllib, csv
import pandas as pd
client = FtxClient()

while True:
    try:
        btc_data = requests.get('https://ftx.com/api/markets/BTC-PERP').json()
        print(btc_data['result']['ask'])
    except exception as e:
        print('Error obtaining BTC old data')
    
    if btc_data['result']['ask'] != 2000.0:
        print('The trade requirement was not satisfied. The percentage move is at ',percent)
        sleep(300)
        continue
    
    elif btc_data['result']['ask'] == 2000.0:
        try:
            data = {
                    "market":"BTC/USD",
                    "side":"buy",
                    "price":None,
                    "type":"market",
                    "size":100,
                    "reduceOnly":False,
                    "ioc":False,
                    "postOnly":False
                    }

                send_order = client._post(f'orders', data)
                print(send_order)
        except excpetion as e:
            print('Error making order request')
        
        sleep(2)
        try:
            order_response = client._process_response(f'send_order', send_order)
            print(order_response)
        except exception as e:
            print('Error checking for order status')
            
        if order_response['success'] == true:
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
        else:
            print('Order was canceled {}'.format(pd.Timestamp.now()))
            break

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

The next example will use a similar order logic, but it will look for the percentage change between two symbols. The main task will be to execute a BTC trade when ETH 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.

This is the so-called pairs trading strategy where we expect the two assets to come back together after an unusual divergence.

while True:
    try:
        btc_old = requests.get('https://ftx.com/api/markets/BTC-PERP').json()
        print(btc_data['result']['ask'])
    except exception as e:
        print('Error obtaining BTC old data')
        
    sleep(300)
    
    try:
        btc_new = requests.get('https://ftx.com/api/markets/BTC-PERP').json()
        print(btc_data['result']['ask'])
    except exception as e:
        print('Error obtaining BTC old data')

    percent = (((float(btc_new['result']['ask']) - float(btc_old['result']['ask'])) * 100) / float(btc_old['result']['ask']))
        
    if percent < 5:
        print('The trade requirement was not satisfied. The percentage move is at ',percent)
        sleep(0.1)
        continue
    
    elif percent >= 5:
        try:
            data = {
                    "market":"BTC/USD",
                    "side":"buy",
                    "price":None,
                    "type":"market",
                    "size":100,
                    "reduceOnly":False,
                    "ioc":False,
                    "postOnly":False
                    }

                send_order = client._post(f'orders', data)
                print(send_order)
        except excpetion as e:
            print('Error making order request')
        
        sleep(2)
        try:
            order_response = client._process_response(f'send_order', send_order)
            print(order_response)
        except exception as e:
            print('Error checking for order status')
            
        if order_response['success'] == true:
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
        else:
            print('Order was canceled {}'.format(pd.Timestamp.now()))
            break

More about FTX

Moreover, the exchange was backed up by Binance on release and is currently owned by FTX Trading LTD and is based in Antigua and Barbuda with the main office in Hong Kong.

The founders of the exchange are transparent and you can freely view their LinkedIn profiles. The main goal of the exchange is to be usable by retail, institutional, and algo traders.

Have in mind that FTX is an unregulated exchange and that it follows the KYC (Know Your Customer) regulation.

The exchange features over 200 tradable coins and over 300 tradable pairs. The most notable ones are BTC, ETH, LTC, BNB, MKR, and more.

Recently, the exchange has opened up to some of the most popular US stocks like AMZN, SPY, APPL, TSLA NFLX, FB, and more. The FTX exchange also allows transfers in fiat and cryptos like BTC, ETH, LTC, and stablecoins.

The exchange features 3 types (tiers) of accounts that get better progressively (higher withdrawal limit, OTC, and more). The accounts are upgraded by providing more KYC information.

Check out the following table to understand how it gets better:

When it comes to FTX’s Leveraged Tokens (ERC20 assets), their main premise is to provide leveraged exposure to the crypto market without the need to manage a leveraged position.

The example of a leveraged token that FTX gives us is the following:

“For example, take ETHBULL, a 3x long ETH token.  For every 1% ETH goes up in a day, ETHBULL goes up 3%; for every 1% ETH goes down, ETHBULL goes down 3%.”

HALF +1/2x | BULL +3x
HEDGE -1x | BEAR -3x

Have in mind that these tokens also carry a risk factor as you can lose large amounts of money if you aren’t an experienced trader that is well-versed in the markets. To learn more about them check out this link:

https://help.ftx.com/hc/en-us/articles/360032509552-Leveraged-Token-Walkthrough-READ-THIS-

When it comes to leverage the FTX exchange allows the user to go up to 101x leverage and the preset leverage is set to 10x for every user. Note that the number can be bumped up in your profile settings.

Their MOVE contracts are a type of futures that have an expiration date according to the raw amount of Bitcoin moves within a certain time frame (e.g. daily, weekly…).

This type of contract allows the contract holder to make profits solely from the volatility of BTC, no matter the direction of the move. This means that the contract’s value is entirely based on the volatility of the asset.

An interesting thing that the Exchange features is the Prediction Market that is currently set for the US election race for 2024. The asset is called TRUMP2024 which is a futures contract that expires to $1 if Donald Trump wins the election and $0 otherwise.

FTX also features its own mobile apps that are available for both Android and iOS. The exchange also runs various trading competitions and events.

For example, the previous one was that every hour you earn 1 DOGE for each WSB (WallStreetsBets) market you traded for at least $500.

The users of the exchange have said that it has good customer support that is always ready to help its customers out. Moreover, FTX features its own Telegram, Blog section, and Twitter where you can read up on various things.

Full code

GitHub Link

Igor Radovanovic