Tracking Your Cryptocurrency Portfolio With Serverless Functions

Monitor your Bitcoin hoard with IBM Cloud Functions writing data to Cloudant

The value of crypto-currencies can vary greatly over time. If you’re lucky, some coins bought for a handful of dollars a few years ago can be worth thousands of dollars now.

At the time of publishing, the value of 1 Bitcoin jumped even higher to $7,174.60.

There are many websites and apps that can help you monitor your portfolio, but what’s the fun in using a ready-made solution when you can build your own?!

Crypto pricing API

We can use an API from CryptoCompare to get the latest price of Bitcoin and Ether, two popular coins, in US dollars. We can call the API passing the symbols BTC, ETH and USD as parameters. For example:

For a single currency, we can use an even simpler call:

Retrieving the data every minute

We can write a script to fetch this data every minute, writing a document to a Cloudant database each time.

The Node.js script to do this is very simple:

The main function expects the Cloudant URL to be supplied as the url key in its args parameter. It calls the API and creates a JSON document which is written to Cloudant:

The _id is the unique key for each Cloudant document. Here, it is actually a timestamp (the number of milliseconds since 1970) which will be unique and in time order for our "once per minute" polling of the API.

All we need now is to call the “main” function every minute.

Going serverless

We have a number of options here:

  • We could write a Node.js script that is on 24/7 and use a JavaScript setInterval timer to call the main function every 60000 milliseconds.
  • We leave the script doing a single execution as it does now and call it every minute using cron — a task scheduler found on most Unix-like systems.
  • We could push our script to IBM Cloud Functions, IBM’s serverless platform, and instruct it to run it for us every minute.

We put the URL of our Cloudant service in the environment variable CLOUDANT_URL and run a series of commands to deploy our Node.js file to IBM Cloud Functions:

The first two commands deploy the code, the last three trigger the code to be run every minute using the alarm package.

Once deployed, we should see the documents appearing in our Cloudant bitcoin database:

Querying the data

Once we’ve left our data collection script running for a while, we can query the data using Cloudant’s API. Our data is already sorted in time order because we used a timestamp as the key _id field.

We can therefore get the first two hours of data:

The most recent hour of data:

The most recent data point:

Aggregating the data

Cloudant’s MapReduce system allows custom indexes to be created by supplying a JavaScript function which is executed over each document in a database.

We can use a function like this:

Here’s what it does:

  • turn the _id field into an integer
  • parse it into a JavaScript Date object
  • extract the year, month, day, hour, and minute
  • emit a key/value pair where the key is the array [year, month, day, hour, minute] and the value is the bitcoin price
The Map function above, as displayed in the Cloudant dashboard, along with it’s built-in Reduce function, _stats.

Combined with the built-in _stats reducer, we can use this index to create hierarchical aggregations of the bitcoin price:

The above query asks for all of the data grouped by year and month. Notice how the _stats reducer gives us a sum/count/sumsqr (which we can use to calculate mean, variance, and standard deviation) and the maximum and minmum value per month. The group_level parameter indicates how many levels into the key we wish to aggregate. For example:

  • group_level=1 - year
  • group_level=2 - year/month
  • group_level=3 - year/month/day
  • group_level=4 - year/month/day/hour

We can also specify a startkey and endkey to limit range of data we want to report on:

The above command asks for year/month/day data for the month of October 2017.

What’s next?

We could do more than just record the data. We could calculate technical indicators and use them to predict whether the market is heading upwards or downwards. We could send emails or alerts when certain market conditions prevail. We could write an algorithm that decides when it’s a good time to buy or sell and call a third-party API to actually make crypto-currency trades.

I’m not that brave, so I wrote a trading simulator that allows you to simulate crypto-currency trading using the last 2 hours of bitcoin data. You start with $5000 of cash and $5000 of bitcoin. Trade as many times as you like and see if you end up with more than $10000 at the end of the game.

Demo deployment of the Market Trader cryptocurrency tracking app.

Try it for yourself: https://glynnbird.github.io/markettrader/public/index.html . You can also find the code on GitHub at https://github.com/glynnbird/markettrader — cheers!