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",
32 class Exchanger(threading.Thread):
34 def __init__(self, parent):
35 threading.Thread.__init__(self)
38 self.quote_currencies = None
39 self.lock = threading.Lock()
40 self.query_rates = threading.Event()
41 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
42 self.parent.exchanges = EXCHANGES
43 self.parent.currencies = ["EUR","GBP","USD","PLN"]
44 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
45 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
46 self.is_running = False
48 def get_json(self, site, get_string):
50 connection = httplib.HTTPSConnection(site)
51 connection.request("GET", get_string)
54 resp = connection.getresponse()
55 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
58 json_resp = json.loads(resp.read())
64 def exchange(self, btc_amount, quote_currency):
66 if self.quote_currencies is None:
68 quote_currencies = self.quote_currencies.copy()
69 if quote_currency not in quote_currencies:
71 if self.use_exchange == "CoinDesk":
73 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
76 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
77 return btc_amount * decimal.Decimal(str(quote_currencies[quote_currency]))
80 self.is_running = False
82 def update_rate(self):
83 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
85 "BitcoinAverage": self.update_ba,
86 "BitcoinVenezuela": self.update_bv,
87 "Bitcurex": self.update_bx,
88 "Bitmarket": self.update_bm,
89 "BitPay": self.update_bp,
90 "Blockchain": self.update_bc,
91 "BTCChina": self.update_CNY,
92 "CaVirtEx": self.update_cv,
93 "CoinDesk": self.update_cd,
94 "Coinbase": self.update_cb,
95 "LocalBitcoins": self.update_lb,
96 "Winkdex": self.update_wd,
99 update_rates[self.use_exchange]()
104 self.is_running = True
105 while self.is_running:
106 self.query_rates.clear()
108 self.query_rates.wait(150)
113 resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
117 quote_currencies = {}
118 for cur in resp_currencies:
119 quote_currencies[str(cur["currency"])] = 0.0
121 self.quote_currencies = quote_currencies
122 self.parent.set_currencies(quote_currencies)
126 winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
127 ####could need nonce value in GET, no Docs available
130 quote_currencies = {"USD": 0.0}
131 ####get y of highest x in "prices"
132 lenprices = len(winkresp["prices"])
133 usdprice = winkresp["prices"][lenprices-1]["y"]
135 quote_currencies["USD"] = decimal.Decimal(str(usdprice))
137 self.quote_currencies = quote_currencies
140 self.parent.set_currencies(quote_currencies)
144 jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
147 quote_currencies = {"CAD": 0.0}
148 cadprice = jsonresp["last"]
150 quote_currencies["CAD"] = decimal.Decimal(str(cadprice))
152 self.quote_currencies = quote_currencies
155 self.parent.set_currencies(quote_currencies)
159 jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json")
162 quote_currencies = {"PLN": 0.0}
163 pln_price = jsonresp["last"]
165 quote_currencies["PLN"] = decimal.Decimal(str(pln_price))
167 self.quote_currencies = quote_currencies
170 self.parent.set_currencies(quote_currencies)
174 jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json")
177 quote_currencies = {"PLN": 0.0}
178 pln_price = jsonresp["last"]
180 quote_currencies["PLN"] = decimal.Decimal(str(pln_price))
182 self.quote_currencies = quote_currencies
185 self.parent.set_currencies(quote_currencies)
187 def update_CNY(self):
189 jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
192 quote_currencies = {"CNY": 0.0}
193 cnyprice = jsonresp["ticker"]["last"]
195 quote_currencies["CNY"] = decimal.Decimal(str(cnyprice))
197 self.quote_currencies = quote_currencies
200 self.parent.set_currencies(quote_currencies)
204 jsonresp = self.get_json('bitpay.com', "/api/rates")
207 quote_currencies = {}
210 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
212 self.quote_currencies = quote_currencies
215 self.parent.set_currencies(quote_currencies)
219 jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
223 quote_currencies = {}
226 if r[:7] == "btc_to_":
227 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
229 self.quote_currencies = quote_currencies
232 self.parent.set_currencies(quote_currencies)
237 jsonresp = self.get_json('blockchain.info', "/ticker")
240 quote_currencies = {}
243 quote_currencies[r] = self._lookup_rate(jsonresp, r)
245 self.quote_currencies = quote_currencies
248 self.parent.set_currencies(quote_currencies)
249 # print "updating exchange rate", self.quote_currencies["USD"]
253 jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
256 quote_currencies = {}
259 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
261 self.quote_currencies = quote_currencies
264 self.parent.set_currencies(quote_currencies)
269 jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
272 quote_currencies = {}
274 for r in jsonresp["BTC"]:
275 quote_currencies[r] = Decimal(jsonresp["BTC"][r])
277 self.quote_currencies = quote_currencies
280 self.parent.set_currencies(quote_currencies)
285 jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
288 quote_currencies = {}
291 if not r == "timestamp":
292 quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
294 self.quote_currencies = quote_currencies
297 self.parent.set_currencies(quote_currencies)
300 def get_currencies(self):
301 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
303 def _lookup_rate(self, response, quote_id):
304 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
305 def _lookup_rate_cb(self, response, quote_id):
306 return decimal.Decimal(str(response[str(quote_id)]))
307 def _lookup_rate_ba(self, response, quote_id):
308 return decimal.Decimal(response[str(quote_id)]["last"])
309 def _lookup_rate_lb(self, response, quote_id):
310 return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
313 class Plugin(BasePlugin):
316 return "Exchange rates"
318 def description(self):
319 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
322 def __init__(self,a,b):
323 BasePlugin.__init__(self,a,b)
324 self.currencies = [self.fiat_unit()]
325 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
328 self.win = self.gui.main_window
329 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
330 self.btc_rate = Decimal("0.0")
332 self.exchanger = Exchanger(self)
333 self.exchanger.start()
334 self.gui.exchanger = self.exchanger #
337 def set_currencies(self, currency_options):
338 self.currencies = sorted(currency_options)
339 self.win.emit(SIGNAL("refresh_currencies()"))
340 self.win.emit(SIGNAL("refresh_currencies_combo()"))
342 def get_fiat_balance_text(self, btc_balance, r):
343 # return balance as: 1.23 USD
344 r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / 100000000)
346 def get_fiat_price_text(self, r):
347 # return BTC price as: 123.45 USD
348 r[0] = self.create_fiat_balance_text(1)
353 def get_fiat_status_text(self, btc_balance, r2):
354 # return status as: (1.23 USD) 1 BTC~123.45 USD
357 self.get_fiat_price_text(r)
360 price_text = "1 BTC~%s"%quote
361 fiat_currency = quote[-3:]
362 btc_price = self.btc_rate
363 fiat_balance = Decimal(btc_price) * (Decimal(btc_balance)/100000000)
364 balance_text = "(%.2f %s)" % (fiat_balance,fiat_currency)
365 text = " " + balance_text + " " + price_text + " "
368 def create_fiat_balance_text(self, btc_balance):
369 quote_currency = self.fiat_unit()
370 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
371 cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
375 quote_balance = btc_balance * Decimal(cur_rate)
376 self.btc_rate = cur_rate
377 quote_text = "%.2f %s" % (quote_balance, quote_currency)
380 def load_wallet(self, wallet):
383 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
384 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
385 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
387 self.tx_list = tx_list
390 def requires_settings(self):
395 enabled = BasePlugin.toggle(self)
396 self.win.update_status()
397 self.win.tabs.removeTab(1)
398 new_send_tab = self.gui.main_window.create_send_tab()
399 self.win.tabs.insertTab(1, new_send_tab, _('Send'))
406 self.exchanger.stop()
408 def history_tab_update(self):
409 if self.config.get('history_rates', 'unchecked') == "checked":
410 cur_exchange = self.config.get('use_exchange', "Blockchain")
412 tx_list = self.tx_list
417 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
420 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
422 if cur_exchange == "CoinDesk":
424 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
427 elif cur_exchange == "Winkdex":
429 resp_hist = self.exchanger.get_json('winkdex.com', "/static/data/0_86400_730.json")['prices']
432 elif cur_exchange == "BitcoinVenezuela":
433 cur_currency = self.fiat_unit()
434 if cur_currency == "VEF":
436 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
439 elif cur_currency == "ARS":
441 resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
447 self.gui.main_window.is_edit = True
448 self.gui.main_window.history_list.setColumnCount(6)
449 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
450 root = self.gui.main_window.history_list.invisibleRootItem()
451 childcount = root.childCount()
452 for i in range(childcount):
455 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
457 newtx = self.wallet.get_tx_history()
458 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
460 tx_info = {'timestamp':int(time.time()), 'value': v }
462 tx_time = int(tx_info['timestamp'])
463 if cur_exchange == "CoinDesk":
464 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
466 tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
468 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
469 elif cur_exchange == "Winkdex":
470 tx_time_str = int(tx_time) - (int(tx_time) % (60 * 60 * 24))
472 tx_rate = resp_hist[[x['x'] for x in resp_hist].index(tx_time_str)]['y']
473 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate), "USD")
475 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
476 elif cur_exchange == "BitcoinVenezuela":
477 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
479 num = resp_hist[tx_time_str].replace(',','')
480 tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
482 tx_BTCVEN_val = _("No data")
484 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
485 item.setText(5, tx_USD_val)
486 elif cur_exchange == "BitcoinVenezuela":
487 item.setText(5, tx_BTCVEN_val)
488 if Decimal(str(tx_info['value'])) < 0:
489 item.setForeground(5, QBrush(QColor("#BC1E1E")))
491 for i, width in enumerate(self.gui.main_window.column_widths['history']):
492 self.gui.main_window.history_list.setColumnWidth(i, width)
493 self.gui.main_window.history_list.setColumnWidth(4, 140)
494 self.gui.main_window.history_list.setColumnWidth(5, 120)
495 self.gui.main_window.is_edit = False
498 def settings_widget(self, window):
499 return EnterButton(_('Settings'), self.settings_dialog)
501 def settings_dialog(self):
503 d.setWindowTitle("Settings")
504 layout = QGridLayout(d)
505 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
506 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
507 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
509 combo_ex = QComboBox()
510 hist_checkbox = QCheckBox()
511 hist_checkbox.setEnabled(False)
512 if self.config.get('history_rates', 'unchecked') == 'unchecked':
513 hist_checkbox.setChecked(False)
515 hist_checkbox.setChecked(True)
516 ok_button = QPushButton(_("OK"))
520 cur_request = str(self.currencies[x])
523 if cur_request != self.fiat_unit():
524 self.config.set_key('currency', cur_request, True)
525 cur_exchange = self.config.get('use_exchange', "Blockchain")
526 if cur_request == "USD" and (cur_exchange == "CoinDesk" or cur_exchange == "Winkdex"):
527 hist_checkbox.setEnabled(True)
528 elif cur_request == "VEF" and (cur_exchange == "BitcoinVenezuela"):
529 hist_checkbox.setEnabled(True)
530 elif cur_request == "ARS" and (cur_exchange == "BitcoinVenezuela"):
531 hist_checkbox.setEnabled(True)
533 hist_checkbox.setChecked(False)
534 hist_checkbox.setEnabled(False)
535 self.win.update_status()
541 self.fiat_button.setText(cur_request)
544 hist_checkbox.setChecked(False)
545 hist_checkbox.setEnabled(False)
548 cur_request = str(self.exchanges[x])
549 if cur_request != self.config.get('use_exchange', "Blockchain"):
550 self.config.set_key('use_exchange', cur_request, True)
553 self.exchanger.query_rates.set()
554 cur_currency = self.fiat_unit()
555 if cur_request == "CoinDesk" or cur_request == "Winkdex":
556 if cur_currency == "USD":
557 hist_checkbox.setEnabled(True)
560 elif cur_request == "BitcoinVenezuela":
561 if cur_currency == "VEF" or cur_currency == "ARS":
562 hist_checkbox.setEnabled(True)
567 set_currencies(combo)
568 self.win.update_status()
570 def on_change_hist(checked):
572 self.config.set_key('history_rates', 'checked')
573 self.history_tab_update()
575 self.config.set_key('history_rates', 'unchecked')
576 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
577 self.gui.main_window.history_list.setColumnCount(5)
578 for i,width in enumerate(self.gui.main_window.column_widths['history']):
579 self.gui.main_window.history_list.setColumnWidth(i, width)
581 def set_hist_check(hist_checkbox):
582 cur_exchange = self.config.get('use_exchange', "Blockchain")
583 if cur_exchange == "CoinDesk" or cur_exchange == "Winkdex":
584 hist_checkbox.setEnabled(True)
585 elif cur_exchange == "BitcoinVenezuela":
586 hist_checkbox.setEnabled(True)
588 hist_checkbox.setEnabled(False)
590 def set_currencies(combo):
591 current_currency = self.fiat_unit()
596 combo.addItems(self.currencies)
598 index = self.currencies.index(current_currency)
601 combo.setCurrentIndex(index)
603 def set_exchanges(combo_ex):
608 combo_ex.addItems(self.exchanges)
610 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
613 combo_ex.setCurrentIndex(index)
618 set_exchanges(combo_ex)
619 set_currencies(combo)
620 set_hist_check(hist_checkbox)
621 combo.currentIndexChanged.connect(on_change)
622 combo_ex.currentIndexChanged.connect(on_change_ex)
623 hist_checkbox.stateChanged.connect(on_change_hist)
624 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
625 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
626 ok_button.clicked.connect(lambda: ok_clicked())
627 layout.addWidget(combo,1,1)
628 layout.addWidget(combo_ex,0,1)
629 layout.addWidget(hist_checkbox,2,1)
630 layout.addWidget(ok_button,3,1)
638 return self.config.get("currency", "EUR")
640 def add_fiat_edit(self):
641 self.fiat_e = AmountEdit(self.fiat_unit)
642 self.btc_e = self.win.amount_e
643 grid = self.btc_e.parent()
646 fiat_amount = Decimal(str(self.fiat_e.text()))
648 self.btc_e.setText("")
650 exchange_rate = self.exchanger.exchange(Decimal("1.0"), self.fiat_unit())
651 if exchange_rate is not None:
652 btc_amount = fiat_amount/exchange_rate
653 self.btc_e.setAmount(int(btc_amount*Decimal(100000000)))
654 self.fiat_e.textEdited.connect(fiat_changed)
656 btc_amount = self.btc_e.get_amount()
657 if btc_amount is None:
658 self.fiat_e.setText("")
660 fiat_amount = self.exchanger.exchange(Decimal(btc_amount)/Decimal(100000000), self.fiat_unit())
661 if fiat_amount is not None:
662 self.fiat_e.setText("%.2f"%fiat_amount)
663 self.btc_e.textEdited.connect(btc_changed)
664 self.btc_e.frozen.connect(lambda: self.fiat_e.setFrozen(self.btc_e.isReadOnly()))
665 self.win.send_grid.addWidget(self.fiat_e, 4, 3, Qt.AlignHCenter)