using the api with python

Requesting Crypto Prices from the API using Python

This article will take a closer look at the 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), features many smaller cryptocurrencies that we cannot find on more extensive exchanges, such as Coinbase or Binance. These small-cap cryptos are generally more volatile, making an exciting platform for price analysis and algorithmic trading.

In the following, we take a quick look at the 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 projects. crypto exchange

About the Spotmarket API

Before we look at the market endpoint, it is crucial to understand that offers multiple markets for different ways of trading cryptocurrencies. For example, there is a futures market, a spot market, and a margin market. Each of these markets has its HTTP REST API endpoint, which in turn provides different operations. For example, there are operations for submitting buy and sell orders at the marketplace and retrieve price and order data. The official API documentation provides a complete list of these operations.

In this tutorial, we will only work with the spot market API endpoint and the list_tickers operation. Unlike most of the other functions, the list_tickers operation does not require authentication. So, we don’t need to register as long we only want to retrieve price data. Another advantage is that there is also no limit to 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 pass a single pair as a variable in the API call. However, it is not possible to restrict multiple pairs. So, we either retrieve data for a single pair or all pairs. For each request, the API returns a list with the following data fields:

Response returned by the API list_tickers operation
The response returned by the API list_tickers operation

Implementation: Retrieving Regular Price Ticker Data from with Python

Let’s start by implementing a short Python script that will periodically call the 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.

We use a separate DataFrame per price pair to ease working with the data later. An alternative would be to store all price data in a single DataFrame. However, we usually want to work with price data for specific price pairs and do Analytics on them. It is easier to 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.


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 package (package name gate-API) to pull price data from the crypto exchange

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 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
# See for a list of all supported configuration parameters.
configuration = gate_api.Configuration(host = "")
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 spot market list_tickers API. Every time we contact 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. Managing 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 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):

            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 =
        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():
            except KeyError:
                # Create new dataframe if currency does not have one yet
                currency_dfs[currency_name] = pd.DataFrame(columns=[
            # get the price of the currency at the last price point
            if len(currency_dfs[currency_name]) > 1:
                price_before = currency_dfs[currency_name]['Price'].iloc[-1]
                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
    return currency_dfs

# this function is called for each cryptocurrency and everytime the 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 
        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 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 four 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.


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

If you are looking for an API for crypto market data, you might also 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.


  • 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