Automated Triangular Arbitrage of Cryptos in 4 steps

Lakshmi Ajay
Geek Culture
Published in
7 min readMar 3, 2022

Build your own arbitrage trading algorithm in Python

Introduction

Arbitrage takes advantage of the difference in the asset prices in the market. Arbitrage has been traditionally done in the forex market for many years but given the volatility in the crypto market, it can applied to the crypto market as well. Opportunities for arbitrage can exist within the same exchange or across exchanges.

Triangular arbitrage is a technique that tries to exploit the price discrepancy across three different assets at the same time.
For example, we can exchange BTC for USDT, BTC for ETH and ETH back to USDT. If the net worth in doing these three trades simultaneously is profitable then the 3 trades are executed simultaneously.

Example of Triangular Arbitrage (Image by Author)

In this article we will be looking into the arbitrage opportunities within the same exchange, in particular we will be deep diving into triangular arbitrage approaches. The focus is to develop and implement a trading algorithm that can identify a profit and trigger the required trade orders for it.

Arbitrage is considered as a lower risk trading method as compared to the traditional trading where the timing of the buy/sell is crucial. Also in arbitrage, the profit/loss is known immediately as all the required trades are executed simultaneously.

Approaches for Triangular Arbitrage

There are different approaches of buying/selling the 3 assets to achieve triangular arbitrage. In this article we shall be considering two approaches.

Approach 1: BUY — BUY — SELL

BUY-BUY-SELL Approach of Triangle Arbitrage (Image by Author)

In the above example, we start with USDT as the initial investment. After performing the 3 trades, we are again left with USDT at the end. Here are the trades that will be performed:

  1. Buy Bitcoin (BTC) with Tether (USDT)
  2. Buy Ethereum (ETH) with Bitcoin (BTC)
  3. Sell Ethereum (ETH) for Tether (USDT)

At the end of the third trade, we can compare the final USDT with the initial investment that we started with in step 1. If this leads to a substantial profit then the 3 trades can be initiated simultaneously.

Approach 2: BUY — SELL — SELL

BUY-SELL-SELL Approach of Triangle Arbitrage (Image by Author)

Similar to the first approach, the same assets are used to check for arbitrage opportunities in a different flow. In the above example the following 3 trades are evaluated:

  1. Buy Ethereum (ETH) with Tether (USDT)
  2. Sell Ethereum (ETH) for Bitcoin (BTC)
  3. Sell Bitcoin (BTC) for Tether (USDT)

Trading algorithm — 4-step implementation

Here is an overview of the different steps to implement a triangular arbitrage trading algorithm. We shall be looking into each of these steps in detail in the next sections.

Step 1: Get all the valid crypto combinations
Step 2: Perform triangular arbitrage
Step 3: Place the trade orders
Step 4: Bundle it together

Before moving ahead with these steps we need to initialise the exchange to do the arbitrage. Select the exchange where you have a trading account and the one that supports api based trading. In this example I have used the WazirX exchange as I have a trading account in this exchange.

import ccxt
from config import myconfig
exchange = ccxt.wazirx({
“apiKey”: myconfig.API_KEY,
“secret”: myconfig.API_SECRET
})

The package ccxt supports various exchanges and in case you have an account in any of the other exchanges then you can get the same code working by just changing the exchange’s name in the above snippet. Refer to this page to get the list of exchanges supported by ccxt.

Step 1: Get all the valid crypto combinations

We need a base currency with the initial investment in our trading account to get started. Here we consider USDT as the base currency. Note that even fiat currencies like INR or USD can be considered as the base currency.

There are hundreds of cryptos supported by the exchange and hence we can derive different combinations to perform the triangular arbitrage. We can either hard-code to a limited set of combinations or allow the code to consider all the possible combinations available in the exchange. The below code snippet implements the second approach of identifying all the possible arbitrage combinations.

There are 543 crypto assets supported by this exchange at the time of writing this article.

Next extract all the possible combinations to apply the BUY-BUY-SELL and the BUY-SELL-SELL approaches of triangular arbitrage.

There are 63 different arbitrage combinations that the code was able to identify.

Eg: If a BUY-BUY-SELL algorithm has to be applied on the first entry, then:

  1. Buy BTC (intermediate) for USDT (base)
  2. Buy XRP (ticker) for BTC (intermediate)
  3. Sell XRP (ticker) for USDT (base)

If this circular trade can lead to a profit, then we are good to execute the 3 trades simultaneously.

Step 2: Perform triangular arbitrage

Pull the prices of the three assets from the exchange and identify the final price after performing the three buy/sell conversions.

Similarly the BUY-SELL-SELL approach also needs to be implemented. Only a snippet of the code is provided here to avoid code congestion. Please refer to the git repository linked in the end of the article to get the complete executable code.

Calculate the profit/loss in performing this triangular arbitrage by considering the exchange’s brokerage for each transaction and the minimum profit expected from the trade.

Step 3: Place the trade orders

Here is the code to execute the three trades on the exchange. If market price trade is not supported by the exchange, then a limit price trade needs to be executed. Limit price orders can sometimes cause the trading order to be stuck if the price has fluctuated before the execution of the order.

Step 4: Bundle it together

Wrap the above steps to a single package and run it for all the possible combinations.

For each combination perform the below 3 steps
(Example: Buy — BTC/USDT, sell — ETH/BTC, sell — ETH/USDT)

  1. Identify the final sell price after performing the 3 trades
  2. Calculate the profit/loss in making these transactions
  3. Place the 3 trade orders if the transactions lead to the desired profit

Results

Here is a sample result on running this code for one iteration.

An initial investment of 100$ was considered. With 63 combinations and 2 approaches, a total of 126 arbitrage combinations were checked and 26 of them showed a profit as below.

Sample Results from Triangular Arbitrage for 1 iteration

Note that the above table is from the logs and not from actual trades that were executed. Though this table shows a rosy figure, it may not always be a smooth ride in reality.

Why it might be a bumpy ride….

  1. Since all the three orders need to be executed simultaneously to realise the profit, there are chances that some orders don’t get executed on time due to network delays or issue with the exchange. In such a scenario you could be stuck with the cryptos and a manual intervention might be required.
  2. The crypto price considered here is the live ticker price. The prices can fluctuate before the orders are executed. Better approach would be to take the entries from the order book and choose the ticker price based on the volume.
  3. Three ticker prices are required simultaneously from the exchange to perform the triangular arbitrage. Some exchanges set a rate limit which does not allow repeated api calls. In such a case the api might throw a RateLimitExceeded (HTTP 429 Too Many Requests) exception. This can be handled by using a 1-second sleep timer between the api calls. But if the price changes within these couple of seconds then the orders may not execute.
  4. Some exchanges don’t allow to place orders at market price (like in my example). Limit price is required. In such cases, again there are chances that the orders don’t get executed due to the price fluctuation.

Code Repo

Refer to this git repo to access the complete code: TriangularArbitrageCryptos

Conclusion

Based on the exchange and the api support that it provides, the trading algorithms can be tuned further. Try playing around with the code by changing the base currency, using market price trades or checking on other arbitrage approaches.

Again, the disclaimer, this article is only for educational purposes and for you to understand the different types of trading options available. Remember that you are competing with several other trading bots out there. In case you want to experiment with real trades then first ensure that you have built a robust trading algorithm before venturing into it to avoid losses.

Additionally, if you are interested in wrapping this code within a trading bot application, use this article as a reference: Building a basic Crypto Trading Bot in Python

Thanks for reading till the end :-). Happy experimenting!!

--

--