Steps to Deploy your Trading Robot to the Cloud

ยท

7 min read

Steps to Deploy your Trading Robot to the Cloud

I recently helped a newbie Python Developer host his trading robot on the cloud, which made me realize how daunting this process can be for people just starting with the world of programming. It gets even more confusing because of the wide variety of industry terms floating around, like an **AWS EC2 Instance, a DigitalOcean Droplet, AWS Lambda, Azure Server, Alibaba Cloud. **

Oh my god, can't they keep things simple? But I guess they probably do this to differentiate their products from each other from a marketing standpoint. Still, every major cloud provider provides more or less similar services. Anyway, getting back to the point, How do you host a Trading Robot to the Cloud?

I will be using a Virtual Server by DigitalOcean to demonstrate this, which they call a Droplet. If you find this reading worthwhile and would like to follow the steps I have mentioned, do signup for DigitalOcean using our affiliate badge below, which will give you $100 worth free credits, and you can launch your own Virtual Machine for free.

DigitalOcean Referral Badge

We will divide this into a few steps, but before I lay out the steps, I want to tell you that this article is more about how to deploy rather than discussing the specifics of the Trading Bot. I will be using a very simple snippet of code below, which will send me the average price of RELIANCE for the last 5 minutes on Telegram. This is to show you the overall process; you are, of course, free to upload your complex strategies. To achieve this, here are the steps:

  1. Building the Trading Robot.

  2. Building a Telegram Bot.

  3. Creating a DigitalOcean Droplet.

  4. Deploying Our Code.

If you prefer watching rather than reading, we have prepared the below Youtube video for you.

Building The Trading Robot.

Installing the Libraries

pip install jugaad_data
pip install telegram_send

We will be using jugaad_data to fetch live prices from NSE Website and use telegram_send to send messages to our Telegram.

from jugaad_data.nse import NSELive
import telegram_send as ts
import time

def get_prices(stockSymbol):
    '''A function to get live prices using jugaad_data library'''
    n = NSELive()
    q = n.stock_quote(stockSymbol)
    return q['priceInfo']['lastPrice']

def send_telegram_message(message):
    ts.send(messages = [str(message)])

live_prices = []
count = 0

while True: 
    current_price = get_prices('HDFC')
    live_prices.append(current_price)
    count = count + 1
    print(f'{count} Minutes Done')

    if len(live_prices) == 5:
        avg_price = round((sum(live_prices[-5:])/len(live_prices[-5:])),2)
        if count == 5:
            send_telegram_message(f'The Average Price of HDFC For Last 5 Minutes is {avg_price}')
            #print(f'The Average Price of HDFC For Last 5 Minutes is {avg_price}')
            count = 0
            live_prices.clear()

    time.sleep(60)

What's Happening in the Above Code?

  • We create function get_prices to get live prices from NSE and function send_telegram_message to send a message. Note: jugaad_data scrapes the actual NSE website for data and may be illegal; please use it at your own risk. This is just for demonstration purposes only. The while loop runs continuously, fetches a price, and sleeps for 60 seconds. - The current_price is added to a list live_prices, as soon as there are additional 5 entries in that list, we calculate the avg_price and send it to Telegram.

Building A Telegram Bot.

To send messages via Python to our Telegram App, we need to create a Bot; if you are a Telegram user, you might have already seen such bots. Follow these steps to create a Bot.

  • Open Anaconda Prompt and change the directory to where your .py file is; for me, it's in a folder called cloud_bot. If the below is not visible properly, please zoom in.

image.png

  • Talk with BotFather on Telegram and follow the instructions until you get a Unique ID for your Bot.

image.png

  • I have redacted by Unique Bot ID for obvious reasons. Enter this Unique ID back into the anaconda terminal.

image.png

image.png

Great, our Telegram Bot is now ready to use, wasn't that really easy?

Creating a DigitalOcean Droplet

A DigitalOcean Droplet is nothing but a Virtual Machine in the Cloud. There are various advantages to deploy your strategy to Cloud primary one being stability. For example, you have a very risky strategy running on your laptop, and you have many positions open, and suddenly your home Wi-Fi stops working, and your algo stops running. Imagine that nightmare! Better to deploy on the cloud and let DigitalOcean take care of the infrastructure. If you follow me in this article, I would really appreciate it if you could sign up using my affiliate badge below.

DigitalOcean Referral Badge

  • Create an Account On DigitalOcean.

  • Once you are logged in, create a new Droplet.

image.png

  • Select Your Machine Configuration and other Resources. If you plan to deploy your trading robot in India, I recommend selecting the Bangalore Data Centre. DigitalOcean does not offer Windows VMs, and just so you know, Windows VM is generally costlier than Linux VMs due to Windows License Fee. (Talk about Bill Gates being a philanthropist LOL)

image.png

  • Create an Authentication Method, to keep things simple, select Password and enter a complex password.

  • Give Your Droplet a HostName and Create It. Great, now you have your own Virtual Machine at zero cost.

image.png

  • **Let's login into our Virtual Machine to see if we can access it. ** a. Open cmd on your Windows Machine or the Terminal on Linux.
    b. Type in ssh root@your.ipv4.address highlighted in the above image and input the password you entered while creating the droplet.

image.png

Awesome, if you see a screen like above, that means you are now logged into your Ubuntu Virtual Machine. How cool, right? Moreover, this droplet comes pre-installed with Python3. If you got an error in the above step, please let me know in the comments.

Deploying Our Trading Robot

To deploy the robot you created on your personal laptop, you will first have to transfer it to the Droplet and then try and run it. You can do it in various ways, but here is the preferred way.

Transferring the Code to our Droplet

  • Download FileZilla from this link. This will be used to transfer the file. Once downloaded, please install it.

  • Go to File --> Site Manager --> New Site --> Select SFTP Protocol --> Enter Host (this is your Droplet ipv4 address) -->** Logon Type** (Interactive) --> User (root) --> Connect

image.png

  • You will get a popup saying Unknown host key if you connect this for the first time, ignore that and click OK.

image.png

  • Enter the Droplet Password and click OK. If everything goes well, you should be connected to the root folder on your Virtual Machine.

image.png

  • Now, it's just as simple as finding the relevant folder in your local site on the left-hand side of the screen and then dragging it to the remote site.

image.png

Awesome, you now have your files on the Virtual Machine. Now it's just a matter of running them from your Terminal.

Running the Code on Droplet

  • Go back to your Command Prompt cmd, log in again into your Droplet if you haven't already and type in ls into the terminal; you will see your folder cloud_bot present there. Change your directory using cd cloud_bot and then try and run the code python3 cloud_botv2.py (Substitute it with your file name, please)

image.png

  • Woah! We got an error; if you look closely, that was pretty much expected. Our code uses external libraries like jugaad_data and telegram_send, which are not present on this machine, so first, we have to install them again. But, to do that, first, we need to install pip3 into this machine as well.

apt install python3-pip

Followed by: pip3 install jugaad_data telegram_send

image.png

image.png

  • **Configure the Telegram Bot on this Droplet Again and finally run the code. **

Inkedcode_launch_LI.jpg

image.png

Awesome ๐ŸŽ†, so now you have a code running on your Virtual Machine (Droplet) where there is no dependency on your local system at all. This was a very basic example but you can upload complex options trading strategies or just bots where you want to get notified if certain conditions meet. There are tons of possibilities if you imagine.

Conclusion

I hope this is a very detailed step-by-step guide for you to set up your own Droplet and host your trading robot on it. If you are confused at any time, please feel free to comment below or speak to me via TopMate.

**You can also find the code I uploaded to the Droplet here on GitHub. **

If you like the content on Trade With Python, please do consider subscribing to our newsletter (you will find an option at the top of the page), and lastly, if you would like to keep our spirits high and produce more content like this, you can BuyMeACoffee by clicking here or on the button below.

๐Ÿ’ก
Please note we haven't made any new posts since Nov 2021 on this blog, you are free to subscribe to the mailing list, however, you will be auto-added to the new blog's (thealtinvestor.in) mailing list as well.

Did you find this article valuable?

Support Trade With Python by becoming a sponsor. Any amount is appreciated!

ย