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",
29 class Exchanger(threading.Thread):
31 def __init__(self, parent):
32 threading.Thread.__init__(self)
35 self.quote_currencies = None
36 self.lock = threading.Lock()
37 self.query_rates = threading.Event()
38 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
39 self.parent.exchanges = EXCHANGES
40 self.parent.currencies = ["EUR","GBP","USD"]
41 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
42 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
43 self.is_running = False
45 def get_json(self, site, get_string):
47 connection = httplib.HTTPSConnection(site)
48 connection.request("GET", get_string)
51 resp = connection.getresponse()
52 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
55 json_resp = json.loads(resp.read())
61 def exchange(self, btc_amount, quote_currency):
63 if self.quote_currencies is None:
65 quote_currencies = self.quote_currencies.copy()
66 if quote_currency not in quote_currencies:
68 if self.use_exchange == "CoinDesk":
70 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
73 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
74 return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency]))
77 self.is_running = False
79 def update_rate(self):
80 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
82 "BitcoinAverage": self.update_ba,
83 "BitcoinVenezuela": self.update_bv,
84 "BitPay": self.update_bp,
85 "Blockchain": self.update_bc,
86 "BTCChina": self.update_CNY,
87 "CaVirtEx": self.update_cv,
88 "CoinDesk": self.update_cd,
89 "Coinbase": self.update_cb,
90 "LocalBitcoins": self.update_lb,
91 "Winkdex": self.update_wd,
94 update_rates[self.use_exchange]()
99 self.is_running = True
100 while self.is_running:
101 self.query_rates.clear()
103 self.query_rates.wait(150)
108 resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
112 quote_currencies = {}
113 for cur in resp_currencies:
114 quote_currencies[str(cur["currency"])] = 0.0
116 self.quote_currencies = quote_currencies
117 self.parent.set_currencies(quote_currencies)
121 winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
122 ####could need nonce value in GET, no Docs available
125 quote_currencies = {"USD": 0.0}
126 ####get y of highest x in "prices"
127 lenprices = len(winkresp["prices"])
128 usdprice = winkresp["prices"][lenprices-1]["y"]
130 quote_currencies["USD"] = decimal.Decimal(str(usdprice))
132 self.quote_currencies = quote_currencies
135 self.parent.set_currencies(quote_currencies)
139 jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
142 quote_currencies = {"CAD": 0.0}
143 cadprice = jsonresp["last"]
145 quote_currencies["CAD"] = decimal.Decimal(str(cadprice))
147 self.quote_currencies = quote_currencies
150 self.parent.set_currencies(quote_currencies)
152 def update_CNY(self):
154 jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
157 quote_currencies = {"CNY": 0.0}
158 cnyprice = jsonresp["ticker"]["last"]
160 quote_currencies["CNY"] = decimal.Decimal(str(cnyprice))
162 self.quote_currencies = quote_currencies
165 self.parent.set_currencies(quote_currencies)
169 jsonresp = self.get_json('bitpay.com', "/api/rates")
172 quote_currencies = {}
175 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
177 self.quote_currencies = quote_currencies
180 self.parent.set_currencies(quote_currencies)
184 jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
188 quote_currencies = {}
191 if r[:7] == "btc_to_":
192 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
194 self.quote_currencies = quote_currencies
197 self.parent.set_currencies(quote_currencies)
202 jsonresp = self.get_json('blockchain.info', "/ticker")
205 quote_currencies = {}
208 quote_currencies[r] = self._lookup_rate(jsonresp, r)
210 self.quote_currencies = quote_currencies
213 self.parent.set_currencies(quote_currencies)
214 # print "updating exchange rate", self.quote_currencies["USD"]
218 jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
221 quote_currencies = {}
224 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
226 self.quote_currencies = quote_currencies
229 self.parent.set_currencies(quote_currencies)
234 jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
237 quote_currencies = {}
239 for r in jsonresp["BTC"]:
240 quote_currencies[r] = Decimal(jsonresp["BTC"][r])
242 self.quote_currencies = quote_currencies
245 self.parent.set_currencies(quote_currencies)
250 jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
253 quote_currencies = {}
256 if not r == "timestamp":
257 quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
259 self.quote_currencies = quote_currencies
262 self.parent.set_currencies(quote_currencies)
265 def get_currencies(self):
266 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
268 def _lookup_rate(self, response, quote_id):
269 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
270 def _lookup_rate_cb(self, response, quote_id):
271 return decimal.Decimal(str(response[str(quote_id)]))
272 def _lookup_rate_ba(self, response, quote_id):
273 return decimal.Decimal(response[str(quote_id)]["last"])
274 def _lookup_rate_lb(self, response, quote_id):
275 return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
278 class Plugin(BasePlugin):
281 return "Exchange rates"
283 def description(self):
284 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
287 def __init__(self,a,b):
288 BasePlugin.__init__(self,a,b)
289 self.currencies = [self.config.get('currency', "EUR")]
290 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
293 self.win = self.gui.main_window
294 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
295 self.btc_rate = Decimal("0.0")
297 self.exchanger = Exchanger(self)
298 self.exchanger.start()
299 self.gui.exchanger = self.exchanger #
301 def set_currencies(self, currency_options):
302 self.currencies = sorted(currency_options)
303 self.win.emit(SIGNAL("refresh_currencies()"))
304 self.win.emit(SIGNAL("refresh_currencies_combo()"))
306 def get_fiat_balance_text(self, btc_balance, r):
307 # return balance as: 1.23 USD
308 r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / 100000000)
310 def get_fiat_price_text(self, r):
311 # return BTC price as: 123.45 USD
312 r[0] = self.create_fiat_balance_text(1)
317 def get_fiat_status_text(self, btc_balance, r2):
318 # return status as: (1.23 USD) 1 BTC~123.45 USD
322 self.get_fiat_balance_text(btc_balance, r)
325 text += " (%s)"%quote
328 self.get_fiat_price_text(r)
331 text += " 1 BTC~%s "%quote
334 def create_fiat_balance_text(self, btc_balance):
335 quote_currency = self.config.get("currency", "EUR")
336 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
337 cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
341 quote_balance = btc_balance * Decimal(cur_rate)
342 self.btc_rate = cur_rate
343 quote_text = "%.2f %s" % (quote_balance, quote_currency)
346 def load_wallet(self, wallet):
349 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
350 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
351 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
353 self.tx_list = tx_list
356 def requires_settings(self):
361 out = BasePlugin.toggle(self)
362 self.win.update_status()
363 if self.config.get('use_exchange_rate'):
367 self.gui.main_window.show_message(_("To see fiat amount when sending bitcoin, please restart Electrum to activate the new GUI settings."))
372 self.exchanger.stop()
374 def history_tab_update(self):
375 if self.config.get('history_rates', 'unchecked') == "checked":
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 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
391 self.gui.main_window.is_edit = True
392 self.gui.main_window.history_list.setColumnCount(6)
393 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
394 root = self.gui.main_window.history_list.invisibleRootItem()
395 childcount = root.childCount()
396 for i in range(childcount):
399 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
401 newtx = self.wallet.get_tx_history()
402 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
404 tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
406 tx_time = int(tx_info['timestamp'])
407 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
409 tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
411 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
413 item.setText(5, tx_USD_val)
414 if Decimal(str(tx_info['value'])) < 0:
415 item.setForeground(5, QBrush(QColor("#BC1E1E")))
417 for i, width in enumerate(self.gui.main_window.column_widths['history']):
418 self.gui.main_window.history_list.setColumnWidth(i, width)
419 self.gui.main_window.history_list.setColumnWidth(4, 140)
420 self.gui.main_window.history_list.setColumnWidth(5, 120)
421 self.gui.main_window.is_edit = False
424 def settings_widget(self, window):
425 return EnterButton(_('Settings'), self.settings_dialog)
427 def settings_dialog(self):
429 d.setWindowTitle("Settings")
430 layout = QGridLayout(d)
431 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
432 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
433 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
435 combo_ex = QComboBox()
436 hist_checkbox = QCheckBox()
437 hist_checkbox.setEnabled(False)
438 if self.config.get('history_rates', 'unchecked') == 'unchecked':
439 hist_checkbox.setChecked(False)
441 hist_checkbox.setChecked(True)
442 ok_button = QPushButton(_("OK"))
446 cur_request = str(self.currencies[x])
449 if cur_request != self.config.get('currency', "EUR"):
450 self.config.set_key('currency', cur_request, True)
451 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
452 hist_checkbox.setEnabled(True)
454 hist_checkbox.setChecked(False)
455 hist_checkbox.setEnabled(False)
456 self.win.update_status()
462 self.fiat_button.setText(cur_request)
465 hist_checkbox.setChecked(False)
466 hist_checkbox.setEnabled(False)
469 cur_request = str(self.exchanges[x])
470 if cur_request != self.config.get('use_exchange', "Blockchain"):
471 self.config.set_key('use_exchange', cur_request, True)
474 self.exchanger.query_rates.set()
475 if cur_request == "CoinDesk":
476 if self.config.get('currency', "EUR") == "USD":
477 hist_checkbox.setEnabled(True)
482 set_currencies(combo)
483 self.win.update_status()
485 def on_change_hist(checked):
487 self.config.set_key('history_rates', 'checked')
488 self.history_tab_update()
490 self.config.set_key('history_rates', 'unchecked')
491 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
492 self.gui.main_window.history_list.setColumnCount(5)
493 for i,width in enumerate(self.gui.main_window.column_widths['history']):
494 self.gui.main_window.history_list.setColumnWidth(i, width)
496 def set_hist_check(hist_checkbox):
497 if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
498 hist_checkbox.setEnabled(True)
500 hist_checkbox.setEnabled(False)
502 def set_currencies(combo):
503 current_currency = self.config.get('currency', "EUR")
508 combo.addItems(self.currencies)
510 index = self.currencies.index(current_currency)
513 combo.setCurrentIndex(index)
515 def set_exchanges(combo_ex):
520 combo_ex.addItems(self.exchanges)
522 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
525 combo_ex.setCurrentIndex(index)
530 set_exchanges(combo_ex)
531 set_currencies(combo)
532 set_hist_check(hist_checkbox)
533 combo.currentIndexChanged.connect(on_change)
534 combo_ex.currentIndexChanged.connect(on_change_ex)
535 hist_checkbox.stateChanged.connect(on_change_hist)
536 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
537 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
538 ok_button.clicked.connect(lambda: ok_clicked())
539 layout.addWidget(combo,1,1)
540 layout.addWidget(combo_ex,0,1)
541 layout.addWidget(hist_checkbox,2,1)
542 layout.addWidget(ok_button,3,1)
550 quote_currency = self.config.get("currency", "???")
551 return quote_currency
553 def fiat_dialog(self):
554 if not self.config.get('use_exchange_rate'):
555 self.gui.main_window.show_message(_("To use this feature, first enable the exchange rate plugin."))
558 if not self.gui.main_window.network.is_connected():
559 self.gui.main_window.show_message(_("To use this feature, you must have a network connection."))
562 quote_currency = self.fiat_unit()
564 d = QDialog(self.gui.main_window)
565 d.setWindowTitle("Fiat")
566 vbox = QVBoxLayout(d)
567 text = "Amount to Send in " + quote_currency
568 vbox.addWidget(QLabel(_(text)+':'))
571 fiat_e = AmountEdit(self.fiat_unit)
572 grid.addWidget(fiat_e, 1, 0)
575 self.get_fiat_price_text(r)
578 text = "1 BTC~%s"%quote
579 grid.addWidget(QLabel(_(text)), 4, 0, 3, 0)
582 vbox.addLayout(ok_cancel_buttons(d))
587 fiat = str(fiat_e.text())
589 if str(fiat) == "" or str(fiat) == ".":
593 self.get_fiat_price_text(r)
596 self.gui.main_window.show_message(_("Exchange rate not available. Please check your network connection."))
600 btcamount = Decimal(fiat) / Decimal(quote)
601 if str(self.gui.main_window.base_unit()) == "mBTC":
602 btcamount = btcamount * 1000
603 quote = "%.8f"%btcamount
604 self.gui.main_window.amount_e.setText( quote )
606 def exchange_rate_button(self, grid):
607 quote_currency = self.config.get("currency", "EUR")
608 self.fiat_button = EnterButton(_(quote_currency), self.fiat_dialog)
609 grid.addWidget(self.fiat_button, 4, 3, Qt.AlignHCenter)