update for new transactions with exchange plugin
[electrum-nvc.git] / plugins / exchange_rate.py
1 from PyQt4.QtGui import *
2 from PyQt4.QtCore import *
3
4 import datetime
5 import decimal
6 import httplib
7 import json
8 import threading
9 import re
10 from decimal import Decimal
11 from electrum.plugins import BasePlugin
12 from electrum.i18n import _
13 from electrum_gui.qt.util import *
14
15
16 class Exchanger(threading.Thread):
17
18     def __init__(self, parent):
19         threading.Thread.__init__(self)
20         self.daemon = True
21         self.parent = parent
22         self.quote_currencies = None
23         self.lock = threading.Lock()
24         self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
25         self.parent.exchanges = ["Blockchain", "Coinbase", "CoinDesk"]
26         self.parent.currencies = ["EUR","GBP","USD"]
27         self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
28         self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
29         self.is_running = False
30
31     def exchange(self, btc_amount, quote_currency):
32         with self.lock:
33             if self.quote_currencies is None:
34                 return None
35             quote_currencies = self.quote_currencies.copy()
36         if quote_currency not in quote_currencies:
37             return None
38         if self.use_exchange == "CoinDesk":
39             try:
40                 connection = httplib.HTTPSConnection('api.coindesk.com')
41                 connection.request("GET", "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
42             except Exception:
43                 return
44             resp = connection.getresponse()
45             if resp.reason == httplib.responses[httplib.NOT_FOUND]:
46                 return
47             try:
48                 resp_rate = json.loads(resp.read())
49             except Exception:
50                 return
51             return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
52         return btc_amount * decimal.Decimal(quote_currencies[quote_currency])
53
54     def stop(self):
55         self.is_running = False
56
57     def run(self):
58         self.is_running = True
59         while self.is_running:
60             self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
61             if self.use_exchange == "Blockchain":
62                 self.update_bc()
63             elif self.use_exchange == "CoinDesk":
64                 self.update_cd()
65             elif self.use_exchange == "Coinbase":
66                 self.update_cb()
67             time.sleep(150)
68
69
70     def update_cd(self):
71         try:
72             connection = httplib.HTTPSConnection('api.coindesk.com')
73             connection.request("GET", "/v1/bpi/supported-currencies.json")
74         except Exception:
75             return
76         response = connection.getresponse()
77         if response.reason == httplib.responses[httplib.NOT_FOUND]:
78             return
79         try:
80             resp_currencies = json.loads(response.read())
81         except Exception:
82             return
83
84         quote_currencies = {}
85         for cur in resp_currencies:
86             quote_currencies[str(cur["currency"])] = 0.0
87         with self.lock:
88             self.quote_currencies = quote_currencies
89         self.parent.set_currencies(quote_currencies)
90
91     def update_cb(self):
92         try:
93             connection = httplib.HTTPSConnection('coinbase.com')
94             connection.request("GET", "/api/v1/currencies/exchange_rates")
95         except Exception:
96             return
97         response = connection.getresponse()
98         if response.reason == httplib.responses[httplib.NOT_FOUND]:
99             return
100
101         try:
102             response = json.loads(response.read())
103         except Exception:
104             return
105
106         quote_currencies = {}
107         try:
108             for r in response:
109                 if r[:7] == "btc_to_":
110                     quote_currencies[r[7:].upper()] = self._lookup_rate_cb(response, r)
111             with self.lock:
112                 self.quote_currencies = quote_currencies
113         except KeyError:
114             pass
115         self.parent.set_currencies(quote_currencies)
116
117
118     def update_bc(self):
119         try:
120             connection = httplib.HTTPSConnection('blockchain.info')
121             connection.request("GET", "/ticker")
122         except Exception:
123             return
124         response = connection.getresponse()
125         if response.reason == httplib.responses[httplib.NOT_FOUND]:
126             return
127         try:
128             response = json.loads(response.read())
129         except Exception:
130             return
131         quote_currencies = {}
132         try:
133             for r in response:
134                 quote_currencies[r] = self._lookup_rate(response, r)
135             with self.lock:
136                 self.quote_currencies = quote_currencies
137         except KeyError:
138             pass
139         self.parent.set_currencies(quote_currencies)
140         # print "updating exchange rate", self.quote_currencies["USD"]
141
142             
143     def get_currencies(self):
144         return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
145
146     def _lookup_rate(self, response, quote_id):
147         return decimal.Decimal(str(response[str(quote_id)]["15m"]))
148     def _lookup_rate_cb(self, response, quote_id):
149         return decimal.Decimal(str(response[str(quote_id)]))
150
151
152
153 class Plugin(BasePlugin):
154
155     def fullname(self):
156         return "Exchange rates"
157
158     def description(self):
159         return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
160
161
162     def __init__(self,a,b):
163         BasePlugin.__init__(self,a,b)
164         self.currencies = [self.config.get('currency', "EUR")]
165         self.exchanges = [self.config.get('use_exchange', "Blockchain")]
166
167     def init(self):
168         self.win = self.gui.main_window
169         self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
170         # Do price discovery
171         self.exchanger = Exchanger(self)
172         self.exchanger.start()
173         self.gui.exchanger = self.exchanger #
174
175     def set_currencies(self, currency_options):
176         self.currencies = sorted(currency_options)
177         self.win.emit(SIGNAL("refresh_currencies()"))
178         self.win.emit(SIGNAL("refresh_currencies_combo()"))
179
180
181     def set_quote_text(self, btc_balance, r):
182         r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
183
184     def create_quote_text(self, btc_balance):
185         quote_currency = self.config.get("currency", "EUR")
186         self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
187         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
188         if quote_balance is None:
189             quote_text = ""
190         else:
191             quote_text = "%.2f %s" % (quote_balance, quote_currency)
192         return quote_text
193
194     def load_wallet(self, wallet):
195         self.wallet = wallet
196         tx_list = {}
197         for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
198             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
199             tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
200             
201         self.tx_list = tx_list
202         
203
204     def requires_settings(self):
205         return True
206
207
208     def toggle(self):
209         out = BasePlugin.toggle(self)
210         self.win.update_status()
211         return out
212
213
214     def close(self):
215         self.exchanger.stop()
216
217     def history_tab_update(self):
218         if self.config.get('history_rates', 'unchecked') == "checked":
219             tx_list = self.tx_list
220             
221             mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
222             maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
223             try:
224                 connection = httplib.HTTPSConnection('api.coindesk.com')
225                 connection.request("GET", "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
226             except Exception:
227                 return
228             resp = connection.getresponse()
229             if resp.reason == httplib.responses[httplib.NOT_FOUND]:
230                 return
231             try:
232                 resp_hist = json.loads(resp.read())
233             except Exception:
234                 return
235
236             self.gui.main_window.is_edit = True
237             self.gui.main_window.history_list.setColumnCount(6)
238             self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
239             root = self.gui.main_window.history_list.invisibleRootItem()
240             childcount = root.childCount()
241             for i in range(childcount):
242                 item = root.child(i)
243                 try:
244                     tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
245                 except Exception:
246                     newtx = self.wallet.get_tx_history()
247                     v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
248                    
249                     tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
250                     pass
251                 tx_time = int(tx_info['timestamp'])
252                 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
253                 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
254
255
256                 item.setText(5, tx_USD_val)
257             
258             for i, width in enumerate(self.gui.main_window.column_widths['history']):
259                 self.gui.main_window.history_list.setColumnWidth(i, width)
260             self.gui.main_window.history_list.setColumnWidth(4, 140)
261             self.gui.main_window.history_list.setColumnWidth(5, 120)
262             self.gui.main_window.is_edit = False
263        
264
265     def settings_widget(self, window):
266         return EnterButton(_('Settings'), self.settings_dialog)
267
268     def settings_dialog(self):
269         d = QDialog()
270         layout = QGridLayout(d)
271         layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
272         layout.addWidget(QLabel(_('Currency: ')), 1, 0)
273         layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
274         combo = QComboBox()
275         combo_ex = QComboBox()
276         hist_checkbox = QCheckBox()
277         hist_checkbox.setEnabled(False)
278         if self.config.get('history_rates', 'unchecked') == 'unchecked':
279             hist_checkbox.setChecked(False)
280         else:
281             hist_checkbox.setChecked(True)
282         ok_button = QPushButton(_("OK"))
283
284         def on_change(x):
285             cur_request = str(self.currencies[x])
286             if cur_request != self.config.get('currency', "EUR"):
287                 self.config.set_key('currency', cur_request, True)
288                 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
289                     hist_checkbox.setEnabled(True)
290                 else:
291                     hist_checkbox.setChecked(False)
292                     hist_checkbox.setEnabled(False)
293                 self.win.update_status()
294
295         def on_change_ex(x):
296             cur_request = str(self.exchanges[x])
297             if cur_request != self.config.get('use_exchange', "Blockchain"):
298                 self.config.set_key('use_exchange', cur_request, True)
299                 if cur_request == "Blockchain":
300                     self.exchanger.update_bc()
301                     hist_checkbox.setChecked(False)
302                     hist_checkbox.setEnabled(False)
303                 elif cur_request == "CoinDesk":
304                     self.exchanger.update_cd()
305                     if self.config.get('currency', "EUR") == "USD":
306                         hist_checkbox.setEnabled(True)
307                     else:
308                         hist_checkbox.setChecked(False)
309                         hist_checkbox.setEnabled(False)
310                 elif cur_request == "Coinbase":
311                     self.exchanger.update_cb()
312                     hist_checkbox.setChecked(False)
313                     hist_checkbox.setEnabled(False)
314                 set_currencies(combo)
315                 self.win.update_status()
316
317         def on_change_hist(checked):
318             if checked:
319                 self.config.set_key('history_rates', 'checked')
320                 self.history_tab_update()
321             else:
322                 self.config.set_key('history_rates', 'unchecked')
323                 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
324                 self.gui.main_window.history_list.setColumnCount(5)
325                 for i,width in enumerate(self.gui.main_window.column_widths['history']):
326                     self.gui.main_window.history_list.setColumnWidth(i, width)
327
328         def set_hist_check(hist_checkbox):
329             if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
330                 hist_checkbox.setEnabled(True)
331             else:
332                 hist_checkbox.setEnabled(False) 
333         
334         def set_currencies(combo):
335             current_currency = self.config.get('currency', "EUR")
336             try:
337                 combo.clear()
338             except Exception:
339                 return
340             combo.addItems(self.currencies)
341             try:
342                 index = self.currencies.index(current_currency)
343             except Exception:
344                 index = 0
345             combo.setCurrentIndex(index)
346
347         def set_exchanges(combo_ex):
348             try:
349                 combo_ex.clear()
350             except Exception:
351                 return
352             combo_ex.addItems(self.exchanges)
353             try:
354                 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
355             except Exception:
356                 index = 0
357             combo_ex.setCurrentIndex(index)
358
359         def ok_clicked():
360             d.accept();
361
362         set_exchanges(combo_ex)
363         set_currencies(combo)
364         set_hist_check(hist_checkbox)
365         combo.currentIndexChanged.connect(on_change)
366         combo_ex.currentIndexChanged.connect(on_change_ex)
367         hist_checkbox.stateChanged.connect(on_change_hist)
368         combo.connect(d, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
369         combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
370         ok_button.clicked.connect(lambda: ok_clicked())
371         layout.addWidget(combo,1,1)
372         layout.addWidget(combo_ex,0,1)
373         layout.addWidget(hist_checkbox,2,1)
374         layout.addWidget(ok_button,3,1)
375         
376         if d.exec_():
377             return True
378         else:
379             return False
380
381
382