Ventures of an ex indie game developer

Building a cryptocurrency trading bot tutorial, step 6/4

This is the last tutorial in a series of four. Six. Anyway. Previous parts can be found here: 1, 2, 3, 4, 5.

The best place to trade, afaik, is BitMEX. It's the biggest exchange. So that's what you should use. They also give you 0.25% when your limit order is taken, which is a big plus.

Start out by downloading my plotting library:
$ pip install -U finplot
Collecting finplot
  Downloading ...
Successfully installed finplot-0.3.2
Then we want to pull down some historic BitMEX price data:

#!/usr/bin/env python3

from collections import defaultdict
import dateutil.parser
import finplot as fplt
import pandas as pd
import requests


baseurl = 'https://www.bitmex.com/api'


def local2timestamp(s):
    return int(dateutil.parser.parse(s).timestamp())

def download_price_history(symbol='XBTUSD', start_time='2019-04-01', end_time='2019-07-07', interval_mins=60):
    start_time = local2timestamp(start_time)
    end_time = local2timestamp(end_time)
    data = defaultdict(list)
    for start_t in range(start_time, end_time, 10000*interval_mins):
        end_t = start_t + 10000*interval_mins
        if end_t > end_time:
            end_t = end_time
        url = baseurl + '/udf/history?symbol=%s&resolution=%s&from=%s&to=%s' % (symbol, interval_mins, start_t, end_t)
        print(url)
        d = requests.get(url).json()
        del d['s'] # ignore status=ok
        for col in d:
            data[col] += d[col]
    return pd.DataFrame(data)


symbol = 'XBTUSD'
df = download_price_history(symbol=symbol)
ax,axv = fplt.create_plot('BitMEX %s price history' % symbol, rows=2)
candle_datasrc = fplt.PandasDataSource(df['t o c h l'.split()])
fplt.candlestick_ochl(candle_datasrc, ax=ax)
volume_datasrc = fplt.PandasDataSource(df['t o c v'.split()])
fplt.volume_ocv(volume_datasrc, ax=axv)
fplt.show()

That code will get you this chart:
So you want to start trading. That means prototyping trades and simulating your gains/losses. That has a word in finance: backtesting. Your first step in backtesting is finding one or more so-called instruments to help you figure out a trading method. But first let's rename BitMEX's data columns to better understand what we're doing:

    df = pd.DataFrame(data)
    return df.rename({'t':'time', 'o':'open', 'c':'close', 'h':'high', 'l':'low', 'v':'volume'})

Now let's implement and visualize a few common instruments, such as accumulation/distribution and exponential moving average (EMA):

def plot_accumulation_distribution(df, ax):
    ad = (2*df.close-df.high-df.low) * df.volume / (df.high - df.low)
    df['acc_dist'] = ad.cumsum().ffill()
    fplt.plot(df.time, df.acc_dist, ax=ax, legend='Accum/Dist', color='#f00000')

def plot_ema(df, ax):
    fplt.plot(df.time, df.close.ewm(span=9).mean(), ax=ax, legend='EMA')

Other noteworthy instruments are Bollinger bands, Heikin Achi candle sticks, on balance volume, RSI and volume moving average. The full source (92 sloc) with those seven instruments can be found in github.

Online you'll easily find a ton of instruments, many in Excel, which are super-simple to implement and try out.

Backtesting

If you use market orders and/or stop-loss orders you must take market slippage into account as your orders fill. If you just use limit orders, that is not required, but you'll take additional risk as you're never sure if your orders will fill or not. Some of such risk can be mitigated by spreading out settlement orders, but at the cost of lower long-term profits.

Strategies

In BitMEX I recommend you use cross margin orders instead of isolated orders. That way you can set your own risk level, depending on the situation at hand.

Myself, I do short-term swing trading, which means I try to short when the price is high and long when the price is low. ('Short' means selling, actually borrowing someone else's money and selling; 'long' means buying in the same sense.)

Other ways I know of is to follow a trend or to scalp. All three ways can yield fantastic profits.

My robot's interest is in the vicinity of 30+% BTC. Per month. And that is low compared to some people.

Spikes

One highly relevant thing about trading on BitMEX is that it gets overloaded during the big spikes. If price suddenly drops one percent, a ton of people and robots are going to try to either short or long at the same time. That means that you have a low chance of placing orders during the most interesting times. Unfortunate as that is, you will have to find a strategy that works with that limitation:
  1. Post as many orders as you possibly can during hausse/baisse, until one or two finally goes through. And hope you don't get banned for spamming.
  2. Use long(er)-term strategies.
  3. Try to predict lows and highs in advance.

Good luck!

Creating trading robots is not for everyone. But after I two years ago decided I wanted to get rich, it is by far the easiest way I've come up with. Unfortunately I can't disclose my strategy, as that would invalidate my retirement/livelihood. With my earlier tutorials, these tips, and my finance rendering library, you only need to find a strategy of your own, and as soon as your backtesting shows black numbers you're good to go. All the best to ya!

About the author

Mitt foto
Gothenburg, Sweden