Bitcoin Price Notifications
Python Project for Beginners: Bitcoin Price Notifications
Welcome to the first article in a series of articles on Python projects for beginners!
In this tutorial weâre going to build a Bitcoin price notification serviceâ
During this project youâll learn about HTTP requests and how to send them using the (appropriately named) requests
package.
Youâre going to learn about webhooks and how you can use them to connect your Python app to external services, such as phone notifications or Telegram messages.
With relatively little code (~50 lines) youâre going to arrive at a full-fledged Bitcoin price notification service that will be easily extendable to other cryptocurrencies and services.
So letâs jump right in: Remove ads
Bitcoin Price Notifications With Python
As we all know, Bitcoin price is a fickle thing. You never really know where itâs going to be at the end of the day. So, instead of constantly checking various sites for the latest updates, letâs make a Python app to do the work for you.
For this, weâre going to use the popular automation website IFTTT. IFTTT (âif this, then thatâ) is a web service that bridges the gap between different apps and devices.
Weâre going to create two IFTTT applets:
One for emergency notification when Bitcoin price falls under a certain threshold; and
another for regular Telegram updates on the Bitcoin price.
Both will be triggered by our Python app which will consume the data from the Coinmarketcap API.
An IFTTT applet is composed of two parts: a trigger and an action.
In our case, the trigger will be a webhook service provided by IFTTT. You can think of webhooks as âuser-defined HTTP callbacksâ and you can read more about them here.
Our Python app will make an HTTP request to the webhook URL which will trigger an action. Now, this is the fun partâthe action could be almost anything you want. IFTTT offers a multitude of actions like sending an email, updating a Google Spreadsheet and even calling your phone.
Project Setup
Letâs start by setting up a virtual environment. Run this command to get a new Python 3 virtual environment:
Before continuing you have to activate the virtual environment and install the required dependencies:
You can deactivate the virtual environment by running the deactivate
shell command.
Retrieving the Bitcoin Price
Time to get our hands dirty. We can start by getting the latest price from the Coinmarketcap API in the Python console:
First, we have to import the requests
module and define the bitcoin_api_url
variable which contains the Coinmarketcap API URL for Bitcoin.
Next, we send an HTTP GET request to the URL using the requests.get()
function and save the response. Since the API returns a JSON response, we can convert it to a Python object by calling the .json()
function on the response. As you can see, the API returned a list with one element containing the Bitcoin price data:>>>
The property that weâre most interested in is 'price_usd'
âthe Bitcoin price in US dollars. Remove ads
Sending a Test IFTTT Notification
Now we can move onto the IFTTT side of things. To use IFTTT youâll first need to set up a new account and install their mobile app (if you want to receive phone notifications from your Python app). Once you set that up, weâre going to create a new IFTTT applet for testing purposes.
To create a new test applet follow these steps:
Click on the big âthisâ button
Search for the âwebhooksâ service and select the âReceive a web requestâ trigger
Letâs name the event
test_event
Now select the big âthatâ button
Search for the ânotificationsâ service and select the âSend a notification from the IFTTT appâ
Change the message to
I just triggered my first IFTTT action!
and click on âCreate actionâClick on the âFinishâ button and weâre done
To see the documentation on how to use the IFTTT webhooks go to this page and click on the âDocumentationâ button in the top right corner. The documentation page contains the webhook URL and it looks like this:
Next up, youâll need to substitute the {event}
part with whatever name you gave our event in step 3, when you created the applet. The {your-IFTTT-key}
part is already populated with your IFTTT key.
Now copy the webhook URL and start another Python console. Again we import the requests
module and define the webhook URL variable. Now we just have to send an HTTP POST request to the IFTTT webhook URL using the requests.post()
function:>>>
After running the last line you should see a notification on your phone:
Creating IFTTT Applets
Now weâre finally ready for the main part. Before starting with the code we need to create two new IFTTT applets: one for emergency Bitcoin price notifications and one for regular updates.
Emergency bitcoin price notification applet:
Choose the âwebhooksâ service and select the âReceive a web requestâ trigger
Name the event
bitcoin_price_emergency
For the action select the âNotificationsâ service and select the âSend a rich notification from the IFTTT appâ action
Give it a title, like âBitcoin price emergency!â
Set the message to
Bitcoin price is at ${{Value1}}. Buy or sell now!
(weâll return to the{{Value1}}
part later on)Optionally you could add a Link URL to the Coinmarketcap Bitcoin page:
https://coinmarketcap.com/currencies/bitcoin/
Create the action and finish setting up the applet
Regular price updates applet:
Again choose the âwebhooksâ service and select the âReceive a web requestâ trigger
Name the event
bitcoin_price_update
For the action select the âTelegramâ service and select the âSend messageâ action
Set the message text to:
Latest bitcoin prices:<br>{{Value1}}
Create the action and finish with the applet
Note: When creating this applet you will have to authorize the IFTTT Telegram bot.
Putting It All Together
Now that we have IFTTT out of the way, letâs start coding! Youâll start by creating the standard Python command-line app skeleton shown below. Take this code and save it in a file called bitcoin_notifications.py
:
Next, we have to translate the two previous Python console sessions into two functions that will return the latest Bitcoin price and post to the IFTTT webhook respectively. Add the following functions above the main function:
The get_latest_bitcoin_price
is pretty much the same, except for the part where we have to convert the price from a string to a floating point number. The post_ifttt_webhook
takes in two parameters: event
and value
.
The event
parameter corresponds to whatever event name we gave to our trigger when setting up the IFTTT applet. Also, the IFTTT webhooks allow us to send additional data along with the request as JSON-formatted data.
Thatâs why we need the value
parameter: When setting up our applets we left a {{Value1}}
tag in our message fields. This tag is replaced with the 'value1'
text from the JSON payload. The requests.post()
function allows us to send additional JSON data just by adding the json
keyword.
Now we can move on to the core of our app in the main
function. It will consist of a while True
loop since we want our app to run forever. In the loop we will call the Coinmarketcap API to get the latest Bitcoin price and record the current date and time.
Based on the current price we will decide if we want to send an emergency notification. For our regular Telegram updates we will also append the current price and date to a bitcoin_history
list. Once the list reaches a certain number of items (e.g. 5) we will format the items, send the update to Telegram, and reset the history for future updates.
Wheew! As you can see, thereâs a lot going on in this app. If youâre having trouble following the code weâve got thus far then take a quick break and re-read the above section again slowly. This stuff isnât easy, so take your time and donât worry about getting everything perfect the first time around.
An important thing is to avoid sending out these requests too frequently, for two reasons:
the Coinmarketcap API states that they update the data only once every 5 minutes, so thereâs no point in reloading the latest pricing info more frequently than that
if your app sends too many requests to the Coinmarketcap API your IP might get banned or temporarily suspended.
That is why we need to âgo to sleepâ (stop the execution of the loop) for at least 5 minutes before we get new data. The code below implements all of the required features I stated above:
Weâre almost done! The only thing missing is the format_bitcoin_history
function. It takes the bitcoin_history
as an argument and formats it using some of the basic HTML tags allowed by Telegram, like <br>
, <b>
, <i>
, and so on. Copy this function above the main
function:
This is what the end result should look like on your phone:
To run your price notification app, execute the following in your command-line terminal:
Thatâs it! In little over 50 lines of Python code, youâve created your very own Bitcoin notification service. Congratulations! Below Iâve added the entire code so you can compare and see if youâve missed anything:
Solution: Python Bitcoin Price NotifierShow/Hide Remove ads
Recap and Next Steps
In this article, we created our very own Bitcoin notification service. You learned how to send HTTP GET and POST requests using the requests
package. You saw how easy it was to connect your Python app to external services using IFTTT and webhooks.
Now, where should you go next? With Python and IFTTT the sky is the limit. But here are some suggestions that can get you started:
Like spreadsheets? Use an IFTTT action that will add the Bitcoin prices to a Google Spreadsheet
Improve the
if price < BITCOIN_PRICE_THRESHOLD
condition to get the notification only once per day (otherwise it will get quite annoying if Bitcoin is consistently low)Like Ethereum/Litecoin/Dogecoin better? Change the
get_latest_bitcoin_price
toget_latest_cryptocurrency_price
that will take a cryptocurrency as a parameter and return its priceYou want the price in a different currency? Check the Coinmarketcap API for the
convert
parameter.
Also, this will be an ongoing series with more Python projects you can build to grow your skills. Donât miss out on the next tutorial:
Reference : https://realpython.com/python-bitcoin-ifttt/
Last updated