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)
276 self.btc_rate = Decimal(0.0)
278 self.exchanger = Exchanger(self)
279 self.exchanger.start()
280 self.gui.exchanger = self.exchanger #
282 def set_currencies(self, currency_options):
283 self.currencies = sorted(currency_options)
284 self.win.emit(SIGNAL("refresh_currencies()"))
285 self.win.emit(SIGNAL("refresh_currencies_combo()"))
288 def set_quote_text(self, btc_balance, r):
289 r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
291 def create_quote_text(self, btc_balance):
292 quote_currency = self.config.get("currency", "EUR")
293 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
294 cur_rate = self.exchanger.exchange(Decimal(1.0), quote_currency)
298 quote_balance = btc_balance * Decimal(cur_rate)
299 self.btc_rate = cur_rate
300 quote_text = "%.2f %s" % (quote_balance, quote_currency)
303 def load_wallet(self, wallet):
306 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
307 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
308 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
310 self.tx_list = tx_list
313 def requires_settings(self):
318 out = BasePlugin.toggle(self)
319 self.win.update_status()
324 self.exchanger.stop()
326 def history_tab_update(self):
327 if self.config.get('history_rates', 'unchecked') == "checked":
328 tx_list = self.tx_list
330 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
331 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
333 resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
337 self.gui.main_window.is_edit = True
338 self.gui.main_window.history_list.setColumnCount(6)
339 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
340 root = self.gui.main_window.history_list.invisibleRootItem()
341 childcount = root.childCount()
342 for i in range(childcount):
345 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
347 newtx = self.wallet.get_tx_history()
348 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
350 tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
352 tx_time = int(tx_info['timestamp'])
353 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
355 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
357 tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
359 item.setText(5, tx_USD_val)
360 if Decimal(tx_info['value']) < 0:
361 item.setForeground(5, QBrush(QColor("#BC1E1E")))
363 for i, width in enumerate(self.gui.main_window.column_widths['history']):
364 self.gui.main_window.history_list.setColumnWidth(i, width)
365 self.gui.main_window.history_list.setColumnWidth(4, 140)
366 self.gui.main_window.history_list.setColumnWidth(5, 120)
367 self.gui.main_window.is_edit = False
370 def settings_widget(self, window):
371 return EnterButton(_('Settings'), self.settings_dialog)
373 def settings_dialog(self):
375 layout = QGridLayout(d)
376 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
377 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
378 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
380 combo_ex = QComboBox()
381 hist_checkbox = QCheckBox()
382 hist_checkbox.setEnabled(False)
383 if self.config.get('history_rates', 'unchecked') == 'unchecked':
384 hist_checkbox.setChecked(False)
386 hist_checkbox.setChecked(True)
387 ok_button = QPushButton(_("OK"))
391 cur_request = str(self.currencies[x])
394 if cur_request != self.config.get('currency', "EUR"):
395 self.config.set_key('currency', cur_request, True)
396 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
397 hist_checkbox.setEnabled(True)
399 hist_checkbox.setChecked(False)
400 hist_checkbox.setEnabled(False)
401 self.win.update_status()
404 hist_checkbox.setChecked(False)
405 hist_checkbox.setEnabled(False)
408 cur_request = str(self.exchanges[x])
409 if cur_request != self.config.get('use_exchange', "Blockchain"):
410 self.config.set_key('use_exchange', cur_request, True)
413 self.exchanger.query_rates.set()
414 if cur_request == "CoinDesk":
415 if self.config.get('currency', "EUR") == "USD":
416 hist_checkbox.setEnabled(True)
421 set_currencies(combo)
422 self.win.update_status()
424 def on_change_hist(checked):
426 self.config.set_key('history_rates', 'checked')
427 self.history_tab_update()
429 self.config.set_key('history_rates', 'unchecked')
430 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
431 self.gui.main_window.history_list.setColumnCount(5)
432 for i,width in enumerate(self.gui.main_window.column_widths['history']):
433 self.gui.main_window.history_list.setColumnWidth(i, width)
435 def set_hist_check(hist_checkbox):
436 if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
437 hist_checkbox.setEnabled(True)
439 hist_checkbox.setEnabled(False)
441 def set_currencies(combo):
442 current_currency = self.config.get('currency', "EUR")
447 combo.addItems(self.currencies)
449 index = self.currencies.index(current_currency)
452 combo.setCurrentIndex(index)
454 def set_exchanges(combo_ex):
459 combo_ex.addItems(self.exchanges)
461 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
464 combo_ex.setCurrentIndex(index)
469 set_exchanges(combo_ex)
470 set_currencies(combo)
471 set_hist_check(hist_checkbox)
472 combo.currentIndexChanged.connect(on_change)
473 combo_ex.currentIndexChanged.connect(on_change_ex)
474 hist_checkbox.stateChanged.connect(on_change_hist)
475 combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
476 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
477 ok_button.clicked.connect(lambda: ok_clicked())
478 layout.addWidget(combo,1,1)
479 layout.addWidget(combo_ex,0,1)
480 layout.addWidget(hist_checkbox,2,1)
481 layout.addWidget(ok_button,3,1)