Requesting Crypto Prices from the Gate.io API using Python

0

In this article, we will take a closer look at the Gate.io spot market-API and use it to stream crypto prices with Python. Despite being one of the smaller players in the crypto exchange market (top 20), Gate.io features a large number of smaller cryptocurrencies that cannot be found on larger exchanges such as Coinbase or Binance. These small-cap cryptos are generally more volatile, which makes gate.io an interesting platform for price analysis and algorithmic trading.

In the following, we take a quick look at the Gate.io API documentation. Then we will implement some Python code that pulls price information in regular intervals. We store the price data for each cryptocurrency in a Pandas DataFrame, with which you can then continue to work on your own projects.

Gate.io
Gate.io crypto exchange

About the Gate.io Spotmarket API

Before we take a look at the market endpoint, it is important to understand that Gate.io offers multiple markets where cryptocurrencies are traded in different ways. For example, there is a futures market, a spot market, and a margin market. Each of these markets has its own HTTP REST API endpoint, which in turn provides different operations. For example, there are operations to submit buy and sell offers at the marketplace and operations to retrieve information such as price and order data. A full list of these operations can be found in the official API documentation.

In this tutorial, we will only work with the spot market API endpoint and the list_tickers operation. Unlike most of the other operations, the list_tickers operation does not require authentication. This means, as long we only want to retrieve price data, we don’t need to register. Another advantage is that there is also no limit to the number of API requests due to the lack of authentication.

The list_ticker operation returns a list of data fields for cryptocurrency pairs. Examples of price pairs are BTC_USD, BTC_ETH, BTC_ADA, and so on. If we want to limit the returned data to a specific price pair (e.g. BTC_USD), we can do so by passing a single pair as a variable in the API call. However, it is not possible to restrict multiple pairs. This means that we either get data for a single pair or for all pairs. The API then returns a list with the following data fields:

Response returned by the Gate.io API list_tickers operation
Response returned by the Gate.io API list_tickers operation

Implementation: Retrieving Regular Price Ticker Data from Gate.io with Python

Let’s start by implementing a short Python script that will periodically call the gate.io spot market endpoint and return a response. Each time we receive a response, we will process it. In doing so, we will extract multiple price fields and append them as new records to a set of DataFrames. To do this, we use a separate DataFrame per crypto price pair.

The use of a separate data frame per price pair was chosen because it facilitates later work with the data. An alternative would be to store all price data in a single data frame. However, we usually want to work with price data for specific price pairs and do Analytics on them, for example. This is easier if we have all the corresponding data in one place and do not have to filter it beforehand.

As always, you can find the code in the relative GitHub repository.

Prerequisites

Before we start the coding part, make sure that you have set up your Python 3 environment and required packages. If you don’t have an environment set up yet, you can follow this tutorial to set up the Anaconda environment.

Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages: 

In addition, we will be using the gate.io package (package name gate-API) to pull price data from the crypto exchange gate.io.

You can install packages using console commands:

  • pip install <package name>
  • conda install <package name> (if you are using the anaconda packet manager)

Step #1: Connect to the Gate.io API

The first step is to establish a connection to the API. We do this by creating a new api_client object and then using it as an argument to the spot API function. This will return an api_instance.

import gate_api
from gate_api.exceptions import ApiException, GateApiException
import pandas as pd
import time
import datetime as dt

# Defining the host is optional and defaults to https://api.gateio.ws/api/v4
# See configuration.py for a list of all supported configuration parameters.
configuration = gate_api.Configuration(host = "https://api.gateio.ws/api/v4")
api_client = gate_api.ApiClient(configuration)

# Create an instance of the API class
api_instance = gate_api.SpotApi(api_client)

Step #2: Define Functions for Calling the API and Handling the Response

Next, we create two functions. The first function contains a loop that calls the gate.io spot market list_tickers API. Every time we call this endpoint, it will return a list with price information. As mentioned before, we handle this data in a dictionary that contains a separate DataFrame for each cryptocurrency price pair. Handling the data means that we iterate through the response and extract the price data per cryptocurrency pair. Each price data is handed over to our second function “append_data_to_df”, which stores the data in its respective DataFrame.

The request_data function takes three arguments:

  • runs: this is how often the API should be called.
  • s: the interval in seconds in which we call the API
  • currency_pair: you can alternatively define a specific currency pair for which you want to retrieve price information. If none is specified, the API endpoint will return the full list of all price pairs (currently ~ 270).
# this function starts calling the Gate.io API
# the response will contains price data for multiple cryptocurrencies
# the price information of each cryptocurrency will be stored in its own dataframe
def request_data(runs, currency_pair, s):
    currency_dfs = {}
    for t in range(runs):

        try:
            api_response = api_instance.list_tickers(currency_pair=currency_pair)
        except GateApiException as ex:
            print("Gate api exception, label: %s, message: %s\n" % (ex.label, ex.message))
        except ApiException as e:
            print("Exception when calling SpotApi->list_tickers: %s\n" % e)

        ts = dt.datetime.now()
        currency_response_dict = {resp.currency_pair: resp for resp in api_response
                                if "USDT" in resp.currency_pair and "BEAR" not in resp.currency_pair}
                  
        for currency_name, response in currency_response_dict.items():
            try:
                currency_dfs[currency_name]
            except KeyError:
                # Create new dataframe if currency does not have one yet
                currency_dfs[currency_name] = pd.DataFrame(columns=[
                    'Symbol', 
                    'Timestamp', 
                    'Volume', 
                    'Price', 
                    'Price_Delta', 
                    'Price_Delta_Percent'])
            
            # get the price of the currency at the last price point
            if len(currency_dfs[currency_name]) > 1:
                #print(currency_dfs[currency_name])
                price_before = currency_dfs[currency_name]['Price'].iloc[-1]
            else:
                price_before = 0
            
            # append a new record the dataframe of this currency
            new_data_as_dict = append_data_to_df(price_before, response, ts)
            
            # add this dataframe to the list of currency_dataframe. there are separate dfs per currency.
            currency_dfs[currency_name] = currency_dfs[currency_name].append(new_data_as_dict, ignore_index=True)
                
        # wait s seconds until the next request
        time.sleep(s)
    return currency_dfs

# this function is called for each cryptocurrency and everytime the gate.io API returns price data
# the function extracts price information from a single API response and adds it to a dataframe 
# example: the API response contains data for 270 cryptocurrency price pairs -> the function is called 270 time per API response
def append_data_to_df(price_before, data, ts):
    volume = data.base_volume
    price = pd.to_numeric(data.last)
    price_delta = price - price_before
    
    if price > 0:
        price_delta_p = price_delta / price 
    else:
        price_delta_p = 0
    
    new_record = {
                  'Symbol': data.currency_pair, 
                  'Timestamp': ts, 
                  'Volume': volume, 
                  'Price': price,
                  'Price_Delta': price_delta,
                  'Price_Delta_Percent': price_delta_p
                 }
    return new_record

Step #3: Start Calling the Gate.io Market API

once we have defined the functions to request and handle the price data, we can start calling the API. In the code below, we use a request interval of 10 seconds. We stop calling the API for test purposes stop after 4 runs. Afterward, we print the list of DataFrames to inspect the collected data.

s = 10 # API request interval in seconds
currency_pair = '' # currency pair (optional)
runs = 4 # number of data points to fetch

df_list = request_data(runs, currency_pair, s)

df_list # list that contains one dataframe per currency
Excerpt of the list of DataFrames

Above you see an excerpt of the list of DataFrames. It contains one DataFrame with for price points per cryptocurrency price pair.

Summary

In this tutorial, we learned how to query Crypto Price data via the Gate.io API and store it in DataFrames. With this, we have laid the foundation for further exciting projects. For example, the data can now be used to display price information on a website, or we can use it for analytics applications such as a crypto trading bot that act in the market upon automated trading signals.

If you are looking for an API for crypto market data, then you might also want to consider the Coinmarketcap API. I have recently covered it in another API tutorial.

If you liked this post, please let me know in the comments.

Author

  • Hi, I am Florian, a Zurich-based consultant for AI and Data. Since the completion of my Ph.D. in 2017, I have been working on the design and implementation of ML use cases in the Swiss financial sector. I started this blog in 2020 with the goal in mind to share my experiences and create a place where you can find key concepts of machine learning and materials that will allow you to kick-start your own Python projects.

Leave a Reply