DEV Community

Mar Bartolome
Mar Bartolome

Posted on

A first attempt at Bitcoin trading algorithms

Algorithmic trading is not a novel idea. In fact it seems to be quite a researched topic, and it's not difficult to find resources about it online. From strategies, to code libraries, to people sharing algorithms on github.

In or case, we wanted to use it to invest on bitcoin or other cryptocurrencies. To invest you need an exchange: a place that you let you buy and sell bitcoin in exchange for "real money" (eg, dollars or euros). In the last years several of them have surged and become established, most notably perhaps Coinbase and Kraken.

And the best news - these exchanges offer a public API, that you can use in your algorithms for automatic trading. Sweet!

Simulate first

Playing with the exchanges themselves however would require investing real money. Also, they charge a rate for every transaction, so before recklessly toying around we should first find a decent algorithm while testing on a simulated environment.
And so, we set ourselves to the task. We made a little python script that would simulate the interface with the stock exchange to buy or sell. You can feed a CSV file to the script with the historical exchange rate, so that it can replay it.

You just need to search google to quickly find some historical data for stocks. For bitcoin data a good source is the Bitcoincharts API.

The algorithms

On top of that toy environment we set to build a couple algorithms, and set them to compete against each other:

  • simple algorithm: keeps a constant amount invested in stock at all time. If the price goes up, it extracts the profit difference with the original amount. If the price goes down, it buys up new stock until it reaches the investment amount.
  • pirate algorithm: based on this algorithm that we found on github. It keeps track of the value at which you bought or sold a bit of stock. If the price goes further down that you bought it for, it will sell it to avoid loss. If it goes up it will rebuy it.
  • static algorithm: buys full amount of funds and simply waits. No fuss investment! It will basically produce profit or loss depending on the longterm evolution of the market.
  • random algorithm: it will randomly buy or sell a fixed amount.

These are not very sophisticated strategies, but they are a starting point. Now the next step would be to simulate them running against the historical exchange rate data for bitcoin, and see if they would have made us any money had we set the algorithm to run some time ago in the past.

Results

We simulated the run of these algorithms over the last year of bitcoin historical data, over an investment amount of $1000. The resulting benefit in USD was a follows:

static simple pirate random (3-run average)
252.244923 486.14863 -999.957644 1204670.35464

Interestingly, it seems that the best strategy is by a huge margin the random one! Our simple algorithm turned to be a slight improvement over the static "invest and forget" strategy, yielding double the amount of benefits. The pirate algorithm turned out a huge disappointment and made us loss practically all of our investment amount. The surprising results come from the random algorithm, which yielded a x1000 ROI.

Is our conclussion then that the best investment strategy for the stock market is to buy and sell randomly? Well, let's not go that fast. Consider that the shape of the exchange rate curve might have much to explain.

Notice how bitcoin has had an exponential growth during the last year. Under this sort of conditions, no matter what you do, the market is going to be on your favor. Under this kind of curve, constant mindless selling and buying is of course what is going to make you right, rather than being more conservative with your money.

Lets see what's the difference when running the same set of algorithms over just the last month of June, in which there was a strong volatility but not a noticeable diff in the exchange rate.

static simple pirate random (3-run average)
-41.3003 -31.1976 -81.3840 -18.3573

There was indeed a small loss in the value of bitcoin, which is reflected by the static strategy. Our simple algorithm was not a huge improvement here, it managed to mitigate the loss a little bit but not in a significant way. The pirate algorithm proves to be just as terrible, while the random one now shows its limitations.

Conclusions

Algorithmic trading is easy to implement, but difficult to come up with a strategy that will make you rich. If there existed a way, be sure that the best data scientists in the world would have already found it, and everyone would be using it. Predicting when is the best time to sell and buy is difficult even for expert human stock traders after all!

Even with one strategy, there's lots of fine tunning to do in terms of amounts, timings and optimizations that we didn't try in our experiments. Also not all stock shapes look the same, and different algorithms might perform differently depending on the characteristics of the stock type. For example, some stocks might exhibit more volatility, others are more stable, some have a higher price than others and might perform better if you algorithm is willing to invest bigger rather than smaller amount.

Even having this into account, what is for sure going to make you money is picking a market that goes up rather than down! It is unlikely that an algorithm can create a profit when prices are going down. At most, it can try to mitigate the losses, but picking a winning stock is the only way to generating benefits.

And last but not least: in our setup we didn't consider the particularities of the exchange services, namely, the fees. An exchange service will charge fees normally per transaction, so having this into account is fundamental when designing your algorithm, or you might loose any earnings simply paying for fees. The fees are different with every exchange service, but normally they are expensive for small quantities and after a level they even out. Exchanges that are friendlier and more accessible for beginners (for instance coinbase) are also more expensive than others.

You can find our algorithms and the sandbox code in our github.

This post was originally published on coconauts.net

Oldest comments (9)

Collapse
 
pratikaambani profile image
Pratik Ambani

Awesome job dude. πŸ‘πŸ‘πŸ‘

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn

Good read, awesome info! I co-founded a CryptoCurrency index fund which obviously doesn't do algorithmic trading but we have looked into it.

I think most these algorithms fail when you introduce fees though. The trade volume will kill you after a while and I'm afraid the profit simply wouldn't be high enough.

I still believe that in order to make money with Crypto, you need to buy and hold, actively wait for the prices to drop and then buy in (Never sell, just always buy low!) or get into the right ICO (which requires a lot of research).

Collapse
 
tyvdh profile image
Tyler van der Hoeven

I built an algorithmic trading bot on the GDAX API awhile back and came to the same conclusion. It's not about making killer profit in the short term, it's about making a faster, smarter, more patient human. Once you accept that and build for that, it becomes a lot easier to turn a profit.

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn

Yeah, I think a script that watches for big drops might be worth it. Just have it automatically buy when the price drops a certain amount and bounces back. You wouldn't always be buying at the best possible moment but I think you could make a killing in the long run.

I do believe Crypto is a buy & hold play anyway and I'm not planning on selling in the next 5 years so these extra profits don't make a dent in the much larger profit you get from holding for a while.

Collapse
 
blowjobs4btc profile image
blowjobs4btc

i have a bot that interfaces with kraken. I use moving averages as buy sell signals, which works okay, but isn't giving me my expected 47,385% weekly returns, sadly.

I am in the process of expanding the code to examine any arbitrary number of currency pairs, such as btc/ltc, btc/xmr, xmr/eth, xrp/usd and so forth. The idea will be to buy the pair that has crashed the most (oversold) in the last N interval with the expectation that market forces will cause it to rise. Come over to reddit and lets get a community going and develop a model that works and pays off. /u/mkultra_xerxes

Collapse
 
djnasir profile image
Forex Trader!

It is not so simple to do Bitcoin trading. But I realized that it is the BEST way and that happened thanks spretting.co.uk, who guided me so brilliantly with spread betting and all those. Plus, I came across Plus500 broker under whom, it was so easy to do Crypto trading. It’s since then that everything has worked perfectly for me.

Collapse
 
littlelittledream profile image
LittleLittleDream

There has long had a platform for bitcoin quantitation trading on the Internet. Since 2013, the platform named "BotVS" has been built. At that time , Some of early bitcoin trader knows use a hedge strategy to let theirs bitcoin appreciation. Afterwards these people got their abundant benefits as bitcoin price rise and hedge strategy profits created.
I think the Programmed Trading is so cool!

Collapse
 
spanual2000 profile image
Bitdroid

I don't really get what you want to know by doing this. I wish people could see something really quite obvious which is: you can't apply any rule, any analysis based on price, price is a random variable, I assure you.

How price got to be that price wasn't random, but when you look back at it as a single point, that price, it is random.

Let me explain..

The amount of variables that dictated that price outcome for a particular point has a complexity factor that is through the roof! The result of that doesn't hold any state or memory of any of that, if you process many of these points you miss out the complexity.

When something is complex and you observe a fraction of it or know or understand a fraction of it, the rest of it is a disturbance that is a random factor to you, not to itself.

The only way to predict price is to understand that complexity which is impossible.

Therefore the only way to predict price is by not predicting price, but in the market is an environment of traders, traders who want to exit, want to enter and they display this intention through action and placing limit orders, the reaction from each of these points through time paint a story about these types of traders who are reacting to price.

If you want to predict price you predict these groups and establish entries and exits, by predicting people or traders which is mostly about relationships not factor allows price to confirm your thoughts which is your edge.

I took this project on because I want to spread what I know, I believe I have a rare form of synesthesia that allows me to see complexity as weights, heavy/light.

I developed Bitdroid which is accurately predicting to some large significance (at least with a strong edge) and is profiting after fees too.

It just pains me that people think they could predict something so complex by addressing it directly, addressing that massive complexity, it's not possible.

If you are interested in what I wrote please do check out bitdroid.co.uk

You won't find something like this published but as you can see I am passionate about educating people, this was written fast my apologies but I just had to post.

Collapse
 
tradedude profile image
Trade Dude

I'm sure it's not that hard to code an algorithm but to come up with one. Investment banks spent millions and millions on their trading algorithms and it wasn't the cost of coding.