1 from PyQt4.QtGui import *
2 from PyQt4.QtCore import *
10 from decimal import Decimal
11 from electrum.plugins import BasePlugin
12 from electrum.i18n import _
13 from electrum_gui.qt.util import *
14 from electrum_gui.qt.amountedit import AmountEdit
17 EXCHANGES = ["BitcoinAverage",
31 class Exchanger(threading.Thread):
33 def __init__(self, parent):
34 threading.Thread.__init__(self)
37 self.quote_currencies = None
38 self.lock = threading.Lock()
39 self.query_rates = threading.Event()
40 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
41 self.parent.exchanges = EXCHANGES
42 self.parent.currencies = ["EUR","GBP","USD","PLN"]
43 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
44 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
45 self.is_running = False
47 def get_json(self, site, get_string):
49 connection = httplib.HTTPSConnection(site)
50 connection.request("GET", get_string)
53 resp = connection.getresponse()
54 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
57 json_resp = json.loads(resp.read())
63 def exchange(self, btc_amount, quote_currency):
65 if self.quote_currencies is None:
67 quote_currencies = self.quote_currencies.copy()
68 if quote_currency not in quote_currencies:
70 if self.use_exchange == "CoinDesk":
72 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
75 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
76 return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency]))
79 self.is_running = False
81 def update_rate(self):
82 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
84 "BitcoinAverage": self.update_ba,
85 "BitcoinVenezuela": self.update_bv,
86 "Bitcurex": self.update_bx,
87 "Bitmarket": self.update_bm,
88 "BitPay": self.update_bp,
89 "Blockchain": self.update_bc,
90 "BTCChina": self.update_CNY,
91 "CaVirtEx": self.update_cv,
92 "CoinDesk": self.update_cd,
93 "Coinbase": self.update_cb,
94 "LocalBitcoins": self.update_lb,
95 "Winkdex": self.update_wd,
98 update_rates[self.use_exchange]()
103 self.is_running = True
104 while self.is_running:
105 self.query_rates.clear()
107 self.query_rates.wait(150)
112 resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
116 quote_currencies = {}
117 for cur in resp_currencies:
118 quote_currencies[str(cur["currency"])] = 0.0
120 self.quote_currencies = quote_currencies
121 self.parent.set_currencies(quote_currencies)
125 winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
126 ####could need nonce value in GET, no Docs available
129 quote_currencies = {"USD": 0.0}
130 ####get y of highest x in "prices"
131 lenprices = len(winkresp["prices"])
132 usdprice = winkresp["prices"][lenprices-1]["y"]
134 quote_currencies["USD"] = decimal.Decimal(str(usdprice))
136 self.quote_currencies = quote_currencies
139 self.parent.set_currencies(quote_currencies)
143 jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
146 quote_currencies = {"CAD": 0.0}
147 cadprice = jsonresp["last"]
149 quote_currencies["CAD"] = decimal.Decimal(str(cadprice))
151 self.quote_currencies = quote_currencies
154 self.parent.set_currencies(quote_currencies)
158 jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json")
161 quote_currencies = {"PLN": 0.0}
162 pln_price = jsonresp["last"]
164 quote_currencies["PLN"] = decimal.Decimal(str(pln_price))
166 self.quote_currencies = quote_currencies
169 self.parent.set_currencies(quote_currencies)
173 jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json")
176 quote_currencies = {"PLN": 0.0}
177 pln_price = jsonresp["last"]
179 quote_currencies["PLN"] = decimal.Decimal(str(pln_price))
181 self.quote_currencies = quote_currencies
184 self.parent.set_currencies(quote_currencies)
186 def update_CNY(self):
188 jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
191 quote_currencies = {"CNY": 0.0}
192 cnyprice = jsonresp["ticker"]["last"]
194 quote_currencies["CNY"] = decimal.Decimal(str(cnyprice))
196 self.quote_currencies = quote_currencies
199 self.parent.set_currencies(quote_currencies)
203 jsonresp = self.get_json('bitpay.com', "/api/rates")
206 quote_currencies = {}
209 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
211 self.quote_currencies = quote_currencies
214 self.parent.set_currencies(quote_currencies)
218 jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
222 quote_currencies = {}
225 if r[:7] == "btc_to_":
226 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
228 self.quote_currencies = quote_currencies
231 self.parent.set_currencies(quote_currencies)
236 jsonresp = self.get_json('blockchain.info', "/ticker")
239 quote_currencies = {}
242 quote_currencies[r] = self._lookup_rate(jsonresp, r)
244 self.quote_currencies = quote_currencies
247 self.parent.set_currencies(quote_currencies)
248 # print "updating exchange rate", self.quote_currencies["USD"]
252 jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
255 quote_currencies = {}
258 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
260 self.quote_currencies = quote_currencies
263 self.parent.set_currencies(quote_currencies)
268 jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
271 quote_currencies = {}
273 for r in jsonresp["BTC"]:
274 quote_currencies[r] = Decimal(jsonresp["BTC"][r])
276 self.quote_currencies = quote_currencies
279 self.parent.set_currencies(quote_currencies)
284 jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
287 quote_currencies = {}
290 if not r == "timestamp":
291 quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
293 self.quote_currencies = quote_currencies
296 self.parent.set_currencies(quote_currencies)
299 def get_currencies(self):
300 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
302 def _lookup_rate(self, response, quote_id):
303 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
304 def _lookup_rate_cb(self, response, quote_id):
305 return decimal.Decimal(str(response[str(quote_id)]))
306 def _lookup_rate_ba(self, response, quote_id):
307 return decimal.Decimal(response[str(quote_id)]["last"])
308 def _lookup_rate_lb(self, response, quote_id):
309 return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
312 class Plugin(BasePlugin):
315 return "Exchange rates"
317 def description(self):
318 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
321 def __init__(self,a,b):
322 BasePlugin.__init__(self,a,b)
323 self.currencies = [self.config.get('currency', "EUR")]
324 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
327 self.win = self.gui.main_window
328 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
329 self.btc_rate = Decimal("0.0")
331 self.exchanger = Exchanger(self)
332 self.exchanger.start()
333 self.gui.exchanger = self.exchanger #
335 def set_currencies(self, currency_options):
336 self.currencies = sorted(currency_options)
337 self.win.emit(SIGNAL("refresh_currencies()"))
338 self.win.emit(SIGNAL("refresh_currencies_combo()"))
340 def get_fiat_balance_text(self, btc_balance, r):
341 # return balance as: 1.23 USD
342 r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / 100000000)
344 def get_fiat_price_text(self, r):
345 # return BTC price as: 123.45 USD
346 r[0] = self.create_fiat_balance_text(1)
351 def get_fiat_status_text(self, btc_balance, r2):
352 # return status as: (1.23 USD) 1 BTC~123.45 USD
355 self.get_fiat_price_text(r)
358 price_text = "1 BTC~%s"%quote
359 fiat_currency = quote[-3:]
360 btc_price = quote[:-4]
361 fiat_balance = Decimal(btc_price) * (Decimal(btc_balance)/100000000)
362 balance_text = "(%.2f %s)" % (fiat_balance,fiat_currency)
363 text = " " + balance_text + " " + price_text + " "
366 def create_fiat_balance_text(self, btc_balance):
367 quote_currency = self.config.get("currency", "EUR")
368 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
369 cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
373 quote_balance = btc_balance * Decimal(cur_rate)
374 self.btc_rate = cur_rate
375 quote_text = "%.2f %s" % (quote_balance, quote_currency)
378 def load_wallet(self, wallet):
381 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
382 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
383 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
385 self.tx_list = tx_list
388 def requires_settings(self):
393 out = BasePlugin.toggle(self)
394 self.win.update_status()
395 if self.config.get('use_exchange_rate'):
399 self.gui.main_window.show_message(_("To see fiat amount when sending bitcoin, please restart Electrum to activate the new GUI settings."))
404 self.exchanger.stop()
406 def history_tab_update(self):
407 if self.config.get('history_rates', 'unchecked') == "checked":
408 cur_exchange = self.config.get('use_exchange', "Blockchain")
410 tx_list = self.tx_list
415 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
418 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
420 if cur_exchange == "CoinDesk":
422 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
425 elif cur_exchange == "Winkdex":
427 resp_hist = self.exchanger.get_json('winkdex.com', "/static/data/0_86400_730.json")['prices']
430 elif cur_exchange == "BitcoinVenezuela":
431 cur_currency = self.config.get('currency', "EUR")
432 if cur_currency == "VEF":
434 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php")['VEF_BTC']
437 elif cur_currency == "ARS":
439 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php")['ARS_BTC']
445 self.gui.main_window.is_edit = True
446 self.gui.main_window.history_list.setColumnCount(6)
447 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
448 root = self.gui.main_window.history_list.invisibleRootItem()
449 childcount = root.childCount()
450 for i in range(childcount):
453 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
455 newtx = self.wallet.get_tx_history()
456 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
458 tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
460 tx_time = int(tx_info['timestamp'])
461 if cur_exchange == "CoinDesk":
462 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
464 tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
466 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
467 elif cur_exchange == "Winkdex":
468 tx_time_str = int(tx_time) - (int(tx_time) % (60 * 60 * 24))
470 tx_rate = resp_hist[[x['x'] for x in resp_hist].index(tx_time_str)]['y']
471 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate), "USD")
473 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
474 elif cur_exchange == "BitcoinVenezuela":
475 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
477 num = resp_hist[tx_time_str].replace(',','')
478 tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
480 tx_BTCVEN_val = _("No data")
482 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
483 item.setText(5, tx_USD_val)
484 elif cur_exchange == "BitcoinVenezuela":
485 item.setText(5, tx_BTCVEN_val)
486 if Decimal(str(tx_info['value'])) < 0:
487 item.setForeground(5, QBrush(QColor("#BC1E1E")))
489 for i, width in enumerate(self.gui.main_window.column_widths['history']):
490 self.gui.main_window.history_list.setColumnWidth(i, width)
491 self.gui.main_window.history_list.setColumnWidth(4, 140)
492 self.gui.main_window.history_list.setColumnWidth(5, 120)
493 self.gui.main_window.is_edit = False
496 def settings_widget(self, window):
497 return EnterButton(_('Settings'), self.settings_dialog)
499 def settings_dialog(self):
501 d.setWindowTitle("Settings")
502 layout = QGridLayout(d)
503 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
504 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
505 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
507 combo_ex = QComboBox()
508 hist_checkbox = QCheckBox()
509 hist_checkbox.setEnabled(False)
510 if self.config.get('history_rates', 'unchecked') == 'unchecked':
511 hist_checkbox.setChecked(False)
513 hist_checkbox.setChecked(True)
514 ok_button = QPushButton(_("OK"))
518 cur_request = str(self.currencies[x])
521 if cur_request != self.config.get('currency', "EUR"):
522 self.config.set_key('currency', cur_request, True)
523 cur_exchange = self.config.get('use_exchange', "Blockchain")
524 if cur_request == "USD" and (cur_exchange == "CoinDesk" or cur_exchange == "Winkdex"):
525 hist_checkbox.setEnabled(True)
526 elif cur_request == "VEF" and (cur_exchange == "BitcoinVenezuela"):
527 hist_checkbox.setEnabled(True)
528 elif cur_request == "ARS" and (cur_exchange == "BitcoinVenezuela"):
529 hist_checkbox.setEnabled(True)
531 hist_checkbox.setChecked(False)
532 hist_checkbox.setEnabled(False)
533 self.win.update_status()
539 self.fiat_button.setText(cur_request)
542 hist_checkbox.setChecked(False)
543 hist_checkbox.setEnabled(False)
546 cur_request = str(self.exchanges[x])
547 if cur_request != self.config.get('use_exchange', "Blockchain"):
548 self.config.set_key('use_exchange', cur_request, True)
551 self.exchanger.query_rates.set()
552 cur_currency = self.config.get('currency', "EUR")
553 if cur_request == "CoinDesk" or cur_request == "Winkdex":
554 if cur_currency == "USD":
555 hist_checkbox.setEnabled(True)
558 elif cur_request == "BitcoinVenezuela":
559 if cur_currency == "VEF" or cur_currency == "ARS":
560 hist_checkbox.setEnabled(True)
565 set_currencies(combo)
566 self.win.update_status()
568 def on_change_hist(checked):
570 self.config.set_key('history_rates', 'checked')
571 self.history_tab_update()
573 self.config.set_key('history_rates', 'unchecked')
574 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
575 self.gui.main_window.history_list.setColumnCount(5)
576 for i,width in enumerate(self.gui.main_window.column_widths['history']):
577 self.gui.main_window.history_list.setColumnWidth(i, width)
579 def set_hist_check(hist_checkbox):
580 cur_exchange = self.config.get('use_exchange', "Blockchain")
581 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
582 hist_checkbox.setEnabled(True)
583 elif cur_exchange == "BitcoinVenezuela":
584 hist_checkbox.setEnabled(True)
586 hist_checkbox.setEnabled(False)
588 def set_currencies(combo):
589 current_currency = self.config.get('currency', "EUR")
594 combo.addItems(self.currencies)
596 index = self.currencies.index(current_currency)
599 combo.setCurrentIndex(index)
601 def set_exchanges(combo_ex):
606 combo_ex.addItems(self.exchanges)
608 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
611 combo_ex.setCurrentIndex(index)
616 set_exchanges(combo_ex)
617 set_currencies(combo)
618 set_hist_check(hist_checkbox)
619 combo.currentIndexChanged.connect(on_change)
620 combo_ex.currentIndexChanged.connect(on_change_ex)
621 hist_checkbox.stateChanged.connect(on_change_hist)
622 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
623 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
624 ok_button.clicked.connect(lambda: ok_clicked())
625 layout.addWidget(combo,1,1)
626 layout.addWidget(combo_ex,0,1)
627 layout.addWidget(hist_checkbox,2,1)
628 layout.addWidget(ok_button,3,1)
636 quote_currency = self.config.get("currency", "???")
637 return quote_currency
639 def fiat_dialog(self):
640 if not self.config.get('use_exchange_rate'):
641 self.gui.main_window.show_message(_("To use this feature, first enable the exchange rate plugin."))
644 if not self.gui.main_window.network.is_connected():
645 self.gui.main_window.show_message(_("To use this feature, you must have a network connection."))
648 quote_currency = self.fiat_unit()
650 d = QDialog(self.gui.main_window)
651 d.setWindowTitle("Fiat")
652 vbox = QVBoxLayout(d)
653 text = "Amount to Send in " + quote_currency
654 vbox.addWidget(QLabel(_(text)+':'))
657 fiat_e = AmountEdit(self.fiat_unit)
658 grid.addWidget(fiat_e, 1, 0)
661 self.get_fiat_price_text(r)
664 text = "1 BTC~%s"%quote
665 grid.addWidget(QLabel(_(text)), 4, 0, 3, 0)
667 self.gui.main_window.show_message(_("Exchange rate not available. Please check your network connection."))
671 vbox.addLayout(ok_cancel_buttons(d))
676 fiat = str(fiat_e.text())
678 if str(fiat) == "" or str(fiat) == ".":
682 btcamount = Decimal(fiat) / Decimal(quote)
683 if str(self.gui.main_window.base_unit()) == "mBTC":
684 btcamount = btcamount * 1000
685 quote = "%.8f"%btcamount
686 self.gui.main_window.amount_e.setText( quote )
688 def exchange_rate_button(self, grid):
689 quote_currency = self.config.get("currency", "EUR")
690 self.fiat_button = EnterButton(_(quote_currency), self.fiat_dialog)
691 grid.addWidget(self.fiat_button, 4, 3, Qt.AlignHCenter)