Build A Cryptocurrency Trading Bot with R (2024)

Build A Cryptocurrency Trading Bot with R (3)

** 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.

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.

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.

Build A Cryptocurrency Trading Bot with R (4)

We will begin by calling several libraries:

Build A Cryptocurrency Trading Bot with R (5)

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:

Build A Cryptocurrency Trading Bot with R (6)

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:

Build A Cryptocurrency Trading Bot with R (7)

Function: bid & ask

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

Build A Cryptocurrency Trading Bot with R (8)

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:

Build A Cryptocurrency Trading Bot with R (9)

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.

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:

Build A Cryptocurrency Trading Bot with R (10)

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.

Build A Cryptocurrency Trading Bot with R (11)

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:

Build A Cryptocurrency Trading Bot with R (12)

That’s it, that’s the entire 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:

Build A Cryptocurrency Trading Bot with R (13)

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.

Build A Cryptocurrency Trading Bot with R (14)

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:

Build A Cryptocurrency Trading Bot with R (15)

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

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

Build A Cryptocurrency Trading Bot with R (2024)

FAQs

How to create your own crypto trading bot? ›

How to Build a Crypto Trading Bot?
  1. #1 Choose the Programming Language. ...
  2. #2 Set up an Account on a Crypto Exchange with an Open API. ...
  3. #3 Select a Trading Model. ...
  4. #4 Build the Bot's Architecture. ...
  5. #5 Develop the Bot. ...
  6. #6 Backtest the Bot. ...
  7. #7 Deploy the Bot on a Live Account.
Mar 15, 2024

Can a crypto trading bot really generate money? ›

Crypto trading bots are profitable. However, it's not as simple as it sounds. You need a deeper understanding of how these tools work. You also need to be equipped with the knowledge to decide whether they are the missing piece in your crypto trading puzzle.

Has anyone made a successful trading bot? ›

It depends on the bot! Some lower-risk crypto trading bots boast a 99% success rate, while others execute higher-risk strategies and have a lower success rate. The main thing most investors need to consider is whether the bot they're looking at can execute their specific investment strategy successfully.

What is the best AI trading bot for beginners? ›

Description: Pionex is a popular AI day trading bot known for its user-friendly interface and free trading services, making it an ideal choice for beginners. It supports a wide range of trading strategies and offers a variety of tools to enhance trading efficiency.

Can I code my own trading bot? ›

With the right strategy, tools, and risk management measures, you can create a trading bot that automates your trades and maximizes your profits. Remember to test your strategy thoroughly, and always practice responsible risk management.

Can you lose money with trading bots? ›

Traders can lose money in bot trading due to technical failures, market risks, programming errors, over-optimization, lack of adaptability, and human oversight. However, with proper risk management, oversight, and testing, traders can mitigate these risks and improve their chances of success in automated trading.

What is the best strategy for crypto trading bot? ›

Bollinger band strategy is the most commonly used technical analysis that offers unique insights into price and volatility. In addition, it determines the overbought and oversold levels and is an indispensable tool for monitoring breakouts. It identifies entry and exit points for a trade.

Are crypto trading bots risky? ›

The risk of loss can be substantial. You may lose all or more than your Virtual Assets balance when trading.

Why do trading bots fail? ›

Factors contributing to bot failures include technical glitches, programming errors, market conditions, over-optimization, lack of human oversight, and regulatory risks.

What is the most successful crypto trading bot? ›

Breaking Down The Best Crypto Trading Bots:
  • Phemex. ...
  • Shrimpy. ...
  • Coinigy. ...
  • 3Commas. ...
  • CryptoHopper. ...
  • TradeSanta. ...
  • Kryll‍ When it comes to building your own trading strategies, Kryll.io leads the market with their outstanding UI. ...
  • Gunbot. Gunbot is a highly customizable trading bot for advanced traders.

What is the average return on a crypto bot? ›

From my experience with several bot providers, you can achieve 20% or more on a day on very rare occasions. However, the long-term average daily return is more like 0.1–0.4% for a reasonably good bot, which can still make several hundred percent profits per year considering compound effects.

Which AI tool is best for crypto trading? ›

What are the best AI crypto trading bots?
  • The best AI crypto trading bots include 3Commas, Cryptohopper, and Kryll, known for their comprehensive features, user-friendly interfaces, and proven performance.
  • These bots leverage artificial intelligence to analyze market trends, execute trades, and manage risk effectively.

Can you make a living off trading bots? ›

Do Trading Bots Help Earning Money? Of course yes. That's why many hedge funds, banking structures, and big financial companies hire machine learning and algorithmic specialists. Those people are responsible for implementing automated trading bots to play in the real markets with big money.

What is the number one trading robot? ›

Forex Fury is considered one of the best forex trading robots in the U.S. Being in the market for over 8 years, Forex Fury has some of the most advanced features and tools available. The key advantages of the Forex Fury robot are the free updates, settings files, and ease of use.

How do you make your own bot? ›

How to make a chatbot from scratch in 8 steps
  1. Step 1: Give your chatbot a purpose. ...
  2. Step 2: Decide where you want it to appear. ...
  3. Step 3: Choose the chatbot platform. ...
  4. Step 4: Design the chatbot conversation in a chatbot editor. ...
  5. Step 5: Test your chatbot. ...
  6. Step 6: Train your chatbots. ...
  7. Step 7: Collect feedback from users.
Jun 25, 2024

Are crypto trading bots free? ›

Pionex is one of the world's 1st exchanges with 12 Free trading bots. Users can automate their trading 24/7 without always checking the markets. It aggregates the liquidity from Binance and Huobi Global and is one of the biggest Binance brokers.. Pionex provides 16 free trading bots for retail investors.

How to build a trading bot without coding? ›

Write your bot using if-then statements Our programming language is plain english. Connect your bot Get notified whenever your bot makes a trade, or have your bot text you for permission before submitting a trade. Track your bot's performance Compare it to the ticker being traded.

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5555

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.