Build A Cryptocurrency Trading Bot with R
By: Brad Lindblad
Tags: Bitcoin, Investing, Trading, R Language, Cryptocurrency

Photo by Branko Stancevic on Unsplash

** Note that the API used in this tutorial is no longer in service. This article should be read for illustrative purposes with that in mind.

The trader’s mind is the weak link in any trading strategy or plan. Effective trading execution needs human inputs that run in the opposite direction to our instincts. We should buy when our reptile brain wants to sell. We should sell when our guts want us to buy more.

It is even more difficult to trade cryptocurrencies with a a critical constitution. The young and emerging markets are flooded with “pump groups” that foster intense FOMO (fear of missing out) which drive prices sky-high before body-slamming them back down to earth. Many novice investors also trade on these markets, investors that possibly never entered a trade on the NYSE. On every trade, there is a maker and a taker, and shrewd crypto investors find it easy to take advantage of the novices flooding the space.

In order to detach my emotions from crypto trading and to take advantage of markets open 24/7, I decided to build a simple trading bot that would follow a simple strategy and execute trades as I slept.

Many “bot traders” as they are called, use the Python programming language to execute these trades. If you were to google, “crypto trading bot,” you would find links to Python code in various Github repositories.

I’m a data scientist, and R is my main tool. I searched for a decent tutorial on using the R language to build a trading bot but found nothing. I was set on building my own package to interface with the GDAX API when I found the package rgdax, which is an R wrapper for the GDAX API. The following is a guide to piecing together a trading bot that you can use to build your own strategies.

The Strategy

In a nutshell, we will be trading the Ethereum — USD pair on the GDAX exchange through their API via the rgdax wrapper. I like trading this pair because Ethereum (ETH) is typically in a bullish stance, which allows this strategy to shine.

Note: this is a super-simplistic strat that will only make a few bucks in a bull market. For all intents and purposes, use this as a base for building your own strat.

We will be buying when a combination of Relative Strength Index (RSI) indicators point to a temporarily oversold market, with the assumption that the bulls will once again push the prices up and we can gather profits.

Once we buy, the bot will enter three limit sell orders: one at 1% profit, another at 4% profit and the last at 7% profit. This allows us to quickly free up funds to enter another trade with the 1st two orders, and the 7% order bolsters our overall profitability.

Software

We will be using Rstudio and Windows task scheduler to execute our R code on a regular basis (every 10 minutes). You will need a GDAX account to send orders to, and a Gmail account to receive trade notifications.

Our Process

Part 1: Call Libraries and Build Functions

We will begin by calling several libraries:

The package rgdax provides the interface to the GDAX api, mailR is used to send us email updates with a Gmail account, stringi helps us parse numbers from JSON and TTR allows us to perform technical indicator calculations.

Function: curr_bal_usd & curr_bal_eth

You will use your api key, secret and passphrase that are generated from GDAX in the API section. These functions query your GDAX account for the most recent balance which we will use repeatedly in our trading:

Function: RSI

We will use the RSI or Relative Strength Index as our main indicators for this strategy. Curr_rsi14_api pulls in the value of the most recent 14 period RSI, using 15 minute candles. RSI14_api_less_one and so forth pull in the RSI for the periods prior:

Function: bid & ask

Next, we will need the current bid and ask prices for our strategy:

Function: usd_hold, eth_hold and cancel_orders

In order for us to place limit orders in an iterative fashion we need to be able to pull in the current status of our orders already placed, and be able to cancel orders that have moved too far down the order book to be filled. We will use the “holds” function of the rgdax package to do this for the former, and “cancel_order” for the latter:

Function: buy_exe

This is the big-daddy function that actual executes our limit orders. There are several steps that this function works through.

1. Order_size function calculates how much eth we can buy, because we want to buy as much as possible each time, less 0.005 eth to account for rounding errors 2. Our WHILE function places limit orders while we still have zero ETH. 3. An order is added at the bid() price, the system sleeps 17 seconds to allow the order to be filled, and then checks to see if the order was filled. If it wasn’t then the process repeats.

Part 2: Store Variables

Next, we need to store some our our RSI indicator variables as objects so the trading loop runs faster and so that we don’t exceed the rate limit of the API:

Part 3: Trading Loop Executes

Up until now, we have just been preparing our functions and variables in order to execute the trading loop. The following is a verbal walk through of the actual trading loop:

If the current balance of our account in USD is greater than $20, we will start the loop. Next, if the current RSI is greater than or equal to 30 AND the RSI in the previous period was less than or equal to 30 AND the RSI in the previous 3 periods was less than 30 at least once, then we buy as much ETH as we can with the current USD balance.

Next, we save this buy price to a CSV file.

Then, we send an email to ourselves to alert us of the buy action.

The loop then prints “buy” so we can track that in our log file.

The system then sleeps for 3 seconds.

Now, we enter 3 tiered limit sell orders to take profits.

Our first limit sell order takes profit at a 1% gain, the next takes profit at a 4% gain, and the last takes profit at a 7% gain:

That’s it, that’s the entire script.

Part 4: Using Windows Task Scheduler to Automate the Script

The whole purpose of this bot is to take the human error out of the trade, and to allow us to enter trades without having to be present at a screen. We will use Windows Task Scheduler to accomplish this.

Schedule script with Rstudio addin

Use the handy Rstudio add in to easily schedule the script:

Modify the scheduled task with Task Scheduler

Navigate to the task created by the Rstudio add in and adjust the trigger to fire at the interval you wish. In my case I choose every 10 minutes indefinitely.

Keep an eye on your task with the log file

Every time your script runs it will make an entry in a text log file, which allows you to troubleshoot errors in your script:

You can see how the “START LOG ENTRY” and “END LOG ENTRY” print function comes in handy to separate our entries.

Make it Your Own

You can modify this script to make it as simple or as complex as you want. I’m working on improving this script with the addition of neural networks from the Keras module from Tensorflow for Rstudio. These neural networks add an exponentially more complex element to the script, but are incredibly powerful for finding hidden patterns in the data.

In addition, the TTR package provides us with a large number of financial functions and technical indicators that can be used to improve your model.

With all this being said, do not play with more money that you can afford to lose. The markets are not a game and you can and will lose your shirt.

Link to Full Source Code on Github