# 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](https://youtu.be/v46bRHR1Pq0?si=XYxChvYlWk1TtfQQ). 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:.

```sh
sudo apt-get install wget
```

Download Miniconda installer with the following command:

```sh
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&#x20;

Talk with the BotFather on Telegram ([https://telegram.me/BotFather](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:

```sh
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.

```sh
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:

{% code title="telegram_test.py" lineNumbers="true" %}
```python
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())
```
{% endcode %}

Run this Python code with the following command:

```sh
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:

```sh
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](https://crontab.guru/).

## Get Data from REST API

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

```python
pip install requests
```

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

{% code title="binance_api_test.py" lineNumbers="true" %}
```python
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'))
```
{% endcode %}

## Bitcoin Price Alert

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

{% code title="price_alert.py" lineNumbers="true" %}
```python
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())
```
{% endcode %}

{% embed url="https://github.com/weenslab/coding_for_finance/blob/main/telegram_bitcoin_price_alert/price_alert.py" %}

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.

<figure><img src="https://4146991827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIsb2SAYKLkGlVOGOY0EE%2Fuploads%2Fx5IkUqvuKR1KprAi8s5N%2Fprice_alert_crypto_telegram.jpg?alt=media&#x26;token=9eb07bff-3968-43e8-8597-e4ebe75dd56e" alt="" width="360"><figcaption></figcaption></figure>

## References

* Google Cloud Platform (Free Tier) WordPress Setup, [https://www.youtube.com/watch?v=v46bRHR1Pq0](https://www.youtube.com/watch?v=v46bRHR1Pq0)
* Python in the Cloud Part I - How to run Python in the Cloud / Conda environment setup on GCP, [https://www.youtube.com/watch?v=lIJlhKrP\_SI](https://www.youtube.com/watch?v=lIJlhKrP_SI)
* crontab guru, [https://crontab.guru/](https://crontab.guru/)
