Trial and Epic Fail

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 = ''

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)
        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)

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.


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.


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.


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!

Saw a UFO this morning

Half-way between the sun and the horizon this morning there was a shiny, reflective object. I saw it for a second or two, and then it was gone. If it was a plane, it sure did disappear fast.

Constant gains

This is the first high volatility turning-point my bot has gone through. It's not doing badly, but the high risk, high return takes its toll on me. And although it's doing good, it's not as good as it could. Here is the last few days' fluctuations in my funds:

So the green stuff is the good stuff. I could do without the red stuff. And the overall gains could be better (+18% is a wee bit weak considering the fluctuations).

But could I have the cake and eat it with my current algorithm? Possibly so. A few minutes looking at charts and tinkering with my trading and optimization algorithms have led me to belive I could do better in both smaller and bigger fluctuations. Key seems to be more and smaller orders, as well as lower progression for larger spikes. My backtesting optimization is in full swing now, I'll know more in a day or two.

Extreme greed again

Yet again the Fear & Greed BTC Index has reached unprecedented levels.

To me it looks like whales have joined together, not to push the price up, but to never let it drop. This is a dangerous time for my puny robot which relies solely on the constant ups and downs of a free market.

So far I'm down another 13%. Last run my funds went down 21% until settling at -12%. This one looks worse.

When will they let go? If they push this one really far, me and a lot of other people are going to go bust along the line. My guess is that's not what they want either, as they feed off of bad traders (who feed off of worse traders). Hopefully they'll just make another big spike and then let go for some time to allow me to lick my wounds for a couple of percent.

My profitability estimates were slightly off

... but I'm not crying about it.

The yellow and blue lines are my predictions for when I would return my losses in my big high-risk experiment. It's not too long until I return to all time high BTC, and from there only +200% or so until I certainly reach all time high fiat. :-]


Volume and volatility is back in crypto. My daily gains in the last 80 days are in the vicinity of 0.4% per day. Which is amazing. However, two days ago BitMEX saw the highest volume ever recorded. And prices are not allowed to drop dramatically, as greed is building. My guess is that the price is going to start dropping in a week or two. Which will further increase volatility. Perhaps I'll even reach 0.5% per day.

To put it in layman's terms: if I keep this up for eight years straight, even if Bitcoin price stays on this level, I'll be the richest man in Sweden. ;)

9.1% done

I was off by two days in my most optimistic prediction, and today Musk hit the mark. Not bad.

About the author

Mitt foto
Gothenburg, Sweden