Live Algo Trading on the Cloud – Vultr

8 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on November 25, 2023

Table of contents:

  1. What does live algorithmic trading on the Cloud mean?
  2. Rerequisite – Basic Guide
  3. What are the pros of deploying your trading strategies to the Cloud?
  4. What are the cons of deploying your trading strategies to the Cloud?
  5. What is the Cloud Service?
  6. What is the Cloud used for? 
  7. What cloud providers are good?
  8. What is Vultr?
  9. Why should I use Vultr?
  10. Why shouldn’t I use Vultr?
  11. What does Vultr offer?
  12. How to get started with Vultr?
  13. Kraken Bot Trading Algorithm
  14. How to set up a Vultr server for trading?
  15. How to connect GitHub with Vultr?
  16. How to run a trading algorithm with Vultr?
  17. Where can I learn more about Vultr?

What does live algorithmic trading on the Cloud mean?

Live algorithmic trading on the Cloud means that your trading bots can use the cloud provider’s resources to run 24/7 while being efficiently maintainable.

This is article, we will demonstrate how to deploy a live algorithmic trading strategy to the cloud server using Vultr and Github.

Prerequisite – Basic Guide

If you are new to deploying strategies to the cloud, do check out our basic guide using AWS.

We covered how to:

  • Choose a location for your server
  • Input your secret keys
  • Deploy a trading script using Github
  • Set Telegram notifications when trades and key events happen

What are the pros of deploying your trading strategies to the Cloud?

  • Cloud services are easily available– they allow the user to access them at any time, from anywhere, and from almost any device.
  • Can lower fees– cloud computing can lower the costs and provide you with a good connection and hardware that saves you money in the long run.
  • Easy to maintain – you can upload your trading strategies to the cloud and get them running 24/7 with minimal effort.
  • Is scalable – you can store almost limitless amounts of data in the cloud.
  • Straightforward to set up – setting up your cloud server is quite easy.

What are the cons of deploying your trading strategies to the Cloud?

  • Security risks – your data is being stored by a third-party provider and if a security breach happens your data is at high risk.
  • Depends on the internet connection – even though this is the same case when executing trading strategies by yourself, the cloud service provider can also suffer from downtime and other natural risks.
  • Data confidentiality risk – your privacy is of utmost importance and when using a third-party cloud provider you can’t be too sure that you’re the only one accessing your data or being able to see it.
  • Can get pricey – sometimes cloud service architecture can get complicated and users can set up suboptimal features which can accrue large bills.

What is the Cloud Service?

A Cloud Service offers cloud computing as a service with the intent to deliver affordable, easy, and efficient access to diverse resources without the need to have your own hardware or infrastructure.

What is Cloud used for?

Cloud services have many purposes for which they could be used and here are some of the most common ones:

  • Algorithmic trading – cloud services allow algorithmic traders to run multiple bots that trade the market.
  • Big data storage – clouds offer an almost limitless storage capacity which is excellent when dealing with big data.
  • Backup and recovery – clouds can be continually backed up and you can easily recover data from them. They also offer good disaster recovery.
  • Test and Development – cloud services are great when testing and developing your applications and trading strategies.
  • Model training – when doing machine learning work, model training can take up to several months, and running it on a cloud can save you computing power and in some cases even money.

What cloud providers are good?

There are many cloud services and picking a quality one is important. In order to make your decisions process easier I will mention a few that are on top of their cloud game:

What is Vultr?

Vultr is a cloud service that offers interesting features to deploy cloud servers, bare metal, and storage worldwide. It is different from other cloud providers as it focuses on quality instead of quantity by using highly performant CPUs and NVMe SSDs.

Why should I use Vultr?

  • Vultr is easy to use and beginner friendly
  • Vultr features the “pay as you go” pricing structure
  • Focuses on performance
  • Offers optimized cloud computing resources with no noisy neighbors.
  • Has a great SDK
  • Features out-of-box solutions
  • Offers low latency which makes it great for traders

Why shouldn’t I use Vultr?

  • Vultr could use more regions (currently has 27)
  • Vultr is expensive when compared to alternatives
  • It can be hard to move to another provider
  • Doesn’t feature a plethora of services like other providers (it focuses on quality and speed)
  • Might be overkill for some non-high-frequency applications

What does Vultr offer?

Vultr offers several different services that make it competitive which are the following:

  • (Optimized) Cloud Compute – VMs for common workloads. The optimized ones are more expensive and feature performant CPUs and SSDs.
  • Bare Metal – automated dedicated servers with zero virtualization
  • Kubernetes – a service to run your containers
  • Load Balancers – enable horizontal scaling
  • Cloud GPUs – Nvidia GPUs
  • Managed Database – the out-of-box database solution
  • Object and Block storage

How to get started with Vultr?

To get started with Vultr, you will need to go to their website and create an account by clicking the blue “Sign up” button in the upper right corner of your screen.

Then, provide your email and create a password. When done, click the blue “Create Account” button. After that, you will be asked to link a payment method from the list of payment methods they offer. You can do an instant deposit to your account or just link it without any deposit.

For the purpose of this guide, we’ll need less than $10 so if you want to min-max it don’t do a deposit.

When done, navigate to the Products tab that is on the left side of your screen. Here, we will configure the server that we want. We want a simple “Cloud Compute” and for the CPU & Storage Technology, we can go with the regular package.

For the server location, it is best to pick one that is close to your exchange servers. If you want to learn how to find this out, visit our AWS article. After that, we will select Ubuntu (22.04 LTS) as our server image. For the server size, we can go with the smallest one.

The rest can be left as is.

Kraken Bot Trading Algorithm

In this article, we will want to deploy a Kraken Bot Trading Algorithm to a Vultr instance. This will be a simple strategy and the deployment process will be very similar to the one we showcased in the AWS article.

Let us explain how this strategy works and where you can learn how to code one.

The main idea behind the strategy will be to buy ETH when BTC moves 5% in the last 5 minutes. For this to work, we will pull BTC prices in 5-minute intervals and calculate the percentage difference.

If this difference is more or equal to 5% we will buy ETH, if the requirement isn’t reached we will continue to loop. The strategy also features error management, logging, and environmental variables.

Error management is used to catch errors that might occur, logging is used so we can obtain data about our bot and what it’s been up to while running on the server and environmental variables allow us to interact with the bot.

The code below is what our trading strategy looks like and here you can find an article about Kraken and how to code a similar strategy by yourself.

# Import the libraries and load the API Keys
import time, logging, os
import pandas as pd
import krakenex
from pykrakenapi import KrakenAPI

# Create environment variables
track_ticker = os.environ.get('ticker_to_track')
trade_ticker = os.environ.get('ticker_to_trade')
api_key = os.environ.get('api_key')
secret_key = os.environ.get('secret_key')
logname = os.environ.get('my_log_name') # Name of the saved log file

api = krakenex.API(key=api_key, secret=secret_key)
kraken = KrakenAPI(api)

# Set up the logging
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)


logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(levelname)s: %(message)s', 
                    filename=logname, filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

# Create the main script logic
while True:
    logging.info('--------- Start of current 5 minute period ---------')
    logging.info(pd.Timestamp.now())
    
    try:
        BTC_old = float((kraken.get_ticker_information(track_ticker))['b'][0][0])
    except Exception as e:
        logging.warning('Error obtaining data')

    time.sleep(300)
    
    try:
        BTC_new = float((kraken.get_ticker_information(track_ticker))['b'][0][0])
    except Exception as e:
        logging.warning('Error obtaining data')
    
    percent = ((BTC_new - BTC_old)*100) / BTC_old
    
    logging.info(f'BTC moved {percent:.2f}% over the last 5 minutes')
    
    if percent >= 5:
        
        try:
            ETH = float((kraken.get_ticker_information(trade_ticker))['a'][0][0]) + 2
        except Exception as e:
            logging.warning('Error obtaining data')
        
        try:
            response = kraken.add_standard_order(pair=trade_ticker, type='buy', ordertype='limit', 
                                                 volume='0.007', price=ETH, validate=False)
        except Exception as e:
            logging.warning('Error placing order')
            
        logging.info(f'Order details:\n{response}')
        
        time.sleep(2)
        
        try:
            check_order = kraken.query_orders_info(response['txid'][0])
        except Exception as e:
            logging.warning('Error checking order')
    
        if check_order['status'][0] == 'open' or 'closed':
            logging.info('Order completed sucessfully')
            break
        else:
            logging.info('Order rejected')
            break
    else:
        logging.info('--------- End of current 5 minute period ---------')

The above strategy is just an example and the code of “real” trading strategies is way more complicated, cleaner, and in more files.

How to set up a Vultr server for trading?

To set up our Vultr server for trading, we will need to make sure that we have Python and Git installed. We first check if they are installed by running python3 --version and git --version.

If they are not installed you will need to run sudo pip install <name>. You will be asked by the terminal emulator to agree to the installation terms. This can be done by pressing “Y” on your keyboard and clicking enter.

The purpose of git is to pull our trading algorithm code from a private GitHub repository. To do this, we will need to make a connection between our server and the GitHub repository.

How to connect GitHub with Vultr?

To connect your Vultr server to GitHub, you will need to utilize the SSH (Secure Shell) method and Git.

This process can be viewed as being consisted of 3 principal steps:

  1. Create your special “keys” (like the API and secret key)
  2. Upload the public key to GitHub
  3. Use the keys when interacting with GitHub

Let’s create the keys. Write the following command in your terminal to create them:

ssh-keygen

Then give it a name and the passphrase can be left blank. I’ll name it “vultr-algotrading”.

Now that your key is created, you can find it by writing the following commands. The first one is ls that will list all the folders that are in your AWS instance.

The “vultr-algotrading” key can be viewed as our secret while the “algotrading.pub” key is the public aka API key. For us to import the key to our GitHub we need to read it first. To read it we write cat.vultr-algotrading.pub.

Copy the contents of the public key as we will need to add that to our GitHub. To do so, go over to your GitHub account -> Setting -> SSH and GPG keys.

When there, click on the green “New SSH key button”. Then give it a name and input the key. Then add the key and input your password when prompted. If you’ve done everything correctly the SSH should be ready.

Now we will instantiate the private key by writing eval "$(ssh-agent)" and then ssh-add vultr-algotrading.

The two code snippets above often need to be typed in your Terminal every time you run the Vultr instance. Now, let us pull our trading strategy from a private repository.

Go over to your repository on GitHub, click on the green “Code” dropdown button, select SSH and copy the URL and write the following in your terminal:

git clone <SSH-URL-HERE>

We have successfully connected our GitHub account to Vultr and obtained the trading algorithm code. The next step is to install our libraries, setup environment variables, and run the algorithm.

How to run a trading algorithm with Vultr?

To run a trading algorithm with Vultr, we will need to make sure that all the libraries are installed, that the environment is set, and that the code is ready.

If you have many dependencies (Libraries) you can utilize the pipreqs library that will export all the libraries your script is using into a .txt file. To install the libraries from such a file you would write sudo pip3 install -r <name>.txt.

As we use only 3 dependencies we can create a txt file (touch requirements.txt) and add the following lines to it:

pandas==1.4.4
krakenex==2.1.0
pykrakenapi==0.3.1

An alternative is to install them 1 by 1. Whichever suits you best.

The next step is to set up the environment variables. To do so, we use the export command and write the values for each of the env variables.

export ticker_to_track='BTCUSD'
export ticker_to_trade='ETHUSD'
export my_log_name='log_kraken'
export api_key=''
export secret_key=''

Finally, to run the script we write python3 main.py. And our script is working. You can confirm this by the logs that are appearing. To keep your script running, we will use the screen command.

First, let’s stop the script by pressing CTRL+C and create a screen by writing screen -S <screen-name>. When inside the screen run the strategy the same way we did before. To detach from a screen press CTRL+A+D.

To attach back to a screen run screen -a <screen-name>. You can create multiple screens and run multiple bots with them. To delete a screen attach to it, stop the script and write exit. If you wish to destroy all screens and their processes run pkill screen.

You can also create a Telegram bot that will notify you about your trading algorithms. You can even create ones that allow you to start/stop, change configuration and query your trading strategies. To learn how to make a notification one, visit our AWS article.

Where can I learn more about Vultr?

To learn more about Vultr, I recommend reading through their documentation which is well written.


Igor Radovanovic