- Advertisement -Newspaper WordPress Theme
Algorithm tradingLive Algo Trading on the Cloud - Vultr - AlgoTrading101 Blog

Live Algo Trading on the Cloud – Vultr – AlgoTrading101 Blog


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:

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:

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe Today

GET EXCLUSIVE FULL ACCESS TO PREMIUM CONTENT

SUPPORT NONPROFIT JOURNALISM

EXPERT ANALYSIS OF AND EMERGING TRENDS IN CHILD WELFARE AND JUVENILE JUSTICE

TOPICAL VIDEO WEBINARS

Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

Exclusive content

- Advertisement -Newspaper WordPress Theme

Latest article

More article

- Advertisement -Newspaper WordPress Theme