summaryrefslogtreecommitdiffstats
path: root/py3status/modules/bitcoin-price.py
blob: 638c2c8495ec98207a00a6cefa4308ce5de1c661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
"""
Module for displaying bitcoin prices using
the API by www.bitcoincharts.com.

Written and contributed by @tasse:
    Andre Doser <doser.andre AT gmail.com>
"""
import json
from time import time


class Py3status:
    # possible markets see http://bitcoincharts.com/markets/list/
    cache_timeout = 900  # load max. every 15 min (according to bitcoincharts)
    color_index = -1  # color output according to which market?
    field = 'close'  # see http://bitcoincharts.com/about/markets-api/
    markets = 'btceEUR, btcdeEUR'  # comma separated
    symbols = True  # convert USD -> $ etc.

    def __init__(self):
        self.last_price = 0
        self.currency_map = {'EUR': '€', 'USD': '$', 'GBP': '£',
                             'YEN': '¥', 'CNY': '¥', 'AUD': '$'}
        self.url = 'http://api.bitcoincharts.com/v1/markets.json'

    def _get_price(self, data, market, field):
        for m in data:
            if m['symbol'] == market:
                return m[field]

    def get_rate(self, i3s_output_list, i3s_config):
        response = {'full_text': '', 'name': 'bitcoin rates',
                    'cached_until': time() + self.cache_timeout}
        try:  # python 3
            import urllib.request as ul
        except:  # python 2
            import urllib2 as ul
        # get the data from the bitcoincharts website
        try:
            data = json.loads(ul.urlopen(self.url).read().decode())
        except Exception:
            response['color'] = i3s_config['color_bad']
            response['full_text'] = 'Bitcoincharts not reachable'
            return response
        # get the rate for each market given
        rates, markets = [], self.markets.split(",")
        color_rate = None
        for i, market in enumerate(markets):
            market = market.strip()
            try:
                rate = self._get_price(data, market, self.field)
                if i == self.color_index:
                    color_rate = rate
            except Exception:
                pass
            out = market[:-3] if rate else market  # market name
            out += ': '
            out += 'N/A' if not rate else '{:.2f}'.format(rate)     # rate
            currency_sym = self.currency_map.get(market[-3:], market[-3:])
            out += currency_sym if self.symbols else market
            rates.append(out)
        # don't color multiple sites if no color_index is given
        if len(rates) == 1 or self.color_index > -1:
            if self.last_price == 0:
                pass
            elif color_rate < self.last_price:
                response['color'] = i3s_config['color_bad']
            elif color_rate > self.last_price:
                response['color'] = i3s_config['color_good']
            self.last_pricee = color_rate
        response['full_text'] = ', '.join(rates)
        return response

if __name__ == '__main__':
    from time import sleep
    x = Py3status()
    while True:
        print(x.get_rate([], {'color_good': 'green',
                              'color_bad': 'red'}))
        sleep(5)