Bitcoin Trading Bot using bitFlyer Lightning APIs

In this article, we will learn how to build a trading bot using bitFlyer Lightning APIs. We will develop a strategy to accumulate Bitcoin based on Simple Moving Average. In addition, we will also backtest and optimize our trading bot.

bitFlyer lightning is a crypto trading platform majorly supporting spot and futures markets for Bitcoin.

bitFlyer provides extensive APIs for their exchange. You need to sign up and verify your account to access the bitFlyer’s APIs.



How to use bitFlyer’s APIs?

bitFlyer lightning provides Rest APIs and Websockets for accessing exchange data.

Here, you can access the complete documentation. In addition, we also provide an API Playground using which you can call our APIs directly from your browser.

Let’s understand with an example.

Getting Markets

To get markets available on bitFlyer exchange, we need to call markets API. In the following example, we are calling the markets API and parsing the results into JSON format.

import requests
import json

API_ENDPOINT = 'https://api.bitflyer.com'


def convetStrToJson(str):
    return json.loads(str)


def getMarkets():
    url = API_ENDPOINT + '/v1/markets/eu'
    response = requests.get(url)
    response = convetStrToJson(response.text)
    print(response)
    return response


getMarkets()

Getting Balance

Now, let’s see an example where we will need our API Keys and secret. This time, we will get our balance from the bitFlyer lightning exchange.

To accomplish this, we need to call getbalance API. This request needs authentication.

Therefore, we need to pass headers with the following fields.

  • Content-Type — application/json
  • ACCESS-KEY — You API Key
  • ACCESS-TIMESTAMP — Unix timestamp
  • ACCESS-SIGN — Signature

Here creating signature is the only tricky part. To prepare it, we need to create a string of 4 parameters.

  • Current timestamp
  • Type of request (ex- Get, POST)
  • The API we are calling
  • Request Body

Then we need to prepare a cryptographic signature as mentioned below.

signature = hmac.new(secret.encode('utf-8'), text.encode('utf-8'), hashlib.sha256).hexdigest()

Here, secret is our API Secret, which we got from the bitFlyer, and text is the string we prepared using the 4 parameters mentioned above.

To see the results, just adds your API key and secret in the following script and run it.

import requests
import json
import time
import hmac
import hashlib
import base64



API_ENDPOINT = 'https://api.bitflyer.com'


key = 'YOUR_API_KEY'
secret = "YOUR_API_SECRET"



def prepareHeaders(method, path, requestBody):
    timestamp = str(time.time())
    if requestBody == '':
        text = timestamp + method + path
    else:
        text = timestamp + method + path + json.dumps(requestBody)
    signature = hmac.new(secret.encode('utf-8'), text.encode('utf-8'), hashlib.sha256).hexdigest()
    headers = {'Content-Type': 'application/json',
               'ACCESS-KEY': key,
               'ACCESS-TIMESTAMP': timestamp,
               'ACCESS-SIGN': signature}
    return headers


def convetStrToJson(str):
    return json.loads(str)


def getMyBalance():
    url = API_ENDPOINT
    path = '/v1/me/getbalance'
    headers = prepareHeaders('GET', path , '')
    response = requests.get( url + path, headers=headers)
    response = convetStrToJson(response.text)
    print(response)
    return response


getMyBalance()

Building Trading Bot

Now, we know how we can call bitFlyer APIs directly, we will leave it there. Now, we will start building our Trading bot, however, for this, we will use a library called CCXT, which already provides an easy way to access bitFlyer exchange APIs.

Prerequisite

To follow this part, you must have some prior programming experience. We will be going to install the following libraries to fetch bitFlyer data and code our trading strategy.

  • CCXT — An open-source library to work with crypto exchange APIs.
  • Pyalgotrade — An open-source library for the algorithm traders.

Note: I am using Ubuntu 18.10 and Python3.8.

Project Setup

Let’s set up our project now. If you don’t have python, you need to install it. You can follow these instructions. In addition, the guide also helps you use python virtual environment, so you don’t install project dependencies globally.

1/ Create a directory

mkdir bitFlyer-trading-bot
cd bitFlyer-trading-bot

2/ Set up and activate the python environment

python3.8 -m venv env

source env/bin/activate

3/ We also need some additional libraries, let’s install them to

pip3.8 install ccxt
pip3.8 install pyalgotrade
pip3.8 install pandas


sudo apt-get install python3.8-tk

Note: At the time of writing this,there is a bug in the ccxt library. Currently, it does not point to the latest bitFlyer API endpoint. To correct that, follow the below steps:

nano env/lib/python3.8/site-packages/ccxt/bitflyer.py

Change api param to ‘api’: ‘https://api.bitflyer.com’ . It should look like below.

Getting Data

Now, we will fetch bitFlyer candle data using ccxt library. So create a file named bitflyer-fetch-ohlcv-to-csv.py in the directory and copy-paste below code.

Once pasted, run below command to run the file, it will fetch the bitFlyer 1-minute candle data and save in a file named sampledata.csv

python3.8 bitflyer-fetch-ohlcv-to-csv.py

Building Strategy

We will create a strategy to accumulate Bitcoin. Therefore, our strategy will help you identify the best prices to enter the market using the Simple Moving Average(SMA).

We will find the best price offset to buy Bitcoin. In addition, we will also configure the parameters below.

  • Capital available for trading — 90,000 (In our example)
  • How we will calculate SMA
  • Buying percentage(buy_percent) — Maximum portion of the balance that can be used to buy Bitcoin
  • Price offset (offset) — Price offset to enter and exit the market

Here we are using pyalgotrade, a python library for backtesting trading strategies.

For now, create a file named accumulator.py and copy-paste the following code.

BackTesting Strategy

Backtesting is testing your strategy using historical data. Now, it’s time to backtest our strategy. In addition, we will also plot the results of the backtest.

For that, we will create a file named strategy.py and copy-paste the code following code.

Running Backtest

Now, use the command below to run the backtest.

python3.8 strategy.py

It will pop-up a chart image. That will show the following information

  1. Price and SMA with entry and exit position marked
  2. Our portfolio performance
  3. Return from our strategy

Optimizing the Strategy

Of course, you can tweak different parameters(buy_offset, buy_percent) to optimize the returns. However, we will write a simple program to check all the different combinations of our parameters.

For that, create a file named optimiser.py and copy-paste the following code.

Now, let’s run this file

python3.8 optimiser.py

It will output the combination of buy_percent and buy_offset, which will provide the best returns for our strategy.

Wrapping Up

Let’s recap what we did today. We created a simple Bitcoin accumulator strategy using the Simple moving average. Then we backtested and optimized our strategy for best returns.

You can find the complete code for our trading bot on Github. Also, check out the bitFlyer lightning APIs to create your own trading strategy.