Build a Bitcoin Price Alert with Google Cloud and Telegram

In this article, I am going to share how to build a Telegram bot for Bitcoin price alerts. The code is written in Python. I use the free tier Google Cloud to run the Python code 24/7 for free. The Python code will read the Bitcoin price from the Binance API, and then it will send a message alert to our Telegram account.

Setup Free Tier Google Cloud

First, we have to create and setup a free tier Google Cloud. You can follow the following tutorial. With this setup, we can use Google Cloud for free even after the trial period is over.

Install Miniconda

First, we have to download and install Miniconda. To download the Miniconda installer, we can use wget commad. If this command is not installed yet, you can install it with the following command:.

sudo apt-get install wget

Download Miniconda installer with the following command:

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh

To install Miniconda, execute the following command:

bash Miniconda3-latest-Linux-x86_64.sh

I installed Miniconda in the following location:

/home/weenslab/miniconda3

After the installation process is finished, we have to restart the Google VM.

Setup Telegram Bot

Talk with the BotFather on Telegram (https://telegram.me/BotFather) and then create a new bot. You will get a token to access the HTTP API of the bot.

Install Telegram library for Python from the Google VM with the following command:

pip install telegram-send

Configure telegram-send with your bot using the token with the following command. Then, you will be asked for the token. After that, you will be asked to add your bot on Telegram and send it the given password. After finising, you are ready to use telegram-send.

telegram-send --configure

To test the connection with your Telegram account, you can execute this command from the Google VM:

telegram-send "Hello, World!"

Send Telegram Message from Python

Now, our Google VM is connected to our Telegram account. Next, we can try to send message from a Python program. This is the Python code:

telegram_test.py
import telegram_send
import asyncio
import datetime
from pytz import timezone

async def main():
        now_utc = datetime.datetime.now(timezone('UTC'))
        now_wib = now_utc.astimezone(timezone('Asia/Jakarta'))
        ct = now_wib.strftime("%d %b %Y, %H:%M")
        await telegram_send.send(messages=["Current time: " + ct])

asyncio.run(main())

Run this Python code with the following command:

python telegram_test.py

Setup CronJob

CronJob creates jobs on a repeating schedule. We can use CronJob to execute our Python code at regular intervals.

To access CronJob setting, use the following command:

crontab -e

Add this setting in order to execute the code every 1 hour.

0 * * * * /home/weenslab/miniconda3/bin/python telegram_test.py # every 1 hour

Details of the CronJob time format can be studied at crontab.guru.

Get Data from REST API

To get data from REST API, we have to install requests library for Python:

pip install requests

Use the following code to test the library with Binance API:

binance_api_test.py
import requests

api_url = "https://api.binance.us/api/v3/ticker/price?symbol=BTCUSDT"
response = requests.get(api_url)
print(response.json().get('symbol') + ': ' + response.json().get('price'))

Bitcoin Price Alert

This code combines all the functionality to get price data from Binance and then send it to the Telegram account.

price_alert.py
import datetime
from pytz import timezone
import requests
import telegram_send
import asyncio

async def main():
        now_utc = datetime.datetime.now(timezone('UTC'))
        now_wib = now_utc.astimezone(timezone('Asia/Jakarta'))
        ct = now_wib.strftime("%d %b %Y, %H:%M")

        coin_list = ['BTCUSDT','ETHUSDT']
        api_url = "https://api.binance.us/api/v3/ticker/price?symbol="
        responses = []
        for c in coin_list:
                #print(api_url + c)
                responses.append(requests.get(api_url + c))

        msg = "My Price Alert\n" + ct + "\n"
        for r in responses:
                msg = msg + r.json().get("symbol") + ": " + str(float(r.json().get("price"))) + "\n"
        #print(msg)

        await telegram_send.send(messages=[msg])

asyncio.run(main())

After that, we can setup the CronJob to automate the Python code execution, for example:

* * * * * /home/weenslab/miniconda3/bin/python price_alert.py # every 1 minute
0 * * * * /home/weenslab/miniconda3/bin/python price_alert.py # every 1 hour
0 */3 * * * /home/weenslab/miniconda3/bin/python price_alert.py # every 3 hour

This figure shows the message in Telegram.

References

Last updated