Use CCXT to calculate Cryptocurrency trade indicators

Lorenz Vanthillo
ITNEXT
Published in
7 min readJan 13, 2021

--

At the time of writing Bitcoin is booming. It is by far the most famous cryptocurrency. Besides bitcoin there are a lot of other types of cryptocurrencies often called altcoins. Experienced traders use trade indicators to trade between Bitcoin, altcoins and other recognized currencies. In this article I will go through some commonly used indicators and I will describe how to calculate them and shortly explain a buy/sell strategy.

Many trade indicators can be calculated by using historical data. It’s very important to get the correct data from a certain coin pair (e.g. ETH/BTC) from an exchange. Here for we will use CCXT. This library provides a layer on top of an API provided by an exchange. CCXT supports a lot of cryptocurrency exchanges and makes it easy to interact between hem. In my examples I will use Binance as exchange and Python to interact with the CCXT library.

Before starting my explanation I want to emphasize that cryptocurrency trading or creating a trading bot isn’t as clear-cut as that. Indicators try to give an indication. They do not represent absolute truth. Be careful with it and first test your calculations before using them. In this article I will focus on how to calculate these indicators. The detailed interpretation is often well explained by external sources. By using this combination you should be able to create a fine trading strategy!

Let’s get started! I’ve generated API keys in my Binance account. As already mentioned, you can use a different exchange if you prefer. Even using a different programming language like JavaScript or PHP is possible. Below I wrote some code to import the CCXT library and to configure my exchange.

Printing the content of the coin_pairs variable will show all possible coin pairs (or trading pairs) supported by the exchange. It can be pretty hard to compare these pairs when they are using a different “base” coin (e.g. a price comparison between XLM/ETH and XRP/BTC is much harder than comparing XLM/BTC and XRP/BTC). This is the reason why I will filter the coin pairs and only use the ones with BTC as base coin.

Now we have the full list of available coin pairs. Our strategy is to loop through this list and fetch the necessary historical data for each coin pair. Next we can calculate trade indicators and create buy/sell signals.

CCXT offers us an easy way to retrieve the OHLC(V) data. OHLC(V) is an aggregated form of cryptocurrency trade data standing for Open, High, Low, Close and Volume. It will serve as our historical data. To fetch this data we need a configured exchange connection and a time frame (1m, 5m, 1h, 1d, …). The time frame defines the duration of a measurement. If you define a time frame of 5m you will get the opening price(O), high/max price (H), low/min price (L) and closing price (C) of a certain coin pair in a 5 minute interval. By default you will have 500 metrics (if available). You can use an optional parameter to define “a since” when you want more or less metrics. (= all available metrics since a certain point in time).

In the code above we will fetch the OHLCV data for each coin pair. We use a time frame of 1 hour. We will also convert the pandas data frame to a stockstats data frame via stockstats. Stockstats is a wrapper for pandas data frames and provides the ability to calculate many different stock market indicators.

The output of a Stockstats data frame

24h Trading Volume

The trading volume refers to the total number of a certain coin pair exchanged between buyers and sellers on a given day. Looking at volume patterns over time can help get a sense of the strength or conviction behind advances and declines in specific stocks and entire markets.

The correct way to calculate the 24h trading volume depends on how you configured your time interval. If you have a time interval of one day you can just take the last item of your data frame. If you use a 1 hour interval you will have to take a sum of the last 24 measurements. (see example). This will cover 24 hours of data. A more precise and easier way to do it is by using the ticker.

This calculation ran close 18.58h. So it contained nearly 24h of data.

You can use a trade volume as trend confirmation or to identify bullish or bearish signs. It’s explained here in much more detail.

RSI

The relative strength index (RSI) measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock.

Traditional interpretation and usage of the RSI dictates that values of 70 or above suggest that a coin is becoming overbought. An RSI reading of 30 or below indicates an oversold or undervalued condition.

# Calculate RSI                       
stock_data['rsi_14']
print(stock_data)

# Get most recent RSI value of our data frame
# In our case this represents the RSI of the last 1h last_rsi = stock_data['rsi_14'].iloc[-1] print(last_rsi)
# output (see data below):
39

RSI is added to the stock data. The current RSI is 39. This is not lower than 30 (buy signal) and not higher than 70 (sell signal). Currently the sign is telling us to “hodl”. A few hours before the RSI was below 30. This could have been a good time to buy. This explanation is actually far too short-sighted. You have to take several other things into account. They are explained here in much more detail.

MACD/MACDS

Moving average convergence divergence (MACD) is a trade indicator that shows the relationship between two moving averages of a coin its price. The MACD is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA. I don’t want to focus too much on the technical aspect although it’s very important to understand it in detail when you want to use it in your trading strategy.

# Calculate macd
stock_data['macd']
print(stock_data)

These values are difficult to interpret without a drawing. I used plotly to create a chart which shows the MACD behaviour. In the upper chart you see the ETH/BTC price. In the lower chart you see the MACD and the MACDS (signal) line.

Traders use MACD to identify changes in the direction or severity of a stock’s price trend. It’s very well explained over here.

A very basic key takeaway is the following: MACD triggers technical signals when it crosses above (to buy) or below (to sell) its signal line.

Below we can see that the MACD (red) line crosses the signal (green) line upwards the 3th of January at 9AM. This could mean a positive price evolution (= a good time to buy).

MACD crosses signal upwards
Price of ETH/BTC starts rising

These “crossings” can be translated to buy or sell signals. Here for you can use the following code.

294  2021-01-03T06:00:00.000Z     HOLD
295 2021-01-03T07:00:00.000Z HOLD
296 2021-01-03T08:00:00.000Z HOLD
297 2021-01-03T09:00:00.000Z BUY
298 2021-01-03T10:00:00.000Z HOLD
299 2021-01-03T11:00:00.000Z HOLD
...

Just like with the previous indicators it’s not not as clear-cut as described. There are plenty of other things to keep in mind! Again Investopedia to the rescue to focus on the important details.

Conclusion

I hope my calculations and basic explanations can help you with creating a fine trading strategy or during your development of a cryptocurrency bot. I would recommend to combine different indicators like RSI and MACD. Also check if your exchange supports a “testnet“ so you can test your bot without making real buys or sells. That way you can analyze your data and tweak your bot! I hope you enjoyed it!

If you really liked it!

--

--

AWS Community Builder | DevOps | Docker Certified Associate | 5x AWS Certified | CKA Certified | https://lvthillo.com