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 *
16 EXCHANGES = ["BitcoinAverage",
27 class Exchanger(threading.Thread):
29 def __init__(self, parent):
30 threading.Thread.__init__(self)
33 self.quote_currencies = None
34 self.lock = threading.Lock()
35 self.query_rates = threading.Event()
36 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
37 self.parent.exchanges = EXCHANGES
38 self.parent.currencies = ["EUR","GBP","USD"]
39 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
40 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
41 self.is_running = False
43 def get_json(self, site, get_string):
45 connection = httplib.HTTPSConnection(site)
46 connection.request("GET", get_string)
49 resp = connection.getresponse()
50 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
53 json_resp = json.loads(resp.read())
59 def exchange(self, btc_amount, quote_currency):
61 if self.quote_currencies is None:
63 quote_currencies = self.quote_currencies.copy()
64 if quote_currency not in quote_currencies:
66 if self.use_exchange == "CoinDesk":
68 resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
71 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
72 return btc_amount * decimal.Decimal(quote_currencies[quote_currency])
75 self.is_running = False
77 def update_rate(self):
78 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
80 "BitcoinAverage": self.update_ba,
81 "BitPay": self.update_bp,
82 "Blockchain": self.update_bc,
83 "BTCChina": self.update_CNY,
84 "CaVirtEx": self.update_cv,
85 "CoinDesk": self.update_cd,
86 "Coinbase": self.update_cb,
87 "LocalBitcoins": self.update_lb,
88 "Winkdex": self.update_wd,
91 update_rates[self.use_exchange]()
96 self.is_running = True
97 while self.is_running:
98 self.query_rates.clear()
100 self.query_rates.wait(150)
105 resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
109 quote_currencies = {}
110 for cur in resp_currencies:
111 quote_currencies[str(cur["currency"])] = 0.0
113 self.quote_currencies = quote_currencies
114 self.parent.set_currencies(quote_currencies)
118 winkresp = self.get_json('winkdex.com', "/static/data/0_600_288.json")
119 ####could need nonce value in GET, no Docs available
122 quote_currencies = {"USD": 0.0}
123 ####get y of highest x in "prices"
124 lenprices = len(winkresp["prices"])
125 usdprice = winkresp["prices"][lenprices-1]["y"]
127 quote_currencies["USD"] = decimal.Decimal(usdprice)
129 self.quote_currencies = quote_currencies
132 self.parent.set_currencies(quote_currencies)
136 jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
139 quote_currencies = {"CAD": 0.0}
140 cadprice = jsonresp["last"]
142 quote_currencies["CAD"] = decimal.Decimal(cadprice)
144 self.quote_currencies = quote_currencies
147 self.parent.set_currencies(quote_currencies)
149 def update_CNY(self):
151 jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
154 quote_currencies = {"CNY": 0.0}
155 cnyprice = jsonresp["ticker"]["last"]
157 quote_currencies["CNY"] = decimal.Decimal(cnyprice)
159 self.quote_currencies = quote_currencies
162 self.parent.set_currencies(quote_currencies)
166 jsonresp = self.get_json('bitpay.com', "/api/rates")
169 quote_currencies = {}
172 quote_currencies[str(r["code"])] = decimal.Decimal(r["rate"])
174 self.quote_currencies = quote_currencies
177 self.parent.set_currencies(quote_currencies)
181 jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
185 quote_currencies = {}
188 if r[:7] == "btc_to_":
189 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(jsonresp, r)
191 self.quote_currencies = quote_currencies
194 self.parent.set_currencies(quote_currencies)
199 jsonresp = self.get_json('blockchain.info', "/ticker")
202 quote_currencies = {}
205 quote_currencies[r] = self._lookup_rate(jsonresp, r)
207 self.quote_currencies = quote_currencies
210 self.parent.set_currencies(quote_currencies)
211 # print "updating exchange rate", self.quote_currencies["USD"]
215 jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
218 quote_currencies = {}
221 quote_currencies[r] = self._lookup_rate_lb(jsonresp, r)
223 self.quote_currencies = quote_currencies
226 self.parent.set_currencies(quote_currencies)
231 jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
234 quote_currencies = {}
237 if not r == "timestamp":
238 quote_currencies[r] = self._lookup_rate_ba(jsonresp, r)
240 self.quote_currencies = quote_currencies
243 self.parent.set_currencies(quote_currencies)
246 def get_currencies(self):
247 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
249 def _lookup_rate(self, response, quote_id):
250 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
251 def _lookup_rate_cb(self, response, quote_id):
252 return decimal.Decimal(str(response[str(quote_id)]))
253 def _lookup_rate_ba(self, response, quote_id):
254 return decimal.Decimal(response[str(quote_id)]["last"])
255 def _lookup_rate_lb(self, response, quote_id):
256 return decimal.Decimal(response[str(quote_id)]["rates"]["last"])
259 class Plugin(BasePlugin):
262 return "Exchange rates"
264 def description(self):
265 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
268 def __init__(self,a,b):
269 BasePlugin.__init__(self,a,b)
270 self.currencies = [self.config.get('currency', "EUR")]
271 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
274 self.win = self.gui.main_window
275 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
277 self.exchanger = Exchanger(self)
278 self.exchanger.start()
279 self.gui.exchanger = self.exchanger #
281 def set_currencies(self, currency_options):
282 self.currencies = sorted(currency_options)
283 self.win.emit(SIGNAL("refresh_currencies()"))
284 self.win.emit(SIGNAL("refresh_currencies_combo()"))
287 def set_quote_text(self, btc_balance, r):
288 r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
290 def create_quote_text(self, btc_balance):
291 quote_currency = self.config.get("currency", "EUR")
292 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
293 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
294 if quote_balance is None:
297 quote_text = "%.2f %s" % (quote_balance, quote_currency)
300 def load_wallet(self, wallet):
303 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
304 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
305 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
307 self.tx_list = tx_list
310 def requires_settings(self):
315 out = BasePlugin.toggle(self)
316 self.win.update_status()
321 self.exchanger.stop()
323 def history_tab_update(self):
324 if self.config.get('history_rates', 'unchecked') == "checked":
325 tx_list = self.tx_list
327 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
328 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
330 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
334 self.gui.main_window.is_edit = True
335 self.gui.main_window.history_list.setColumnCount(6)
336 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
337 root = self.gui.main_window.history_list.invisibleRootItem()
338 childcount = root.childCount()
339 for i in range(childcount):
342 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
344 newtx = self.wallet.get_tx_history()
345 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
347 tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
349 tx_time = int(tx_info['timestamp'])
350 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
351 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
353 item.setText(5, tx_USD_val)
354 if Decimal(tx_info['value']) < 0:
355 item.setForeground(5, QBrush(QColor("#BC1E1E")))
357 for i, width in enumerate(self.gui.main_window.column_widths['history']):
358 self.gui.main_window.history_list.setColumnWidth(i, width)
359 self.gui.main_window.history_list.setColumnWidth(4, 140)
360 self.gui.main_window.history_list.setColumnWidth(5, 120)
361 self.gui.main_window.is_edit = False
364 def settings_widget(self, window):
365 return EnterButton(_('Settings'), self.settings_dialog)
367 def settings_dialog(self):
369 layout = QGridLayout(d)
370 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
371 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
372 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
374 combo_ex = QComboBox()
375 hist_checkbox = QCheckBox()
376 hist_checkbox.setEnabled(False)
377 if self.config.get('history_rates', 'unchecked') == 'unchecked':
378 hist_checkbox.setChecked(False)
380 hist_checkbox.setChecked(True)
381 ok_button = QPushButton(_("OK"))
385 cur_request = str(self.currencies[x])
388 if cur_request != self.config.get('currency', "EUR"):
389 self.config.set_key('currency', cur_request, True)
390 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
391 hist_checkbox.setEnabled(True)
393 hist_checkbox.setChecked(False)
394 hist_checkbox.setEnabled(False)
395 self.win.update_status()
398 hist_checkbox.setChecked(False)
399 hist_checkbox.setEnabled(False)
402 cur_request = str(self.exchanges[x])
403 if cur_request != self.config.get('use_exchange', "Blockchain"):
404 self.config.set_key('use_exchange', cur_request, True)
407 self.exchanger.query_rates.set()
408 if cur_request == "CoinDesk":
409 if self.config.get('currency', "EUR") == "USD":
410 hist_checkbox.setEnabled(True)
415 set_currencies(combo)
416 self.win.update_status()
418 def on_change_hist(checked):
420 self.config.set_key('history_rates', 'checked')
421 self.history_tab_update()
423 self.config.set_key('history_rates', 'unchecked')
424 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
425 self.gui.main_window.history_list.setColumnCount(5)
426 for i,width in enumerate(self.gui.main_window.column_widths['history']):
427 self.gui.main_window.history_list.setColumnWidth(i, width)
429 def set_hist_check(hist_checkbox):
430 if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
431 hist_checkbox.setEnabled(True)
433 hist_checkbox.setEnabled(False)
435 def set_currencies(combo):
436 current_currency = self.config.get('currency', "EUR")
441 combo.addItems(self.currencies)
443 index = self.currencies.index(current_currency)
446 combo.setCurrentIndex(index)
448 def set_exchanges(combo_ex):
453 combo_ex.addItems(self.exchanges)
455 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
458 combo_ex.setCurrentIndex(index)
463 set_exchanges(combo_ex)
464 set_currencies(combo)
465 set_hist_check(hist_checkbox)
466 combo.currentIndexChanged.connect(on_change)
467 combo_ex.currentIndexChanged.connect(on_change_ex)
468 hist_checkbox.stateChanged.connect(on_change_hist)
469 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
470 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
471 ok_button.clicked.connect(lambda: ok_clicked())
472 layout.addWidget(combo,1,1)
473 layout.addWidget(combo_ex,0,1)
474 layout.addWidget(hist_checkbox,2,1)
475 layout.addWidget(ok_button,3,1)