Let’s Build a Real-Time Bitcoin Price Notification Project using Python

thecoding pie
ITNEXT
Published in
10 min readJan 11, 2021

--

Photo by Dmitry Demidko on Unsplash

Howdy Folks, I know it’s been a while since I posted something… But the truth is I am back with another exciting python project!

This post was initially published in my blog which you can find here — https://thecodingpie.com/

You can get the complete code for this project from my GitHub repo — https://github.com/the-coding-pie/bitcoin_price_tracker

Nowadays, Cryptocurrencies are the hot trending topic, most importantly ‘Bitcoin’. But the problem is that bitcoin’s price is highly volatile and you will never really know where it’s going to be at the end of the day. It’s really hard to keep track of the ever-changing BTC price, isn’t it?

So Instead of constantly checking various websites for the latest price, why don’t we make Python do the work for us ?!

In this project, we are going to build a python script that will keep track of the latest bitcoin price. And it will send you a telegram message every 30 minutes (you can tweak that) with the latest 6 bitcoin prices (again you can tweak that too). You can set a minimum threshold value so that if the BTC price goes below that threshold, then the script will send an immediate alert message showing the price.

Sound’s cool, right?

Requirements

To make this script, you will need the following things:

  • A coinmarketcap.com API key. Because we are going to make use of their API to get the latest bitcoin price.
  • The telegram app, and your account’s chat_id.
  • Then a telegram bot and it’s token key. Without a bot, you will not be able to send programmatic messages. In short, if you want to send price notifications from our python script to your telegram account, then you need a telegram bot.
  • Finally Python3, and a Text editor of your choice.

I know most of you may not have the first three things, that’s why I broke down this tutorial into three parts for making life easier:

  1. Getting Coinmarketcap API Key
  2. Telegram Bot and your Chat ID
  3. Fitting everything together

Without further ado, let’s get started.

1). Getting Coinmarketcap API Key

Coinmarketcap.com no longer provides cryptocurrency data for anonymous users. So we need an API key to use their service. If you don’t have an account on their website, then first do signup or login.

When you do so you will be taken to your account dashboard which will look something like this:

My Dashboard
My Dashboard

As you can see there is a limit in using their API with their Basic Plan. But 333 requests a day is a lot for us! If you want to use their paid plan, then feel free to do so.

Remember we made this account to get the Coinmarketcap API Key. Now you can get that by clicking on that COPY KEY button which will pop up when you hover over that API Key box.

Awesome, now we have our Coinmarketcap API Key. Bookmark this page, because we will need this later.

2). Telegram Bot and your Chat ID

Before continuing this step, please make sure you have the Telegram app installed on your mobile phone/computer and you have an account created.

Now to the logic. As we all know, to send a message, there should be two entities, the sender and the receiver. Here the sender is the bot that we are going to create and the receiver is you or, to be exact, your chat_id.

See that’s why you need your own telegram bot and your chat_id.

In fact, telegram bots are so awesome. You can know more about how awesome telegram bots are from their official docs.

But How do I create a bot?

Just talk to BotFather and follow a few simple steps!

BotFather bot
BotFather bot

BotFather is the one bot to rule them all. You can use it to create new bot accounts and manage your existing bots.

Now let’s make our own bot:

  • First, search for BotFather in the telegram app. You will see the BotFather with a blue verified tick next to it.
  • Click on that bot and type the message/command /newbot and send it. /newbot command is used to create a new bot. See whenever you enter a command to a bot you should always use the forward-slash (/) in front of the command.
  • Now the BotFather will ask you for a name and a username, provide it.
  • Then it will send you a congratulations message which contains the link to your bot and the authorization token for your bot.
  • Now let’s activate your bot. To do that, click on the link to your bot which the BotFather gave you:
My bot’s link. Your’s will look like that but with your bot’s name
My bot’s link. Your’s will look like that but with your bot’s name
  • Click on that link and send a /start command to activate it.

That’s it, you have created your own bot and successfully activated it!

The token you got for your bot is a string that will look something like this — 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw. This token is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot 😱.

Awesome! Now you have your bot and importantly its token key. Save it for later use.

Getting your chat_id

The next step is to obtain your telegram chat_id. You can get that easily through a ready-made bot called ‘IDBot’:

  • Search in the telegram app for ‘IDBot’. Its icon will be something like this:
IDBot’s icon
IDBot’s icon
  • Now click on that bot and type a message exactly like this /getid. This /getid command will get your chat_id.

Awesome again! Now you have your chat_id, save this somewhere because we will need this later.

3). Fitting everything together

Make sure you have Python3.4+ and pip3 installed.

Initial Setups

Before starting, we need to set up a folder, virtual environment, and all that stuff. Why? Because it is a good practice!

  • First, create a folder named bitcoin_tracker anywhere on your computer.
  • Then open it inside visual studio code (I am using vs code as my text editor).
  • Now let’s create a new virtual environment using venv and activate it. To do that:
  • From within your text editor, Open Terminal > New Terminal or you can use the command line (If you are on windows) or bash/zsh terminal (on Linux/Mac).
  • Then make sure you are inside the bitcoin_tracker directory or please cd into it and from there type the following command in the terminal:
python3 -m venv venv

This command will create a virtual environment named venv for us.

  • To activate it, if you are on windows, type the following:
venv\Scripts\activate.bat
  • If you are on Linux/Mac, then type this instead:
source venv/bin/activate

Now you should see something like this:

This prefix means that you have successfully activated the virtual environment
This prefix means that you have successfully activated the virtual environment
  • Finally, create a new file named “tracker.py” directly inside the bitcoin_tracker folder.

Now you should have a file structure similar to this:

current folder structure with venv (your virtual env) folder and tracker.py file

Note: If you are still confused about how to set up a virtual environment, then read this Quick Guide.

We have to make some HTTP requests from this script, so we need a python module named requests, so let’s install it.

Type the following command in the terminal to install the requests module:

pip install requests

That’s it, now it’s time to write the actual script!

Let’s Begin…

Open the tracker.py file and type:

import requests
import time
# global variables
api_key = 'your_coinmarketcap_api_key'
bot_token = 'your_telegram_bot_token'
chat_id = 'your_telegram_account_chat_id_here'
threshold = 30000
time_interval = 5 * 60 # in seconds
  • Here, at the very top, we are importing the needed modules. We need the requests module to make an HTTP request to the Coinmarketcap API and the telegram endpoint.
  • We need the time module to make a delay in our code (using sleep() function).
  • Then we are setting some global variables:
  • api_key = ‘put_your_coinmarketcap_api_key_here_which_we_first_obtained’
  • bot_token = ‘put_your_own_telegram_bot_token’
  • chat_id = ‘put_your_telegram_chat_id’
  • threshold = put the minimum threshold bitcoin price
  • time_interval = in seconds. Here I used 5 minutes. That means, my script will make an API request every 5 minutes and stores the price in a python list. Remember you can only make 333 free requests per day, keep that always in mind.

Now let’s make two functions:

  • one named get_btc_price(), which will fetch the latest cryptocurrency prices, extracts the Bitcoin price from it, and then return it.
  • And another named send_message(chat_id, msg), which accepts the chat_id and msg we want to send. This function will make use of the Telegram HTTPS endpoints to send messages to our telegram account.

Type the following:

def get_btc_price():
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key
}

# make a request to the coinmarketcap api
response = requests.get(url, headers=headers)
response_json = response.json()
# extract the bitcoin price from the json data
btc_price = response_json['data'][0]
return btc_price['quote']['USD']['price']
  • See, ‘https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' is the API endpoint to get the latest cryptocurrency prices.
  • Remember you have to send your api_key. You can supply that in one of the two ways:
  1. Preferred method: Via a custom header named X-CMC_PRO_API_KEY. We are using this method because it is the preferred way.
  2. Convenience method: Via a query string parameter named CMC_PRO_API_KEY
  • In the next lines, we are making the GET request and convert the data into json() format.
  • The data we have at this point contains a lot of information. But we only need the bitcoin price. So that’s what we are doing in the last two lines.

The data the API return may vary in structure from time to time. If the above code doesn’t get you the bitcoin price, then try to find where is bitcoin price in the response_json variable by printing the value in it and changing the last two lines according to that.

Now if we call the above function, it will return the latest bitcoin price!

Awesome, now let’s build the send_message() function:

# fn to send_message through telegram
def send_message(chat_id, msg):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
# send the msg
requests.get(url)
  • See, the url you see above is the endpoint which we have to use to send telegram messages from our bot to our telegram account. Here I used the f-string so that I can concatenate the bot_token, chat_id, and the msg I want to send in one single string.
  • Then we are making the GET request to the url, if we do so, you will get a message from your bot in your app.

The next piece of the puzzle is to use the above functions in the way we want them to work. So let’s make a main() function which will call the above two functions:

# main fn
def main():
price_list = []
# infinite loop
while True:
price = get_btc_price()
price_list.append(price)
# if the price falls below threshold, send an immediate msg
if price < threshold:
send_message(chat_id=chat_id, msg=f'BTC Price Drop Alert: {price}')
# send last 6 btc price
if len(price_list) >= 6:
send_message(chat_id=chat_id, msg=price_list)
# empty the price_list
price_list = []
# fetch the price for every dash minutes
time.sleep(time_interval)
# fancy way to activate the main() function
if __name__ == '__main__':
main()
  • We are running an infinite loop which will run at a 5-minute time_interval.
  • For every time_interval, we will call the get_btc_price() function and store the result in the price_list variable. Once its length becomes >= 6, we call the send_message() function with the last 6 bitcoin prices and then empty the price_list.
  • If the BTC price suddenly falls below the threshold value, then we will send an immediate message with the latest bitcoin price.

That’s it, we have made our python script! If you don’t understand the last 2 “fancy” lines, then it is a small exercise for you. Google that line and find out what I am trying to do there!

Let’s run it…

Now let’s run our script. In the terminal, type:

python tracker.py

If everything is all right, then you will receive a message every 30 minutes!

Try tweaking the time_limit and threshold value to get immediate messages. But always keep the free API limit in your mind! You can deploy this online on any server and get real-time notifications too.

Complete Code

Here is the complete code. Cross-check your code with this if something doesn’t work as intended.

import requests
import time
# global variables
api_key = 'your_coinmarketcap_api_key'
bot_token = 'your_telegram_bot_token'
chat_id = 'your_telegram_account_chat_id_here'
threshold = 30000
time_interval = 5 * 60 # in seconds
def get_btc_price():
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key
}

# make a request to the coinmarketcap api
response = requests.get(url, headers=headers)
response_json = response.json()
# extract the bitcoin price from the json data
btc_price = response_json['data'][0]
return btc_price['quote']['USD']['price']
# fn to send_message through telegram
def send_message(chat_id, msg):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
# send the msg
requests.get(url)
# main fn
def main():
price_list = []
# infinite loop
while True:
price = get_btc_price()
price_list.append(price)
# if the price falls below threshold, send an immediate msg
if price < threshold:
send_message(chat_id=chat_id, msg=f'BTC Price Drop Alert: {price}')
# send last 6 btc price
if len(price_list) >= 6:
send_message(chat_id=chat_id, msg=price_list)
# empty the price_list
price_list = []
# fetch the price for every dash minutes
time.sleep(time_interval)
# fancy way to activate the main() function
if __name__ == '__main__':
main()

Wrapping Up

I hope you enjoyed this tutorial. If you have any doubts, then please comment them below. Thank you 🥰.

--

--

Hey Folks! My name is Aravind. I am a passionate learner from India. I write about what I know to help viewers like you. If you like and enjoy my content, sup..