1 from PyQt4.QtGui import *
2 from PyQt4.QtCore import *
11 from decimal import Decimal
12 from electrum.plugins import BasePlugin
13 from electrum.i18n import _
14 from electrum_gui.qt.util import *
15 from electrum_gui.qt.amountedit import AmountEdit
18 EXCHANGES = ["BitcoinAverage",
30 class Exchanger(threading.Thread):
32 def __init__(self, parent):
33 threading.Thread.__init__(self)
36 self.quote_currencies = None
37 self.lock = threading.Lock()
38 self.query_rates = threading.Event()
39 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
40 self.parent.exchanges = EXCHANGES
41 self.parent.currencies = ["EUR","GBP","USD"]
42 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
43 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
44 self.is_running = False
46 def get_json(self, site, get_string):
48 connection = httplib.HTTPSConnection(site)
49 connection.request("GET", get_string)
52 resp = connection.getresponse()
53 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
56 json_resp = json.loads(resp.read())
62 def exchange(self, btc_amount, quote_currency):
64 if self.quote_currencies is None:
66 quote_currencies = self.quote_currencies.copy()
67 if quote_currency not in quote_currencies:
69 if self.use_exchange == "CoinDesk":
71 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
74 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
75 return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency]))
78 self.is_running = False
80 def update_rate(self):
81 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
83 "BitcoinAverage": self.update_ba,
84 "BitcoinVenezuela": self.update_bv,
85 "BitPay": self.update_bp,
86 "Blockchain": self.update_bc,
87 "BTCChina": self.update_CNY,
88 "CaVirtEx": self.update_cv,
89 "CoinDesk": self.update_cd,
90 "Coinbase": self.update_cb,
91 "LocalBitcoins": self.update_lb,
92 "Winkdex": self.update_wd,
95 update_rates[self.use_exchange]()
100 self.is_running = True
101 while self.is_running:
102 self.query_rates.clear()
104 self.query_rates.wait(150)
109 resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
113 quote_currencies = {}
114 for cur in resp_currencies:
115 quote_currencies[str(cur["currency"])] = 0.0
117 self.quote_currencies = quote_currencies
118 self.parent.set_currencies(quote_currencies)
122 winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
123 ####could need nonce value in GET, no Docs available
126 quote_currencies = {"USD": 0.0}
127 ####get y of highest x in "prices"
128 lenprices = len(winkresp["prices"])
129 usdprice = winkresp["prices"][lenprices-1]["y"]
131 quote_currencies["USD"] = decimal.Decimal(str(usdprice))
133 self.quote_currencies = quote_currencies
136 self.parent.set_currencies(quote_currencies)
140 jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
143 quote_currencies = {"CAD": 0.0}
144 cadprice = jsonresp["last"]
146 quote_currencies["CAD"] = decimal.Decimal(str(cadprice))
148 self.quote_currencies = quote_currencies
151 self.parent.set_currencies(quote_currencies)
153 def update_CNY(self):
155 jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
158 quote_currencies = {"CNY": 0.0}
159 cnyprice = jsonresp["ticker"]["last"]
161 quote_currencies["CNY"] = decimal.Decimal(str(cnyprice))
163 self.quote_currencies = quote_currencies
166 self.parent.set_currencies(quote_currencies)
170 jsonresp = self.get_json('bitpay.com', "/api/rates")
173 quote_currencies = {}
176 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
178 self.quote_currencies = quote_currencies
181 self.parent.set_currencies(quote_currencies)
185 jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
189 quote_currencies = {}
192 if r[:7] == "btc_to_":
193 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
195 self.quote_currencies = quote_currencies
198 self.parent.set_currencies(quote_currencies)
203 jsonresp = self.get_json('blockchain.info', "/ticker")
206 quote_currencies = {}
209 quote_currencies[r] = self._lookup_rate(jsonresp, r)
211 self.quote_currencies = quote_currencies
214 self.parent.set_currencies(quote_currencies)
215 # print "updating exchange rate", self.quote_currencies["USD"]
219 jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
222 quote_currencies = {}
225 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
227 self.quote_currencies = quote_currencies
230 self.parent.set_currencies(quote_currencies)
235 jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
238 quote_currencies = {}
240 for r in jsonresp["BTC"]:
241 quote_currencies[r] = Decimal(jsonresp["BTC"][r])
243 self.quote_currencies = quote_currencies
246 self.parent.set_currencies(quote_currencies)
251 jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
254 quote_currencies = {}
257 if not r == "timestamp":
258 quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
260 self.quote_currencies = quote_currencies
263 self.parent.set_currencies(quote_currencies)
266 def get_currencies(self):
267 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
269 def _lookup_rate(self, response, quote_id):
270 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
271 def _lookup_rate_cb(self, response, quote_id):
272 return decimal.Decimal(str(response[str(quote_id)]))
273 def _lookup_rate_ba(self, response, quote_id):
274 return decimal.Decimal(response[str(quote_id)]["last"])
275 def _lookup_rate_lb(self, response, quote_id):
276 return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
279 class Plugin(BasePlugin):
282 return "Exchange rates"
284 def description(self):
285 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
288 def __init__(self,a,b):
289 BasePlugin.__init__(self,a,b)
290 self.currencies = [self.config.get('currency', "EUR")]
291 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
294 self.win = self.gui.main_window
295 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
296 self.btc_rate = Decimal("0.0")
298 self.exchanger = Exchanger(self)
299 self.exchanger.start()
300 self.gui.exchanger = self.exchanger #
302 def set_currencies(self, currency_options):
303 self.currencies = sorted(currency_options)
304 self.win.emit(SIGNAL("refresh_currencies()"))
305 self.win.emit(SIGNAL("refresh_currencies_combo()"))
307 def get_fiat_balance_text(self, btc_balance, r):
308 # return balance as: 1.23 USD
309 r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / 100000000)
311 def get_fiat_price_text(self, r):
312 # return BTC price as: 123.45 USD
313 r[0] = self.create_fiat_balance_text(1)
318 def get_fiat_status_text(self, btc_balance, r2):
319 # return status as: (1.23 USD) 1 BTC~123.45 USD
322 self.get_fiat_price_text(r)
325 price_text = "1 BTC~%s"%quote
326 fiat_currency = quote[-3:]
327 btc_price = quote[:-4]
328 fiat_balance = Decimal(btc_price) * (Decimal(btc_balance)/100000000)
329 balance_text = "(%.2f %s)" % (fiat_balance,fiat_currency)
330 text = " " + balance_text + " " + price_text + " "
333 def create_fiat_balance_text(self, btc_balance):
334 quote_currency = self.config.get("currency", "EUR")
335 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
336 cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
340 quote_balance = btc_balance * Decimal(cur_rate)
341 self.btc_rate = cur_rate
342 quote_text = "%.2f %s" % (quote_balance, quote_currency)
345 def load_wallet(self, wallet):
348 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
349 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
350 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
352 self.tx_list = tx_list
355 def requires_settings(self):
360 out = BasePlugin.toggle(self)
361 self.win.update_status()
362 if self.config.get('use_exchange_rate'):
366 self.gui.main_window.show_message(_("To see fiat amount when sending bitcoin, please restart Electrum to activate the new GUI settings."))
371 self.exchanger.stop()
373 def history_tab_update(self):
374 if self.config.get('history_rates', 'unchecked') == "checked":
375 cur_exchange = self.config.get('use_exchange', "Blockchain")
377 tx_list = self.tx_list
382 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
385 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
387 if cur_exchange == "CoinDesk":
389 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
392 elif cur_exchange == "Winkdex":
394 resp_hist = self.exchanger.get_json('winkdex.com', "/static/data/0_86400_730.json")['prices']
397 elif cur_exchange == "BitcoinVenezuela":
398 cur_currency = self.config.get('currency', "EUR")
399 if cur_currency == "VEF":
401 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php")['VEF_BTC']
404 elif cur_currency == "ARS":
406 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php")['ARS_BTC']
412 self.gui.main_window.is_edit = True
413 self.gui.main_window.history_list.setColumnCount(6)
414 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
415 root = self.gui.main_window.history_list.invisibleRootItem()
416 childcount = root.childCount()
417 for i in range(childcount):
420 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
422 newtx = self.wallet.get_tx_history()
423 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
425 tx_info = {'timestamp':int(time.time()), 'value': v }
427 tx_time = int(tx_info['timestamp'])
428 if cur_exchange == "CoinDesk":
429 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
431 tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
433 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
434 elif cur_exchange == "Winkdex":
435 tx_time_str = int(tx_time) - (int(tx_time) % (60 * 60 * 24))
437 tx_rate = resp_hist[[x['x'] for x in resp_hist].index(tx_time_str)]['y']
438 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate), "USD")
440 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
441 elif cur_exchange == "BitcoinVenezuela":
442 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
444 num = resp_hist[tx_time_str].replace(',','')
445 tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
447 tx_BTCVEN_val = _("No data")
449 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
450 item.setText(5, tx_USD_val)
451 elif cur_exchange == "BitcoinVenezuela":
452 item.setText(5, tx_BTCVEN_val)
453 if Decimal(str(tx_info['value'])) < 0:
454 item.setForeground(5, QBrush(QColor("#BC1E1E")))
456 for i, width in enumerate(self.gui.main_window.column_widths['history']):
457 self.gui.main_window.history_list.setColumnWidth(i, width)
458 self.gui.main_window.history_list.setColumnWidth(4, 140)
459 self.gui.main_window.history_list.setColumnWidth(5, 120)
460 self.gui.main_window.is_edit = False
463 def settings_widget(self, window):
464 return EnterButton(_('Settings'), self.settings_dialog)
466 def settings_dialog(self):
468 d.setWindowTitle("Settings")
469 layout = QGridLayout(d)
470 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
471 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
472 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
474 combo_ex = QComboBox()
475 hist_checkbox = QCheckBox()
476 hist_checkbox.setEnabled(False)
477 if self.config.get('history_rates', 'unchecked') == 'unchecked':
478 hist_checkbox.setChecked(False)
480 hist_checkbox.setChecked(True)
481 ok_button = QPushButton(_("OK"))
485 cur_request = str(self.currencies[x])
488 if cur_request != self.config.get('currency', "EUR"):
489 self.config.set_key('currency', cur_request, True)
490 cur_exchange = self.config.get('use_exchange', "Blockchain")
491 if cur_request == "USD" and (cur_exchange == "CoinDesk" or cur_exchange == "Winkdex"):
492 hist_checkbox.setEnabled(True)
493 elif cur_request == "VEF" and (cur_exchange == "BitcoinVenezuela"):
494 hist_checkbox.setEnabled(True)
495 elif cur_request == "ARS" and (cur_exchange == "BitcoinVenezuela"):
496 hist_checkbox.setEnabled(True)
498 hist_checkbox.setChecked(False)
499 hist_checkbox.setEnabled(False)
500 self.win.update_status()
506 self.fiat_button.setText(cur_request)
509 hist_checkbox.setChecked(False)
510 hist_checkbox.setEnabled(False)
513 cur_request = str(self.exchanges[x])
514 if cur_request != self.config.get('use_exchange', "Blockchain"):
515 self.config.set_key('use_exchange', cur_request, True)
518 self.exchanger.query_rates.set()
519 cur_currency = self.config.get('currency', "EUR")
520 if cur_request == "CoinDesk" or cur_request == "Winkdex":
521 if cur_currency == "USD":
522 hist_checkbox.setEnabled(True)
525 elif cur_request == "BitcoinVenezuela":
526 if cur_currency == "VEF" or cur_currency == "ARS":
527 hist_checkbox.setEnabled(True)
532 set_currencies(combo)
533 self.win.update_status()
535 def on_change_hist(checked):
537 self.config.set_key('history_rates', 'checked')
538 self.history_tab_update()
540 self.config.set_key('history_rates', 'unchecked')
541 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
542 self.gui.main_window.history_list.setColumnCount(5)
543 for i,width in enumerate(self.gui.main_window.column_widths['history']):
544 self.gui.main_window.history_list.setColumnWidth(i, width)
546 def set_hist_check(hist_checkbox):
547 cur_exchange = self.config.get('use_exchange', "Blockchain")
548 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
549 hist_checkbox.setEnabled(True)
550 elif cur_exchange == "BitcoinVenezuela":
551 hist_checkbox.setEnabled(True)
553 hist_checkbox.setEnabled(False)
555 def set_currencies(combo):
556 current_currency = self.config.get('currency', "EUR")
561 combo.addItems(self.currencies)
563 index = self.currencies.index(current_currency)
566 combo.setCurrentIndex(index)
568 def set_exchanges(combo_ex):
573 combo_ex.addItems(self.exchanges)
575 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
578 combo_ex.setCurrentIndex(index)
583 set_exchanges(combo_ex)
584 set_currencies(combo)
585 set_hist_check(hist_checkbox)
586 combo.currentIndexChanged.connect(on_change)
587 combo_ex.currentIndexChanged.connect(on_change_ex)
588 hist_checkbox.stateChanged.connect(on_change_hist)
589 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
590 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
591 ok_button.clicked.connect(lambda: ok_clicked())
592 layout.addWidget(combo,1,1)
593 layout.addWidget(combo_ex,0,1)
594 layout.addWidget(hist_checkbox,2,1)
595 layout.addWidget(ok_button,3,1)
603 quote_currency = self.config.get("currency", "???")
604 return quote_currency
606 def fiat_dialog(self):
607 if not self.config.get('use_exchange_rate'):
608 self.gui.main_window.show_message(_("To use this feature, first enable the exchange rate plugin."))
611 if not self.gui.main_window.network.is_connected():
612 self.gui.main_window.show_message(_("To use this feature, you must have a network connection."))
615 quote_currency = self.fiat_unit()
617 d = QDialog(self.gui.main_window)
618 d.setWindowTitle("Fiat")
619 vbox = QVBoxLayout(d)
620 text = "Amount to Send in " + quote_currency
621 vbox.addWidget(QLabel(_(text)+':'))
624 fiat_e = AmountEdit(self.fiat_unit)
625 grid.addWidget(fiat_e, 1, 0)
628 self.get_fiat_price_text(r)
631 text = "1 BTC~%s"%quote
632 grid.addWidget(QLabel(_(text)), 4, 0, 3, 0)
634 self.gui.main_window.show_message(_("Exchange rate not available. Please check your network connection."))
638 vbox.addLayout(ok_cancel_buttons(d))
643 fiat = str(fiat_e.text())
645 if str(fiat) == "" or str(fiat) == ".":
649 btcamount = Decimal(fiat) / Decimal(quote)
650 if str(self.gui.main_window.base_unit()) == "mBTC":
651 btcamount = btcamount * 1000
652 quote = "%.8f"%btcamount
653 self.gui.main_window.amount_e.setText( quote )
655 def exchange_rate_button(self, grid):
656 quote_currency = self.config.get("currency", "EUR")
657 self.fiat_button = EnterButton(_(quote_currency), self.fiat_dialog)
658 grid.addWidget(self.fiat_button, 4, 3, Qt.AlignHCenter)