python 比特币价格通知

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 比特币价格通知相关的知识,希望对你有一定的参考价值。

import requests
import time
from datetime import datetime


BITCOIN_API_URL = 'https://api.coinmarketcap.com/v2/ticker/1/?convert=BRL'
IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/<IFTTT_KEY>'
BITCOIN_PRICE_THRESHOLD = 10000


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['data']['quotes']['USD']['price'])


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


def format_bitcoin_history(bitcoin_history):
    rows = []
    for bitcoin_price in bitcoin_history:
        # Formats the date into a string: '15.07.2018 00:11'
        date = bitcoin_price['date'].strftime('%d.%m.%Y %H:%M')
        price = bitcoin_price['price']
        # <b> (bold) tag creates bolded text
        # 15.07.2018 00:11: $<b>6240.93
        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>
    return '<br>'.join(rows)


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 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
        time.sleep(60)


if __name__ == '__main__':
    main()

以上是关于python 比特币价格通知的主要内容,如果未能解决你的问题,请参考以下文章

Python数据分析入门:比特币价格涨幅趋势分布

Python数据分析入门:比特币价格涨幅趋势分布

python获取比特币价格时间序列数组并绘制蜡烛图(candlestick chart)

python获取比特币价格时间序列数组并绘制蜡烛图(candlestick chart)

如何使用 Web 套接字从 GDAX 抓取比特币价格,以便实时更改价值?

比特币价格再超黄金,“比特币ETF”或助燃行情