Add history fiat tx value for 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.fromtimestamp(int( max(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).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                 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
244                 tx_time = int(tx_info['timestamp'])
245                 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
246                 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
247
248
249                 item.setText(5, tx_USD_val)
250             
251             for i, width in enumerate(self.gui.main_window.column_widths['history']):
252                 self.gui.main_window.history_list.setColumnWidth(i, width)
253             self.gui.main_window.history_list.setColumnWidth(4, 140)
254             self.gui.main_window.history_list.setColumnWidth(5, 120)
255             self.gui.main_window.is_edit = False
256        
257
258     def settings_widget(self, window):
259         return EnterButton(_('Settings'), self.settings_dialog)
260
261     def settings_dialog(self):
262         d = QDialog()
263         layout = QGridLayout(d)
264         layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
265         layout.addWidget(QLabel(_('Currency: ')), 1, 0)
266         layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
267         combo = QComboBox()
268         combo_ex = QComboBox()
269         hist_checkbox = QCheckBox()
270         hist_checkbox.setEnabled(False)
271         if self.config.get('history_rates', 'unchecked') == 'unchecked':
272             hist_checkbox.setChecked(False)
273         else:
274             hist_checkbox.setChecked(True)
275         ok_button = QPushButton(_("OK"))
276
277         def on_change(x):
278             cur_request = str(self.currencies[x])
279             if cur_request != self.config.get('currency', "EUR"):
280                 self.config.set_key('currency', cur_request, True)
281                 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
282                     hist_checkbox.setEnabled(True)
283                 else:
284                     hist_checkbox.setChecked(False)
285                     hist_checkbox.setEnabled(False)
286                 self.win.update_status()
287
288         def on_change_ex(x):
289             cur_request = str(self.exchanges[x])
290             if cur_request != self.config.get('use_exchange', "Blockchain"):
291                 self.config.set_key('use_exchange', cur_request, True)
292                 if cur_request == "Blockchain":
293                     self.exchanger.update_bc()
294                     hist_checkbox.setChecked(False)
295                     hist_checkbox.setEnabled(False)
296                 elif cur_request == "CoinDesk":
297                     self.exchanger.update_cd()
298                     if self.config.get('currency', "EUR") == "USD":
299                         hist_checkbox.setEnabled(True)
300                     else:
301                         hist_checkbox.setChecked(False)
302                         hist_checkbox.setEnabled(False)
303                 elif cur_request == "Coinbase":
304                     self.exchanger.update_cb()
305                     hist_checkbox.setChecked(False)
306                     hist_checkbox.setEnabled(False)
307                 set_currencies(combo)
308                 self.win.update_status()
309
310         def on_change_hist(checked):
311             if checked:
312                 self.config.set_key('history_rates', 'checked')
313                 self.history_tab_update()
314             else:
315                 self.config.set_key('history_rates', 'unchecked')
316                 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
317                 self.gui.main_window.history_list.setColumnCount(5)
318                 for i,width in enumerate(self.gui.main_window.column_widths['history']):
319                     self.gui.main_window.history_list.setColumnWidth(i, width)
320
321         def set_hist_check(hist_checkbox):
322             if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
323                 hist_checkbox.setEnabled(True)
324             else:
325                 hist_checkbox.setEnabled(False) 
326         
327         def set_currencies(combo):
328             current_currency = self.config.get('currency', "EUR")
329             try:
330                 combo.clear()
331             except Exception:
332                 return
333             combo.addItems(self.currencies)
334             try:
335                 index = self.currencies.index(current_currency)
336             except Exception:
337                 index = 0
338             combo.setCurrentIndex(index)
339
340         def set_exchanges(combo_ex):
341             try:
342                 combo_ex.clear()
343             except Exception:
344                 return
345             combo_ex.addItems(self.exchanges)
346             try:
347                 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
348             except Exception:
349                 index = 0
350             combo_ex.setCurrentIndex(index)
351
352         def ok_clicked():
353             d.accept();
354
355         set_exchanges(combo_ex)
356         set_currencies(combo)
357         set_hist_check(hist_checkbox)
358         combo.currentIndexChanged.connect(on_change)
359         combo_ex.currentIndexChanged.connect(on_change_ex)
360         hist_checkbox.stateChanged.connect(on_change_hist)
361         combo.connect(d, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
362         combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
363         ok_button.clicked.connect(lambda: ok_clicked())
364         layout.addWidget(combo,1,1)
365         layout.addWidget(combo_ex,0,1)
366         layout.addWidget(hist_checkbox,2,1)
367         layout.addWidget(ok_button,3,1)
368         
369         if d.exec_():
370             return True
371         else:
372             return False
373
374
375