Algorithmic trading with bitcoin – part 1
Hi and welcome back to my blog! This is the very first te a series of articles which describes the process of building a trading algorithm for bitcoins. All the algorithms featured will be live tested on a real bitcoin exchange and results of profitability given.
I will discuss the problems with commonly used trading algorithms, indicators and adverse selection.
It’s aimed primarily at programmers albeit the content ought to be readable enough ter general to interested traders.
Readers unacquainted with algorithmic trading ter general should read my primer on the subject.
- There is very little documentation on the internet which covers the various different technologies and processes required to build a algorithmic trading framework for bitcoin.
- Bitcoin exchanges have now reached a point where there is sufficient liquidity to make live testing feasible without waiting hours for a trade to occur.
- Unlike te Forex, bitcoin trading cuts out the middle-man, there is no broker taking his cut of your profits, you overeenkomst directly with the exchanges yourself.
- There are bitcoin exchanges which suggest zero trading fees, which is very attractive and totally unheard of ter Forex.
Which exchange to chose?
Spil I write this, there are approximately 100 bitcoin exchanges to chose from. So how to pick the right one?
My requirements are:
To my skill there are only two exchanges suggesting zero trade fees at the uur. BTC China and Huobi – both of which are Chinese exchanges, but the websites do have english sections, if you can find them. You can deposit and withdraw bitcoins instantly from both exchanges so needing access to Chinese Yuan isn’t necessary, fortunately! Both also suggest API access.
Taking a look at a graph of the same time period ter both exchanges gives some idea of the liquidity difference:
The above are graphs from the 1 minute time period, notice the gaps te the BTC China graph te the earlier part of the time period compared to the Huobi graph? That is a difference te trade frequency which goes palm ter mitt with liquidity. A closer look at the traded volume for both exchanges (enlarged from above) during the same period is exposing:
Ten BTC traded on BTC China
200 BTC traded on Huobi
So, Huobi has overheen 20 times the traded volume and has a higher trade frequency than BTC China making it the best choice.
The Huobi API
The Huobi API is somewhat quirky and inadequate ter a few places. Ter particular:
- Every authenticated request vereiste include a created field which is a unix timestamp. Unluckily, their server’s clock is about 1 minute 30 seconds behind actual UTC, which means you have to offset the values you send to compensate, otherwise you get error 70 back from their API.
- They have a rate limit for every API call of 1 2nd, and each call has individually monitored boundaries. However ter practice I found I actually needed to wait 1.Five seconds inbetween calling the same method twice.
- The only way to get public trade gegevens from their API gives back a structure which is very lacking, the time returned is a string with no date component and there is no trade ID which means differentiating inbetween old and fresh trades is unlikely with absolute certainty.
- During periods of high activity it is very common for API requests to fail or timeout, so you vereiste implement a sturdy error treating and retry policy.
All prices submitted to Huobi voorwaarde be truncated to Two decimal places. All amounts should be truncated to Four decimal places.
The documentation can be found here:
To save you the trouble of implementing this all yourself, please take a look at the C# Huobi API I have made available on Github.
The trading framework
The trading framework itself is very much more than just API access to Huobi. Te particular wij want to be able to visualise:
- The price act ter graph form te real time
- Our buy/sell orders which have bot placed by the algorithm(s) at the location on the graph where they occurred
- Whether said buy/sell orders were actually packed
- Profit/loss chart
Trading act on left, profit/loss on right
Something like the above is indeed fairly necessary te order to quickly help identify problems with trading algorithms and to give an idea about the profitability.
Terugwedstrijd on investment, or ROI is used to spil the profitability measure of each algorithm, this way the amount of BTC invested doesn’t affect the displayed profitability because its a relative percentage. This permits you to get consistent results inbetween tests spil your balance switches. You calculate ROI by taking a snapshot of the amount of fiat and BTC you have at commence time, then convert fiat into BTC using the current mid price (bid + ask) / Two and subtract what you have now from what you used to have, then divide by what you used to have and multiply by 100 to get a percentage.
decimal totalBtcValueStart = m_startInfo.m_TotalCny / midPrice + m_startInfo.m_TotalBtc, decimal totalBtcValueNow = infoNow.m_TotalCny / midPrice + infoNow.m_TotalBtc, decimal profitPercent = 100*(totalBtcValueNow – totalBtcValueStart) / totalBtcValueStart,
The price series
Raw tick gegevens is used spil the price series because candlesticks hide too much information.
The framework should provide a modular system within which to attempt numerous different algorithms. To that end I have a class AlgoBase which each algorithm I’ll describe ter this series derives from.
AlgoBase defines a number of utility functions, like CancelOpenOrders() and CalculateProfit() and also provides a virtual Update() function which each algorithm can implement. This Update function is called at regular intervals by the main program and is where the trading actually occurs.
The choice of algorithm to implement is governed by a few fundamental truths, learned from practice:
- Trading using ‘technical analysis’ simply does not work
- Indicators only work on one predefined timescale, yet the market is permanently switching
- Attempting to make indicators adapt to the market is like attempting to gezond a square peg into a round crevice
- The only true sources of information are the orderbook and trade history
With thesis points te mind, the very first set of algorithms I’m going to explore is the Market Maker(s).
A market making algorithm is one which posts limit orders on both sides of the book, attempting to make profit by providing liquidity to antsy traders who have an opinion about the future direction of the price (alpha). Thesis class of algorithms are directionless, te that they do not make profit from the directional movement of the price, but rather from pairs of buys and sells, buying price being lower than selling, of course.
The key problem for the market marker is that of adverse selection.
Adverse selection is when your buy order gets packed but then the price falls, leaving the twin sell order unfilled. The same thing can toebijten with sell orders, when the sell is packed and price raises.
Ter the above picture, white arrows represent unfilled orders, crimson arrows are packed sell orders and green arrows are packed buy orders. The price is the crimson line. Notice how the very first sell order gets packed and then the price goes up, leaving the twin buy order unfilled? The same thing happens to the next three buy orders. If the unfilled orders had bot packed, each would have bot a profitable set of trades, but due to adverse selection each wasgoed a losing trade.
To demonstrate this problem, the very first market making algorithm I’m going to explore is the naive market maker.
The Naive Market Maker
The naive market maker places buy/sell orders at the best bid/ask price te the book at each update period. The idea being to capture the spread each time and make the associated profit. The algorithm is plain:
- Cancel all open orders
- Place two fresh buy/sell orders at the best bid/ask te the orderbook
The results of live testing this algorithm for 6 hours on Huobi are illuminating.
Click to increase
It consistently suffers the adverse selection problem, losing an outstanding 2% of invested BTC overheen the 6 hour period! Te addition, because of the erratic movement of the best bid/ask prices, adverse selection losses are exacerbated because often pair trades are part packed, price moves away, algorithm re-prices, opposite trade gets packed and price moves back again, losing on both sides of the trade.
Dealing with adverse selection
Ter the next article I’m going to talk about dealing with adverse selection. Ter particular I’m going to explore the academic literature on the subject and whether technologies like those described by Glosten and Milgrom actually still have any relevance thesis days te practice.
You can access the source code accompanying this article via this GitHub repro. It contains the Huobi Api and everything else I’ve described here so far, including the Naive Market maker.