Author: xiaoyu

Python Data Science

Python data analyst


Many of my friends asked me if I had any good projects to practice on after learning Python.

In fact, do projects mainly according to the needs. However, for a beginner, many complex projects cannot be completed independently, so the blogger chose a project that is very suitable for beginners. The content is not very complicated, but very interesting. I believe it is the best project for beginners.

In this project, we will establish a reminder service of bitcoin price.

  • You’ll mainly learn about HTTP requests and how to use the Requests package to send them.

  • You will also learn about Webhooks and how to use them to connect Python apps to external devices such as mobile phone alerts or Telegram services.

It takes less than 50 lines of code to complete a Bitcoin price alert service and can easily be extended to other cryptocurrencies and services.

Let’s take a look at that in a second.

Implement bitcoin price alerts in Python

As we all know, bitcoin is a fluid thing. You don’t really know where it’s going. So, instead of constantly refreshing to see what’s new, we can make a Python app that does the work for you.

To do this, we’ll use a popular automation site called IFTTT. IFTTT**(” If this, then that”)** is a tool that Bridges the gap between different app devices and Web services.

We will create two IFTTT applets:

  • One is an emergency reminder when the price of bitcoin falls below a certain threshold
  • The other is the regular bitcoin price update

Both programs will be triggered by our Python app, which gets the data from the Coinmakercap API point here.

An IFTTT program consists of two parts: the triggering part and the action part.

In our case, the trigger is a Webhook service provided by IFTTT. You can think of Webhooks as “user-defined HTTP callbacks”. See webhooks for more information

Our Python app will issue an HTTP request to a Webhook URL, and the Webhook URL triggers the action. Now, here’s the fun part. It can be anything you want. IFTTT offers many actions like sending an email, updating a Google spreadsheet, and even giving you a phone call.

Configuration items

If you have PYTHon3 installed, you can simply install another requests package.

$PIP install requests = = 2.18.4# We only need the requests package
Copy the code

Choose an editor, such as Pycharm, to edit the code.

Get the price of Bitcoin

The code is simple and can be done on the console. Import the Requests package and define the bitcoin_API_URL variable, which is the URL of the Coinmarketcap API.

Next, send an HTTP GET request using the requests.get() function and save the response. Since the API returns a JSON response, we can convert it to a Python object via.json().

>>> import requests
>>> bitcoin_api_url = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
>>> response = requests.get(bitcoin_api_url)
>>> response_json = response.json()
>>> type(response_json) # The API returns a list
<class 'list'>
>>> # Bitcoin data is the first element of the list
>>> response_json[0]
{'id': 'bitcoin'.'name': 'Bitcoin'.'symbol': 'BTC'.'rank': '1'.'price_usd': '10226.7'.'price_btc': '1.0'.'24h_volume_usd': '7585280000.0'.'market_cap_usd': '172661078165'.'available_supply': '16883362.0'.'total_supply': '16883362.0'.'max_supply': '21000000.0'.'percent_change_1h': '0.67'.'percent_change_24h': '0.78'.'percent_change_7d': '4.79'.'last_updated': '1519465767'}
Copy the code

Above we are interested in price_USD.

Send an IFTTT alert for the test

Now we can move on to IFTTT. To use IFTTT, we need to create a new account, IFTTT, and then install the mobile app (if you want to be notified on your phone). Once the setup is successful, we will start creating a new IFTTT applet for testing.

To create a new test applet, follow these steps:

  1. Click the big “This” button;
  2. Search for “webhooks” service and select “Receive a Web Request “to trigger;
  3. Rename event totest_event;
  4. Then select the big “That” button;
  5. Search for “Notifications” service and select “Send a notification from the IFTTT app”
  6. Change the short message toI just triggered my first IFTTT action!Then click “Create Action “;
  7. Click the “Finish” button to Finish.

To see how to use IFTTT WebHooks, click on the “Documentation” button. The Documentation page has the URL for WebHooks.

https://maker.ifttt.com/trigger/{event}/with/key/{your-IFTTT-key}
Copy the code

Next, you need to replace {event} with the name you gave yourself in Step 3. {your-ifttt-key} is an existing IFTTT key.

Now you can copy the Webhook URL and start another console. Also import the Requests and send the POST request.

>>> import requests
>>> # Make sure that your key is in the URL
>>> ifttt_webhook_url = 'https://maker.ifttt.com/trigger/test_event/with/key/{your-IFTTT-key}'
>>> requests.post(ifttt_webhook_url)
<Response [200]>
Copy the code

After running, you can see:

Who built IFTTT came up Applets

This was just testing, now we’re getting to the main part. Before we can start coding again, we need to create two new IFTTT applets: one for urgent notifications of bitcoin prices and the other for regular updates.

Bitcoin price emergency notification applet:

  1. Select the “Webhooks” service, and select the trigger for “Receive a Web Request “;
  2. Name an event event asbitcoin_price_emergency;
  3. For the action part of the response, select “Notifications” service, then continue to select the “Send a rich notification from the IFTTT app” action;
  4. Provide a title like “Bitcoin Price Emergency!”
  5. Set the short message toBitcoin price is at ${{Value1}}. Buy or sell now!(We’ll return to that in a moment{{Value1}}Section)
  6. Optionally, you can add a URL link to Coinmarketcap Bitcoin Page:https://coinmarketcap.com/currencies/bitcoin/;
  7. Create the action, and then finish setting up the applet;

Regular price update applet:

  1. Also select “webhooks” service, and select “Receive a Web Request “trigger;
  2. Name an event event asbitcoin_price_update;
  3. For the action part of the response, select the “Telegram” service, then continue to select the “Send Message “action;
  4. Set the SMS message text to:Latest bitcoin prices:<br>{{Value1}};
  5. Create the action, and then finish setting up the applet;

Connect it all together

Now that we have IFTTT, here’s the code. You’ll get started by creating a standard Python command line app skeleton like the one below. Add the code and save as bitcoin_notifications. Py:

import requests
import time
from datetime import datetime

def main():
    pass

if __name__ == '__main__':
    main()
Copy the code

Next, we’ll convert the code from the first two Python Console sections into two functions that return the most recent bitcoin price and post each to IFTTT’s Webhook. Add the following code to the main() function.

BITCOIN_API_URL = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/{}/with/key/{your-IFTTT-key}'

def get_latest_bitcoin_price():
    response = requests.get(BITCOIN_API_URL)
    response_json = response.json()
    # Convert the price to a floating point number
    return float(response_json[0]['price_usd'])


def post_ifttt_webhook(event, value):
    # The payload that will be sent to IFTTT service
    data = {'value1': value}
    # inserts our desired event
    ifttt_event_url = IFTTT_WEBHOOKS_URL.format(event)
    # Sends a HTTP POST request to the webhook URL
    requests.post(ifttt_event_url, json=data)
Copy the code

Other than changing the price from a string to a floating-point number, get_latest_bitcoin_price hasn’t changed much. Psot_ifttt_webhook takes two parameters: event and value.

The event parameter corresponds to the trigger name we named earlier. Also, IFTTT’s Webhooks allow us to send additional data through Requests, in JSON format.

That’s why we need the value argument: when we set up our applet, we have {{Value1}} tags in the message text. This tag is replaced with values1 text in the JSON payload. The requests.post() function allows us to send additional JSON data by setting json keywords.

Now we can move on to our app’s core main function digital code. It includes a while True loop, because we want the app to run forever. In the loop, we call the Coinmarkertcap API to get the most recent bitcoin price and record the date and time at that time.

Based on the current price, we will decide if we want to send an urgent notice. For our regular update we will put the current price and date into a bitcoin_history list. Once the list reaches a certain number (say five), we wrap it up, send the update out, and then reset the history for subsequent updates.

One caveat is to avoid sending messages too often, for two reasons:

  • The Coinmarketcap API states that they only update every 5 minutes, so frequent updates are useless
  • If your app sends too many requests to the Coinmarketcap API, your IP may be banned

So we ended up adding “Go to sleep” sleep, set it for at least 5 minutes to get new data. The following code implements the features we need:

BITCOIN_PRICE_THRESHOLD = 10000  # Set this to whatever you like

def main():
    bitcoin_history = []
    while True:
        price = get_latest_bitcoin_price()
        date = datetime.now()
        bitcoin_history.append({'date': date, 'price': price})

        # Send an emergency notification
        if price < BITCOIN_PRICE_THRESHOLD:
            post_ifttt_webhook('bitcoin_price_emergency', price)

        # Send a Telegram notification
        # Once we have 5 items in our bitcoin_history send an update
        if len(bitcoin_history) == 5:
            post_ifttt_webhook('bitcoin_price_update', 
                               format_bitcoin_history(bitcoin_history))
            # Reset the history
            bitcoin_history = []

        # Sleep for 5 minutes 
        # (For testing purposes you can set it to a lower number)
        time.sleep(5 * 60)
Copy the code

We’re almost there. But a format_bitcoin_history function is missing. It takes bitcoin_history as a parameter and then transforms it using basic HTML tags (like

, , < I >, etc.) that Telegram allows. Copy this function above main().

def format_bitcoin_history(bitcoin_history):
    rows = []
    for bitcoin_price in bitcoin_history:
        # Formats the date into a string: '24.02.2018 15:09'
        date = bitcoin_price['date'].strftime('%d.%m.%Y %H:%M')
        price = bitcoin_price['price']
        # <b> (bold) tag creates bolded text
        # 24.02.2018 15:09: $10123.4 < / b > < b >
        row = '{}: $<b>{}</b>'.format(date, price)
        rows.append(row)

    # Use a <br> (break) tag to create a new line
    # Join the rows delimited by <br> tag: row1<br>row2<br>row3
    return '<br>'.join(rows)
Copy the code

The final result on the phone looks like this:

Then, our function is complete, as soon as the price of Bitcoin is updated, the mobile terminal of the phone will have a prompt. Of course, you can also turn it off in the app if you’re bored.

Reference: https://realpython.com/python-bitcoin-ifttt/

Follow the official wechat account Python Data Science to obtain 120G artificial intelligence learning materials.