CryptoTrading bot with R (No real transactions, beginner friendly)

Brenda Leyva
MCD-UNISON
Published in
6 min readDec 28, 2020

This program is not meant for real trading, the goal is to understand a few concepts on cryptotrading and how it can be automated based on certain strategies.

Image created with R : source code

Before going ahead and trying this for yourself, you will need to go to Binance.com and create your own API key.

The first few steps in developing this project consist in understanding the concepts on which we will be supporting the trading strategies. As a quick summary:

Bitcoin: Is a digital currency created in January 2009 following the housing market crash. It follows the ideas set out in a whitepaper by the mysterious and pseudonymous Satoshi Nakamoto. The identity of the person or persons who created the technology is still a mystery. Bitcoin offers the promise of lower transaction fees than traditional online payment mechanisms and is operated by a decentralized authority, unlike government-issued currencies.

MACD — Moving Average Convergence Divergence: Is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price. The MACD is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA. The result of that calculation is the MACD line. A nine-day EMA of the MACD called the “signal line,” is then plotted on top of the MACD line, which can function as a trigger for buy and sell signals. Traders may buy the security when the MACD crosses above its signal line and sell — or short — the security when the MACD crosses below the signal line.

RSI — Relative Strength Index: The relative strength index (RSI) is a momentum indicator used in technical analysis that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset. The RSI can have a reading from 0 to 100. Traditional interpretation and usage of the RSI are that values of 70 or above indicate that a security is becoming overbought or overvalued and may be primed for a trend reversal or corrective pullback in price. An RSI reading of 30 or below indicates an oversold or undervalued condition.

Strategies

With the previous information we are now able to establish the strategies to follow for buying and selling cryptocurrency. The combination of both indicators reviewed above makes for a couple of conditions that need to happen simultaneously in order for an action to be taken.

To buy: MACD has to be below the signal and RSI below the value of 30.

To sell: MACD has to be above the signal and RSI above the value of 60 for our example.

In order to translate this to our program we create a function that will take the indicators and give back the instruction to buy, sell or wait (do nothing). The result will be given in the form of a data frame that contains the datetime, the comparison between MACD and signal, the RSI value, the decision or suggested action and the price of the currency at that time.

Email about event

A nice feature of the program that was developed is the ability to send and email whenever bitcoin is sold or purchased. The function that takes care of this was created as follows with the help of the R library “emayili”.

Main program

The first thing needed from the program and what makes everything automated is it’s ability to run for an arbitrary amount of time, for example, one can leave the program running all night and go over earnings in the morning. The way this was solved is by inserting the whole code into one big repeat cycle. This solution may not be an elegant one but it worked well and is easy to implement for beginners.

The shortest time between queries that the API allows is one minute, so the cycle was set up to repeat every 60 seconds.

repeat{

Sys.sleep(time = 60)

}

The following will happen every minute:

  1. The code will access the API and generate the most recent data.
  2. MACD and RSI values are computed.
  3. The new line for our log file is created with the last line of the data frame returned by the indication function.
  4. A series of IF cases are established for the instruction, buy, sell or wait.
  5. The cycle ends here and starts again in 60 seconds.

Code chunks

The first few lines are dedicated to sourcing the functions, setting up the API keys and calling said API as well as entering the email that will be sending and receiving the alerts. Note that this works perfectly with Gmail but I can’t confirm if this works with other domains.

Then, the new information is accessed and the indicators are calculated.

IF the indication to buy appears the loop will go into the following section where the purchased is completed and the activity is logged into a separate csv file, nothing happens until the selling indication is given then a difference is calculated and the profit of that one transaction is added to the log.

If the instruction that was received was to either wait or sell (when we haven’t bought anything) the status is stored in the log file called df.

At the end you will have a couple csv files, one general purpose log, named df.csv, that registers the status while there is no buying indication, that looks like the below:

And one file, named results.csv, that registers the buying and selling transactions and the individual gain or loss:

Profit calculation

Outside the repeat cycle a small data frame is created to show the initial investment, the Total or balance at the end of the running time and the amount that represents the final profit.

For example, after running the code for about 10 hours the results were the below:

For this test 90 dollars were earned while sleeping, which is not bad at all.

Final thoughts

The code is actually simplistic and flawed, this was done under some interesting time constraints and with very specific and basic goals in mind that were, in fact, achieved. However, I think that for someone interested in the topic with very basic programming skills this can be a great starting point and really good practice with some R tools.

You can go here for the complete code and resources.

--

--

Brenda Leyva
MCD-UNISON

Former business administration professional turned physicist, turned data scientist with a unique approach to problem solving and data analysis.