- Advertisement -Newspaper WordPress Theme
Algorithm tradingLive Algo Trading on the Cloud - Google Cloud Platform - AlgoTrading101...

Live Algo Trading on the Cloud – Google Cloud Platform – AlgoTrading101 Blog


How to get started with Google Cloud?

To get started with Google Cloud, you will need to open an account to access cloud resources. To do this, go over to their main cloud webpage and click the blue “Get started for free” button in the middle part of your screen.

This will open up a new page where you will be asked from which country you’re from and for what use cases will you use Google Cloud. After answering these questions and agreeing to their terms, click the blue “Continue” button.

The second step will ask you to provide your payment information so that Google can confirm that you aren’t a robot. They won’t charge you anything as we are setting up a free account and getting free $300 worth of credits that last 90 days.

After that, we can choose to upgrade our account to the premium tier after which we start to get charged. When you are done adding in your payment data, click the blue “START MY FREE TRIAL” button to proceed to the Google Cloud Platform.

In the following headers, we will explore how to deploy a live Kraken exchange trading algorithm to Google Cloud. The way that we’ll do this involves the use of Docker and Cloud Run.

For a similar Docker way of doing this, visit our Microsoft Azure article, and for a more manual way, we have the AWS article.

All three ways can be used on all three platforms as all of them have the same services with different, and sometimes similar, names.

Kraken Bot Trading Algorithm

The simple trading strategy that we will use will feature the Kraken exchange, Docker and Cloud Run. Before we set up everything, 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. 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 we need
import time, logging, os
import pandas as pd
import krakenex
from pykrakenapi import KrakenAPI
from dotenv import load_dotenv

# Grab environment variables
load_dotenv()
API_KEY = os.getenv("KRAKEN_API_KEY")
API_SECRET = os.getenv("KRAKEN_API_SECRET")
TRACK_TICKER = os.getenv("TRACK_TICKER")
TRADE_TICKER = os.getenv("TRADE_TICKER")

api = krakenex.API(key=API_KEY, secret=API_SECRET)
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"
)
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 executed sucessfully")
            break
        else:
            logging.info("Order rejected")
            break
    else:
        logging.info("--------- End of current 5 minute period ---------")

As we need to provide our API keys for the trading algorithm to work, we will need to find one of the “safer” solutions to perform that.

How to package a trading algorithm with Docker?

To package a trading algorithm with Docker, we will need to have a file named dockerfile that has all the instructions on how to make our algorithm ready by copying code files we need, installing libraries, passing the environment variables, and more.

Because Docker needs to know what dependencies we want to install for our algorithm, it is good practice to have a requirements.txt file that lists all the libraries we need and their versions:

python-dotenv==0.21.0
pandas==1.4.4
krakenex==2.1.0
pykrakenapi==0.3.1

To get your package version you can write pip show <package>.

Now that the requirements are ready, we can move on to specifying our installation and other setup commands inside of the dockerfile. We first create the dockerfile by writing touch dockerfile.

The inside of our dockerfile looks the following way:

FROM python:3.8
RUN mkdir -p /code

COPY ./main.py /code/
COPY ./requirements.txt /code/

WORKDIR /code

# set environment variablesFROM python:3.8
RUN mkdir -p /code

COPY ./main.py /code/
COPY ./requirements.txt /code/

WORKDIR /code

# set environment variables
ARG API_KEY
ARG API_SECRET
ARG TRACK
ARG TRADE

ENV KRAKEN_API_KEY $API_KEY
ENV KRAKEN_API_SECRET $API_SECRET
ENV TRACK_TICKER $TRACK
ENV TRADE_TICKER $TRADE

RUN pip install -r requirements.txt

EXPOSE 8080

CMD ["python", "/code/main.py"]

To build this container image we run the following command:

docker build -t google-algotrading101 
	--build-arg API_KEY=<YOUR-API-KEY> 
	--build-arg API_SECRET=<YOUR-API-SECRET> 
	--build-arg TRACK=BTCUSDT 
	--build-arg TRADE=ETHUSDT .

Once docker is done, you will see a message similar to this one:

[+] Building 8.2s (11/11) FINISHED
=> [internal] load build definition from Dockerfile ...  

To see your docker images, you can write the following command to the terminal:

REPOSITORY                       TAG               IMAGE ID       CREATED         SIZE
google-algotrading101             latest            f81336abb1fc   2 minutes ago   1.08GB

If you want to run the container locally, you can write the following command:

docker run -d -p 8080:80 google-algotrading101

The next step is to store this image in the Google Artifact Registry. Prior to exploring that, we will need to install the gcloud CLI.

What is Google Artifact Registry?

Google Artifact Registry is the evolution of the previously used Container Registry and is a single place for you to manage container images. It also integrates well with other Google Cloud services such as the Cloud Run service for easy deployment of containers.


How to push a Docker image to Google Artifact Registry?

To store a Docker image on the Google Artifact Registry, navigate to it in your Google Cloud dashboard and enable its usage. Then, click the Create Repository button and set up your repository details. In our case, it is a Docker repository.

When done, click the Create button. The next step is to configure our Docker to work with the Google Artifact Registry. To do this, we will use our previously installed gcloud CLI. Let us open it up and write the following command:

gcloud auth configure-docker 
    northamerica-northeast1-docker.pkg.dev

Take note that your region might be different depending on your choice when creating the Registry. To view your region, you can click the “SETUP INSTRUCTIONS” hyperlink in your Artifact Registry dashboard. This will open an example query you need to run to configure your docker.

Now, we need to tag our docker image with the details from our created Artifact Registry. Have in mind that this will be different for you depending on your registry location and name. I’ll add the “latest” tag to the image.

docker tag google-algotrading101 
northamerica-northeast1-docker.pkg.dev/gifted-healer-362818/kraken-demo/google-algotrading101:latest

To make sure the tag was set, run docker images again. If everything is good, we can push our Docker image to the Registry by writing the following with the gcloud CLI:

docker push krakenexample101.azurecr.io/azure-algotrading101:awesome

When docker is done, you should see the image in your registry:

If you are facing issues, here is a good tutorial by Google on how to push/pull images properly.

Where can I learn more?

To learn more about the Google Cloud Platform, I advise visiting their webpage and exploring various google tutorials, and reading the documentation. There are also great tutorials on YouTube and other blog pages that you might want to explore.

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