fix space
[electrum-nvc.git] / plugins / exchange_rate.py
1 from PyQt4.QtGui import *
2 from PyQt4.QtCore import *
3
4 import decimal
5 import httplib
6 import json
7 import threading
8 import re
9 from decimal import Decimal
10 from electrum.plugins import BasePlugin
11 from electrum.i18n import _
12 from electrum_gui.qt.util import *
13
14
15 class Exchanger(threading.Thread):
16
17     def __init__(self, parent):
18         threading.Thread.__init__(self)
19         self.daemon = True
20         self.parent = parent
21         self.quote_currencies = None
22         self.lock = threading.Lock()
23         self.is_running = False
24
25     def exchange(self, btc_amount, quote_currency):
26         with self.lock:
27             if self.quote_currencies is None:
28                 return None
29             quote_currencies = self.quote_currencies.copy()
30         if quote_currency not in quote_currencies:
31             return None
32         return btc_amount * quote_currencies[quote_currency]
33
34     def stop(self):
35         self.is_running = False
36
37     def run(self):
38         self.is_running = True
39         while self.is_running:
40             self.update()
41             time.sleep(120)
42
43     def update(self):
44         try:
45             connection = httplib.HTTPConnection('blockchain.info')
46             connection.request("GET", "/ticker")
47         except Exception:
48             return
49         response = connection.getresponse()
50         if response.reason == httplib.responses[httplib.NOT_FOUND]:
51             return
52         try:
53             response = json.loads(response.read())
54         except Exception:
55             return
56         quote_currencies = {}
57         try:
58             for r in response:
59                 quote_currencies[r] = self._lookup_rate(response, r)
60             with self.lock:
61                 self.quote_currencies = quote_currencies
62         except KeyError:
63             pass
64         self.parent.set_currencies(quote_currencies)
65         # print "updating exchange rate", self.quote_currencies["USD"]
66
67             
68     def get_currencies(self):
69         return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
70
71     def _lookup_rate(self, response, quote_id):
72         return decimal.Decimal(str(response[str(quote_id)]["15m"]))
73
74
75 class Plugin(BasePlugin):
76
77     def fullname(self):
78         return "Exchange rates"
79
80     def description(self):
81         return """exchange rates, retrieved from blockchain.info"""
82
83
84     def __init__(self,a,b):
85         BasePlugin.__init__(self,a,b)
86         self.currencies = [self.config.get('currency', "EUR")]
87
88     def init(self):
89         self.win = self.gui.main_window
90         self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
91         # Do price discovery
92         self.exchanger = Exchanger(self)
93         self.exchanger.start()
94         self.gui.exchanger = self.exchanger #
95
96     def set_currencies(self, quote_currencies):
97         self.currencies = sorted(quote_currencies.keys())
98         self.win.emit(SIGNAL("refresh_currencies()"))
99         self.win.emit(SIGNAL("refresh_currencies_combo()"))
100
101     def set_quote_text(self, btc_balance, r):
102         r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
103
104     def create_quote_text(self, btc_balance):
105         quote_currency = self.config.get("currency", "EUR")
106         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
107         if quote_balance is None:
108             quote_text = ""
109         else:
110             quote_text = "%.2f %s" % (quote_balance, quote_currency)
111         return quote_text
112
113
114     def requires_settings(self):
115         return True
116
117
118     def toggle(self):
119         out = BasePlugin.toggle(self)
120         self.win.update_status()
121         return out
122
123
124     def close(self):
125         self.exchanger.stop()
126
127
128     def settings_widget(self, window):
129         combo = QComboBox()
130
131         def on_change(x):
132             cur_request = str(self.currencies[x])
133             if cur_request != self.config.get('currency', "EUR"):
134                 self.config.set_key('currency', cur_request, True)
135                 self.win.update_status()
136
137         def set_currencies(combo):
138             try:
139                 combo.clear()
140             except Exception:
141                 return
142             combo.addItems(self.currencies)
143             try:
144                 index = self.currencies.index(self.config.get('currency', "EUR"))
145             except Exception:
146                 index = 0
147             combo.setCurrentIndex(index)
148
149         set_currencies(combo)
150         combo.currentIndexChanged.connect(on_change)
151         combo.connect(window, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
152         return combo
153
154
155