Close Navigation
Learn more about IBKR accounts
Live Algo Trading on the Cloud – AWS

Live Algo Trading on the Cloud – AWS

Posted September 26, 2022
Igor Radovanovic - via AlgoTrading101 Blog
AlgoTrading101

The article “Live Algo Trading on the Cloud – AWS” first appeared on AlgoTrading101 Blog.

Excerpt

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 easily maintainable.

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

The pros:

  • Cloud services are easily accessible – they allow the user to access them at any time, from anywhere, and from almost any device.
  • Can lower costs – 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.
  • Easy to set up – setting up your cloud server is quite easy.

The cons:

  • 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 running 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.

What is the Cloud Service?

A Cloud Service offers cloud computing as a service with an intent to provide affordable, easy and efficient access to various 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 for 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 great when dealing with big data.
  • Backup and recovery – clouds can be frequently 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:

  • Amazon Web Services (AWS)
  • Microsoft Azure
  • Google Cloud Platform
  • Server Space
  • IBM Cloud Services
  • Oracle

What are Amazon Web Services (AWS)?

Amazon Web Services are cloud services that offer various features like computing power, database storage, content delivery, financial services, machine learning model training, and more.

Why should I use AWS?

  • Easy to use
  • Pay for the amount you use
  • Affordable
  • Trusted
  • Has diverse services
  • Offers unlimited server capacity

Why shouldn’t I use AWS?

  • Resources limited by region
  • Can be confusing for beginners
  • Hard to move to another provider
  • Has a steep learning curve
  • Suffer from the cons of Cloud services

Kraken Bot

In this article, we will want to explore the AWS Lightsail cloud service that offers affordable servers on which we can run our trading strategies. The simple trading strategy that we will use will feature the Kraken exchange.

Before we set up a server and let the bot go crazy with trading, we need to 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 around. 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 how 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
api = krakenex.API()
kraken = KrakenAPI(api)

api.load_key('KrakenPass.txt')

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

# 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 ---------')

Notice: The code is stored in a private GitHub repository.

Visit AlgoTrading101 for instructions on how to sign up for an AWS server: https://algotrading101.com/learn/live-algo-trading-on-the-cloud-aws/.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from AlgoTrading101 and is being posted with its permission. The views expressed in this material are solely those of the author and/or AlgoTrading101 and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.