Add new exchange rate options
[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 EXCHANGES = ["BitcoinAverage",
17              "BitPay",
18              "Blockchain",
19              "BTCChina",
20              "CaVirtEx",
21              "Coinbase",
22              "CoinDesk",
23              "LocalBitcoins",
24              "Winkdex"]
25              
26
27 class Exchanger(threading.Thread):
28
29     def __init__(self, parent):
30         threading.Thread.__init__(self)
31         self.daemon = True
32         self.parent = parent
33         self.quote_currencies = None
34         self.lock = threading.Lock()
35         self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
36         self.parent.exchanges = EXCHANGES
37         self.parent.currencies = ["EUR","GBP","USD"]
38         self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
39         self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
40         self.is_running = False
41
42     def get_json(self, site, get_string):
43         try:
44             connection = httplib.HTTPSConnection(site)
45             connection.request("GET", get_string)
46         except Exception:
47             raise
48         resp = connection.getresponse()
49         if resp.reason == httplib.responses[httplib.NOT_FOUND]:
50             raise
51         try:
52             json_resp = json.loads(resp.read())
53         except Exception:
54             raise
55         return json_resp
56
57
58     def exchange(self, btc_amount, quote_currency):
59         with self.lock:
60             if self.quote_currencies is None:
61                 return None
62             quote_currencies = self.quote_currencies.copy()
63         if quote_currency not in quote_currencies:
64             return None
65         if self.use_exchange == "CoinDesk":
66             try:
67                 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
68             except Exception:
69                 return
70             return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
71         return btc_amount * decimal.Decimal(quote_currencies[quote_currency])
72
73     def stop(self):
74         self.is_running = False
75
76     def update_rate(self):
77         self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
78         update_rates = {
79             "BitcoinAverage": self.update_ba,
80             "BitPay": self.update_bp,
81             "Blockchain": self.update_bc,
82             "BTCChina": self.update_CNY,
83             "CaVirtEx": self.update_cv,
84             "CoinDesk": self.update_cd,
85             "Coinbase": self.update_cb,
86             "LocalBitcoins": self.update_lb,
87             "Winkdex": self.update_wd,
88         }
89         try:
90             update_rates[self.use_exchange]()
91         except KeyError:
92             return
93
94     def run(self):
95         self.is_running = True
96         while self.is_running:
97             self.update_rate()
98             time.sleep(150)
99
100
101     def update_cd(self):
102         try:
103             resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
104         except Exception:
105             return
106
107         quote_currencies = {}
108         for cur in resp_currencies:
109             quote_currencies[str(cur["currency"])] = 0.0
110         with self.lock:
111             self.quote_currencies = quote_currencies
112         self.parent.set_currencies(quote_currencies)
113     
114     def update_wd(self):
115         try:
116             winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
117             ####could need nonce value in GET, no Docs available
118         except Exception:
119             return
120         quote_currencies = {"USD": 0.0}
121         ####get y of highest x in "prices"
122         lenprices = len(winkresp["prices"])
123         usdprice = winkresp["prices"][lenprices-1]["y"]
124         try:
125             quote_currencies["USD"] = decimal.Decimal(usdprice)
126             with self.lock:
127                 self.quote_currencies = quote_currencies
128         except KeyError:
129             pass
130         self.parent.set_currencies(quote_currencies)
131             
132     def update_cv(self):
133         try:
134             jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
135         except Exception:
136             return
137         quote_currencies = {"CAD": 0.0}
138         cadprice = jsonresp["last"]
139         try:
140             quote_currencies["CAD"] = decimal.Decimal(cadprice)
141             with self.lock:
142                 self.quote_currencies = quote_currencies
143         except KeyError:
144             pass
145         self.parent.set_currencies(quote_currencies)
146
147     def update_CNY(self):
148         try:
149             jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
150         except Exception:
151             return
152         quote_currencies = {"CNY": 0.0}
153         cnyprice = jsonresp["ticker"]["last"]
154         try:
155             quote_currencies["CNY"] = decimal.Decimal(cnyprice)
156             with self.lock:
157                 self.quote_currencies = quote_currencies
158         except KeyError:
159             pass
160         self.parent.set_currencies(quote_currencies)
161
162     def update_bp(self):
163         try:
164             jsonresp = self.get_json('bitpay.com', "/api/rates")
165         except Exception:
166             return
167         quote_currencies = {}
168         try:
169             for r in jsonresp:
170                 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
171             with self.lock:
172                 self.quote_currencies = quote_currencies
173         except KeyError:
174             pass
175         self.parent.set_currencies(quote_currencies)
176
177     def update_cb(self):
178         try:
179             jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
180         except Exception:
181             return
182
183         quote_currencies = {}
184         try:
185             for r in jsonresp:
186                 if r[:7] == "btc_to_":
187                     quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
188             with self.lock:
189                 self.quote_currencies = quote_currencies
190         except KeyError:
191             pass
192         self.parent.set_currencies(quote_currencies)
193
194
195     def update_bc(self):
196         try:
197             jsonresp = self.get_json('blockchain.info', "/ticker")
198         except Exception:
199             return
200         quote_currencies = {}
201         try:
202             for r in jsonresp:
203                 quote_currencies[r] = self._lookup_rate(jsonresp, r)
204             with self.lock:
205                 self.quote_currencies = quote_currencies
206         except KeyError:
207             pass
208         self.parent.set_currencies(quote_currencies)
209         # print "updating exchange rate", self.quote_currencies["USD"]
210
211     def update_lb(self):
212         try:
213             jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
214         except Exception:
215             return
216         quote_currencies = {}
217         try:
218             for r in jsonresp:
219                 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
220             with self.lock:
221                 self.quote_currencies = quote_currencies
222         except KeyError:
223             pass
224         self.parent.set_currencies(quote_currencies)
225                 
226
227     def update_ba(self):
228         try:
229             jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
230         except Exception:
231             return
232         quote_currencies = {}
233         try:
234             for r in jsonresp:
235                 if not r == "timestamp":
236                     quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
237             with self.lock:
238                 self.quote_currencies = quote_currencies
239         except KeyError:
240             pass
241         self.parent.set_currencies(quote_currencies)
242
243
244     def get_currencies(self):
245         return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
246
247     def _lookup_rate(self, response, quote_id):
248         return decimal.Decimal(str(response[str(quote_id)]["15m"]))
249     def _lookup_rate_cb(self, response, quote_id):
250         return decimal.Decimal(str(response[str(quote_id)]))
251     def _lookup_rate_ba(self, response, quote_id):
252         return decimal.Decimal(response[str(quote_id)]["last"])
253     def _lookup_rate_lb(self, response, quote_id):
254         return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
255
256
257 class Plugin(BasePlugin):
258
259     def fullname(self):
260         return "Exchange rates"
261
262     def description(self):
263         return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
264
265
266     def __init__(self,a,b):
267         BasePlugin.__init__(self,a,b)
268         self.currencies = [self.config.get('currency', "EUR")]
269         self.exchanges = [self.config.get('use_exchange', "Blockchain")]
270
271     def init(self):
272         self.win = self.gui.main_window
273         self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
274         # Do price discovery
275         self.exchanger = Exchanger(self)
276         self.exchanger.start()
277         self.gui.exchanger = self.exchanger #
278
279     def set_currencies(self, currency_options):
280         self.currencies = sorted(currency_options)
281         self.win.emit(SIGNAL("refresh_currencies()"))
282         self.win.emit(SIGNAL("refresh_currencies_combo()"))
283
284
285     def set_quote_text(self, btc_balance, r):
286         r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
287
288     def create_quote_text(self, btc_balance):
289         quote_currency = self.config.get("currency", "EUR")
290         self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
291         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
292         if quote_balance is None:
293             quote_text = ""
294         else:
295             quote_text = "%.2f %s" % (quote_balance, quote_currency)
296         return quote_text
297
298     def load_wallet(self, wallet):
299         self.wallet = wallet
300         tx_list = {}
301         for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
302             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
303             tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
304             
305         self.tx_list = tx_list
306         
307
308     def requires_settings(self):
309         return True
310
311
312     def toggle(self):
313         out = BasePlugin.toggle(self)
314         self.win.update_status()
315         return out
316
317
318     def close(self):
319         self.exchanger.stop()
320
321     def history_tab_update(self):
322         if self.config.get('history_rates', 'unchecked') == "checked":
323             tx_list = self.tx_list
324             
325             mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
326             maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
327             try:
328                 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
329             except Exception:
330                 return
331
332             self.gui.main_window.is_edit = True
333             self.gui.main_window.history_list.setColumnCount(6)
334             self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
335             root = self.gui.main_window.history_list.invisibleRootItem()
336             childcount = root.childCount()
337             for i in range(childcount):
338                 item = root.child(i)
339                 try:
340                     tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
341                 except Exception:
342                     newtx = self.wallet.get_tx_history()
343                     v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
344                    
345                     tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
346                     pass
347                 tx_time = int(tx_info['timestamp'])
348                 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
349                 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
350
351                 item.setText(5, tx_USD_val)
352                 if Decimal(tx_info['value']) < 0:
353                     item.setForeground(5, QBrush(QColor("#BC1E1E")))
354
355             for i, width in enumerate(self.gui.main_window.column_widths['history']):
356                 self.gui.main_window.history_list.setColumnWidth(i, width)
357             self.gui.main_window.history_list.setColumnWidth(4, 140)
358             self.gui.main_window.history_list.setColumnWidth(5, 120)
359             self.gui.main_window.is_edit = False
360        
361
362     def settings_widget(self, window):
363         return EnterButton(_('Settings'), self.settings_dialog)
364
365     def settings_dialog(self):
366         d = QDialog()
367         layout = QGridLayout(d)
368         layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
369         layout.addWidget(QLabel(_('Currency: ')), 1, 0)
370         layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
371         combo = QComboBox()
372         combo_ex = QComboBox()
373         hist_checkbox = QCheckBox()
374         hist_checkbox.setEnabled(False)
375         if self.config.get('history_rates', 'unchecked') == 'unchecked':
376             hist_checkbox.setChecked(False)
377         else:
378             hist_checkbox.setChecked(True)
379         ok_button = QPushButton(_("OK"))
380
381         def on_change(x):
382             cur_request = str(self.currencies[x])
383             if cur_request != self.config.get('currency', "EUR"):
384                 self.config.set_key('currency', cur_request, True)
385                 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
386                     hist_checkbox.setEnabled(True)
387                 else:
388                     hist_checkbox.setChecked(False)
389                     hist_checkbox.setEnabled(False)
390                 self.win.update_status()
391
392         def disable_check():
393             hist_checkbox.setChecked(False)
394             hist_checkbox.setEnabled(False)
395
396         def on_change_ex(x):
397             cur_request = str(self.exchanges[x])
398             if cur_request != self.config.get('use_exchange', "Blockchain"):
399                 self.config.set_key('use_exchange', cur_request, True)
400                 self.exchanger.update_rate()
401                 if cur_request == "CoinDesk":
402                     if self.config.get('currency', "EUR") == "USD":
403                         hist_checkbox.setEnabled(True)
404                     else:
405                         disable_check()
406                 else:
407                     disable_check()
408                 set_currencies(combo)
409                 self.win.update_status()
410
411         def on_change_hist(checked):
412             if checked:
413                 self.config.set_key('history_rates', 'checked')
414                 self.history_tab_update()
415             else:
416                 self.config.set_key('history_rates', 'unchecked')
417                 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
418                 self.gui.main_window.history_list.setColumnCount(5)
419                 for i,width in enumerate(self.gui.main_window.column_widths['history']):
420                     self.gui.main_window.history_list.setColumnWidth(i, width)
421
422         def set_hist_check(hist_checkbox):
423             if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
424                 hist_checkbox.setEnabled(True)
425             else:
426                 hist_checkbox.setEnabled(False) 
427         
428         def set_currencies(combo):
429             current_currency = self.config.get('currency', "EUR")
430             try:
431                 combo.clear()
432             except Exception:
433                 return
434             combo.addItems(self.currencies)
435             try:
436                 index = self.currencies.index(current_currency)
437             except Exception:
438                 index = 0
439             combo.setCurrentIndex(index)
440
441         def set_exchanges(combo_ex):
442             try:
443                 combo_ex.clear()
444             except Exception:
445                 return
446             combo_ex.addItems(self.exchanges)
447             try:
448                 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
449             except Exception:
450                 index = 0
451             combo_ex.setCurrentIndex(index)
452
453         def ok_clicked():
454             d.accept();
455
456         set_exchanges(combo_ex)
457         set_currencies(combo)
458         set_hist_check(hist_checkbox)
459         combo.currentIndexChanged.connect(on_change)
460         combo_ex.currentIndexChanged.connect(on_change_ex)
461         hist_checkbox.stateChanged.connect(on_change_hist)
462         combo.connect(d, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
463         combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
464         ok_button.clicked.connect(lambda: ok_clicked())
465         layout.addWidget(combo,1,1)
466         layout.addWidget(combo_ex,0,1)
467         layout.addWidget(hist_checkbox,2,1)
468         layout.addWidget(ok_button,3,1)
469         
470         if d.exec_():
471             return True
472         else:
473             return False
474
475
476