I’ve been playing for the last three weeks with a fun project: Bitcoin algorithmic trading.
Kraken.com has a super easy restful api which allows to place orders with just a few lines of code. Using the api is free and you only need to pay 0.26% per trade.
For example, I can query my balance with three lines of code
<?php require_once ‘header.php’;
$res = $kraken->QueryPrivate(‘Balance’);
print_r($res);
?>
I can place an order to buy or sell bitcoin with nine lines
<?php require_once ‘header.php’;
$res = $kraken->QueryPrivate(‘AddOrder’, array(
‘pair’ => ‘XXBTZEUR’,
‘type’ => ‘sell’,
‘ordertype’ => ‘limit’,
‘price’ => ‘1200’,
‘volume’ => ‘0.0001’
));
print_r($res);
?>
I can query the last trades executed in the market in three lines
<?php require_once ‘header.php’; $res = $kraken->QueryPublic(‘Trades’, array(‘pair’ => ‘XXBTZEUR’,’since’=>’1486857244103748648′));
print_r($res);
?>
These three functions are all is needed to be able to build a program that looks at the direction the trades are going, check my balance and place an order.
I had a stroke of insight, an algorithm which could not fail: “If the last three trades are going up, buy it all. If the last three trades are going down, sell it all, else wait” I thought to myself my first lamborghini would be orange while I got to work building the program.
Instead of letting it loose with my money I thought it would be a good idea to backtest it first, to simulate how my algorithm would fare.
You can download the whole history of bitcoin trades for each market here. The following script scheduled with cron to run every morning at 5:00 am downloads the whole history of prices, loads it into a mysql table, runs my algorithm and outputs a file with each decision taken.
#!/bin/bash
cd /home/roge/programando/kraken/histdata
wget http://api.bitcoincharts.com/v1/csv/krakenEUR.csv.gz
gunzip -f krakenEUR.csv.gz
cd ..
mysql kraken <truncate_krakenEUR.sql
mysqlimport kraken –local histdata/krakenEUR.csv –columns timestamp,price,volume –fields-terminated-by=’,’
mysql kraken <create_ruleofthree.sql
php backtest_ruleofthree.php >backtest_ruleofthree.output
the output is 4.8 million lines long so I thought I’d use big data analysis tools such as jupyter/pandas/matplotlib to see what my algorithm had done in a nice chart. Below you can see how my algorithm is super efficient at giving all my money to kraken in fees. In less than 30.000 ticks I would have blown through all my savings. Back to the drawing board 🙂