Algorithmic Trading in the Cryptocurrency Markets

Josh Playle
12 min readApr 11, 2018

--

Cryptocurrency exchanges are the perfect place to learn the ropes of algorithmic/autonomous trading. The London Stock Exchange charges £52,000 a year for access to live data from the exchange. In the crypto markets however, that data is entirely free on all of the exchanges. The markets are also young and small and therefore exhibit some rather large inefficiencies, which can be exploited for a profit. In the last ~8 months I’ve built a number of these trading ‘bots’ and, having tried everything and reached the conclusion that the crypto markets aren’t quite ready yet, decided to spill some insider knowledge.

For those not familiar: ‘algorithmic’ or ‘autonomous’ trading is the act of using a computer programme to execute a trading strategy on your behalf. That means it monitors data from the markets, makes decisions on what/when to trade and then executes the entire order process.

You might be wondering how on earth some computer code can decide whether it’s a good idea to open a trade on something, let alone something as volatile as a cryptocurrency. There are three categories of legitimate strategy available: arbitrage, market making and price prediction. This article will explore them all.

Arbitrage

Arbitrage is the act of profiting from a difference that theoretically shouldn’t exist. For example, Bitcoin is going for £10,000 on exchange A but you can get £10,500 for it on exchange B.

  1. Inter-Exchange Arbitrage

At one point in the crazy crypto flurry of Christmas 2017 the difference in the price of any given currency on CEX.io would be as much as 10% or more than the price for the same thing on Bitstamp. Let’s say you have a spare £1,000 lying around. All you have to do is deposit your money in Bitstamp, buy £1,000 worth of Ripple, send it to CEX (takes about 2–3 seconds) and then sell it there for 10% of what you bought it for. £100 bagged in a matter of minutes. All a trading algo has to do is sit and monitor the prices on a few different exchanges, wait for a nice profit to exist and then execute all of the necessary trades and transfers.

How is this possible? For the following reason. You’ve probably heard phrases on the news like ‘Bitcoin is an inherently volatile asset’, however that is a completely incorrect statement. The correct statement is: ‘the exchange(s) on which Bitcoin is traded have extremely low liquidity in comparison to the currencies which we’re used to’. Liquidity simply means the amount that is available for purchase/sale at any one time. The liquidity of the Forex market (where ‘normal’ currencies are traded) is roughly five trillion dollars a day. A big number, and there are only a handful of venues on which trading takes place. For cryptocurrencies the daily liquidity is roughly 10 billion USD (last checked January 2018). That’s 500 times less than the Forex market. Then consider that it’s spread out between literally hundreds of different exchanges and you can see how the liquidity is so thin per exchange. The fact that there are so many different exchanges is the first reason for big price differences. The second is that low liquidity leads to bigger price fluctuations, so it’s easy for the price to run away on one exchange or another if a few big orders come in.

Top right: GDAX, one of the biggest exchanges out there, has a 24 hour volume for Bitcoin traded in GBP of just 183BTC — roughly £915,000.

Unfortunately, this strategy will never work for the following reasons:

  • It is GUARANTEED that at some point the transfer of crypto from one exchange to another will break due to a lost transaction, insufficient miner fees, exchange errors etc. Some exchanges don’t even allow automated transfer of funds. I’ve had crypto transfers worth thousands go wrong that took weeks to recover. That is not fun…
  • The time taken for the transfer is too long or too expensive (although since I was first exploring this the Bitcoin lightning network has been introduced so maybe this point might be invalid now).
  • Even if the last two points weren’t true, the price difference is usually the same across all assets so you’re waiting to make a smaller loss moving funds back to exchange A than the profit you made in moving them to B. Otherwise you’ve wiped out any profits made in the first place, and this opportunity rarely crops up.

2. Triangular Arbitrage

You could call this intra-exchange arbitrage as, due to the reasons mentioned in the last section, it will only work inside a single exchange. This is possibly my favourite strategy and the best one available at the time of writing. I can confidently say that this is the only thing that will make you safe profits as far as cryptocurrency algo trading is concerned.

Tri-Arb works as follows: you monitor three exchange rates and wait for a time such that multiplying your money through each one would result in you having more at the end than you started with. For example, you buy £100 worth of Bitcoin and at the current rate that gets you 0.01BTC. With that Bitcoin you buy Ethereum and at the current rate that gets you 0.1ETH. Finally, the current ETH/GBP exchange rate means that when you sell your 0.1ETH it gives you back £105 — £5 profit. Here’s a diagram based on FIAT currency to illustrate what’s going on (it’s a bit confusing but you get the general gist):

The great thing about this is that you choose the trios such that they all start and end in the same currency. That means all your profits can remain in GBP/USD/EUR etc which are much more stable (and of course usable).

There are numerous exchanges on which this strategy works very well and I had an interesting time implementing it on OKEx.com. This exchange has markets for over 400 different cryptocurrencies, giving rise to 270 possible triangular arbitrage routes. The algo could only stream data for 100 of them due to limits on computational power. The average duration that a profit would be available for was anywhere between 10 and 100 milliseconds. That meant you had to recognise the profit and then conduct all three trades in that time, or a loss would be made. Given that the exchange is based in China, any messages sent from the UK would take way too long to transmit. A simple geo-location of OKEx.com’s IP address revealed that their service was being hosted in an Alibaba data centre in Hong Kong. I rented some computing power in the same data centre and the round trip of messages was down to microseconds. The game was on. Data gathering also showed that a great number of profit opportunities cropped up each day and some of them were as big as 25%. Yes, 25% — put £1,000 through the trade and get £250 out, which is absolutely insane. I was very excited. However, on running the algo some unexpected results were had. OKEx’s own servers could not update the account balance in the time between the first trade being placed and the next one arriving. That meant that the second trade failed because they thought you had insufficient funds for the trade. I conducted a number of experiments that ruled out all other possibilities. Extremely frustrating.

3. Statistical Arbitrage

This was one of, if not the first ever quantitative and autonomously executed trading strategies and still stands as a sturdy, profitable strategy today. I’ve not tried it on cryptocurrencies yet, but have implemented it for Forex. In this strategy you take the price history of two currencies and check for co-integration. The maths here is rather complex — enough to put most people off, so I’m just putting this in to show off:

Checking for co-integration in a nutshell.

If a co-integration exists then it means that the difference between the prices of the two currencies (known as the ‘spread’) remains fairly constant over time. When the spread is considerably different from the norm it presents a trading opportunity because the prices are likely to return to a position where the spread is normal again. This is known as mean reversion — returning to the average after a deviation away from it. If you’re going to use this strategy then aim to get as many currency pairs as possible in order to increase the likelihood of finding co-integrations. There are a couple of exchanges out there that this strategy could work well on and cryptocurrencies are volatile enough to make positive net returns theoretically possible.

Market Making

Arguably the second-best strategy to arbitrage. Market making is when you provide liquidity on both sides of the order book. That means you simultaneously have orders open to buy and to sell, except that the price your willing to sell at is always kept a bit higher than what you’re buying at. You’re constantly buying a currency and constantly selling it at the exact same time, with a markup. The profit per trade is small but you end up conducting a high volume of trades per day which can add up to a tasty profit.

  1. GDAX

When I first laid eyes on the BTC/GBP market on GDAX I was almost in disbelief. The spread (the difference between the price you could buy and then sell at) was as much as £100 at times. This is what the exchange looks like:

Order book for BTC/GBP on GDAX.

In the picture above the orders to buy are in green and those to sell are in orange. Therefore the best offer to buy is £4,910.03 and the best asking price to sell at is £4,912.44. The spread is only £2.41 in this screenshot but sometimes it stays at £15 and more for some time. The algo’s job therefore is to constantly track what the best prices are and offer liquidity at the best price on both the buy and sell side. Some logic is also used to predict whether the price is likely to go up, down or remain the same. The strategy only executes when the indication is for the price to remain or to go up.

When I first ran this algo it was incredible. It made 6% a day, every day for a few weeks, regardless of what the price of Bitcoin was doing. To put that into perspective — if that was kept up it would’ve been the most successful trading algo of all time in terms of percentage return on investment. If you don’t believe me — Google ‘Medallion Fund’. It turned £125 into £180 in five days. Not bad for just leaving your laptop on over night. But then one of two things happened — I started to implement improvements, namely use of the FIX API for those in the know, and either I broke something in the code or GDAX’s infrastructure went down the drain. After some time, the algo becomes severely out of sync with the order book that GDAX is showing on the website. I’ve implemented two different methods of maintaining the order book in the algo, both exactly as prescribed by GDAX and both suffer the same fate. Others online have also complained of the same problem. Given that it worked fine before, in a time just before cryptocurrencies hit the main stream, I’m going to shamelessly blame GDAX and put it down to increased load on their systems. Even GDAX’s own standard Python module for doing this becomes out of sync after a few hours.

2. OKEx (again)

Until roughly the first week of January 2018 this exchange offered a 0.1% return for a ‘maker’ order. A maker order is quite simply when you get there first. That means your order is open on the book at a certain price first and any subsequent orders with the same price will be matched to yours. Those subsequent orders are charged a fee of 0.1% because they are ‘taking’ liquidity off the exchange rather than offering it. So all this algo had to do was market make but every time it conducted a trade it made 0.1%, plus the market making profit (if any). That may not sound like a lot but when you’re doing hundreds if not thousands of trades a day that stacks up to a HUGE percentage return.

Developing this thing cost roughly $100 - at first most if not all orders were being executed as taker orders and therefore being charged a fee, due to the time taken for messages to travel from the UK to China inducing a massive lag. This led to the script co-location exercise described in the paragraph on triangular arbitrage on OKEx and running the code from Hong Kong improved the situation dramatically. All orders were now maker orders without fail. But it was still losing money? How could that be? A quick check of the website revealed that literally the day I’d got it ready they had changed their fee structure to charge ALL orders a fee now. You just can’t win.

To sum up market making: it is a great strategy but I’ve yet to find an exchange which has the triple combination of a viable fee structure, a live data stream that actually works AND the right setup to make meaningful profits. I’d love to be wrong though.

Price Prediction

This strategy deals with the most obvious thing you’d expect a trading algo to do: predict whether the price will go up or not. In order to do that you need to learn a bit about market micro-structure. The way an exchange works is as follows: you have orders to buy and orders to sell. Each order consists of two things: a price and a volume e.g. 300 shares at 50p a share. Once all of the orders at a given price have been completed, that price remains open for new orders to move into it. It is in this fashion that a price can increase, or decrease, from one point to the next. Therefore, the more action there is on a given side of the order book, the more likely the price is to move in that direction. If lots of the sell orders are being completed it opens up space for the buy orders to move into that space i.e. the price increases, and vice versa. There is a great YouTube video explaining this process in much more detail here:

The video references a paper, an excerpt from which is shown below:

Excerpt from ‘Price dynamics in a Markovian limit order market’. If you fancy implementing this strategy then the full article is available at: https://arxiv.org/pdf/1104.4596.pdf.

Equation 7 is the killer potion. It looks mind-blowing at first but actually 90% of it is just a constant so it can be simplified greatly, however there is no analytical solution so one must be found using the trapezium rule. Quite simple really. This equation gives rise to somewhat of a holy grail: a percentage likelihood that the price will go up or not. Having built and run a strategy using this equation as the indicator I’ve found it to be rather accurate and have had a few successful trades off the back of it. The real complexity comes in defining the amount by which the price will go up, if it does. The details on doing that are expressed in the paper (link in the photo caption) and are generally to do with looking at the deviations in the price levels i.e. are there any big gaps between prices — if so, the increase is likely to be greater and vice versa.

Price prediction in this manner is different from arbitrage and market making in that profits are more expectation based than opportunity based. That means that you need to gear your algorithm to have a positive expected return value over time. Say you establish that 80% of your trades are profitable and on average they make £5 per trade. The remaining 20% of trades are losses and you lose £10 on average per losing trade. The equation to work out what you’re expected net return over time is:

net_return = (%win_rate * ave%won(£)) — (%lose_rate * ave%lost(£))

= (0.8 * £5) — (0.2 * £10)

= £2 (average profit per single trade)

Then simply multiple the expected return per trade by the number of trades you expect to execute and that’s your total profit. As mentioned before I have experienced the price prediction method mentioned here to work well when applied to cryptocurrency markets. What remains unexplored is to predict the magnitude of price moves and see how accurate that can be.

In Conclusion…

After many months of building, testing and occasionally profiting from cryptocurrency trading algorithms, I’ve decided that it just isn’t worth it in the current market conditions. For the profitable combinations of strategy and exchange that do exist, the liquidity is so low that the returns aren’t even remotely enticing.

Couple that with the sometimes poor infrastructure, fee structures changing by the day (and being cripplingly high in a lot of cases) and usually rubbish documentation and support from exchanges and the whole thing can be a lot less fun than it should be.

For now, all you can do is keep an eye on the markets, stay current and be ready to launch some killer algos if/when the right conditions show up.

If you’re reading this and you’re a fellow algo/crypto enthusiast and you want to get involved/collaborate on a project then get in touch: joshplayle@hotmail.com.

--

--