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 class Exchanger(threading.Thread):
18 def __init__(self, parent):
19 threading.Thread.__init__(self)
22 self.quote_currencies = None
23 self.lock = threading.Lock()
24 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
25 self.parent.exchanges = ["Blockchain", "Coinbase", "CoinDesk"]
26 self.parent.currencies = ["EUR","GBP","USD"]
27 self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
28 self.parent.win.emit(SIGNAL("refresh_currencies_combo()"))
29 self.is_running = False
31 def exchange(self, btc_amount, quote_currency):
33 if self.quote_currencies is None:
35 quote_currencies = self.quote_currencies.copy()
36 if quote_currency not in quote_currencies:
38 if self.use_exchange == "CoinDesk":
40 connection = httplib.HTTPSConnection('api.coindesk.com')
41 connection.request("GET", "/v1/bpi/currentprice/" + str(quote_currency) + ".json")
44 resp = connection.getresponse()
45 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
48 resp_rate = json.loads(resp.read())
51 return btc_amount * decimal.Decimal(str(resp_rate["bpi"][str(quote_currency)]["rate_float"]))
52 return btc_amount * decimal.Decimal(quote_currencies[quote_currency])
55 self.is_running = False
58 self.is_running = True
59 while self.is_running:
60 self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
61 if self.use_exchange == "Blockchain":
63 elif self.use_exchange == "CoinDesk":
65 elif self.use_exchange == "Coinbase":
72 connection = httplib.HTTPSConnection('api.coindesk.com')
73 connection.request("GET", "/v1/bpi/supported-currencies.json")
76 response = connection.getresponse()
77 if response.reason == httplib.responses[httplib.NOT_FOUND]:
80 resp_currencies = json.loads(response.read())
85 for cur in resp_currencies:
86 quote_currencies[str(cur["currency"])] = 0.0
88 self.quote_currencies = quote_currencies
89 self.parent.set_currencies(quote_currencies)
93 connection = httplib.HTTPSConnection('coinbase.com')
94 connection.request("GET", "/api/v1/currencies/exchange_rates")
97 response = connection.getresponse()
98 if response.reason == httplib.responses[httplib.NOT_FOUND]:
102 response = json.loads(response.read())
106 quote_currencies = {}
109 if r[:7] == "btc_to_":
110 quote_currencies[r[7:].upper()] = self._lookup_rate_cb(response, r)
112 self.quote_currencies = quote_currencies
115 self.parent.set_currencies(quote_currencies)
120 connection = httplib.HTTPSConnection('blockchain.info')
121 connection.request("GET", "/ticker")
124 response = connection.getresponse()
125 if response.reason == httplib.responses[httplib.NOT_FOUND]:
128 response = json.loads(response.read())
131 quote_currencies = {}
134 quote_currencies[r] = self._lookup_rate(response, r)
136 self.quote_currencies = quote_currencies
139 self.parent.set_currencies(quote_currencies)
140 # print "updating exchange rate", self.quote_currencies["USD"]
143 def get_currencies(self):
144 return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
146 def _lookup_rate(self, response, quote_id):
147 return decimal.Decimal(str(response[str(quote_id)]["15m"]))
148 def _lookup_rate_cb(self, response, quote_id):
149 return decimal.Decimal(str(response[str(quote_id)]))
153 class Plugin(BasePlugin):
156 return "Exchange rates"
158 def description(self):
159 return """exchange rates, retrieved from blockchain.info, CoinDesk, or Coinbase"""
162 def __init__(self,a,b):
163 BasePlugin.__init__(self,a,b)
164 self.currencies = [self.config.get('currency', "EUR")]
165 self.exchanges = [self.config.get('use_exchange', "Blockchain")]
168 self.win = self.gui.main_window
169 self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
171 self.exchanger = Exchanger(self)
172 self.exchanger.start()
173 self.gui.exchanger = self.exchanger #
175 def set_currencies(self, currency_options):
176 self.currencies = sorted(currency_options)
177 self.win.emit(SIGNAL("refresh_currencies()"))
178 self.win.emit(SIGNAL("refresh_currencies_combo()"))
181 def set_quote_text(self, btc_balance, r):
182 r[0] = self.create_quote_text(Decimal(btc_balance) / 100000000)
184 def create_quote_text(self, btc_balance):
185 quote_currency = self.config.get("currency", "EUR")
186 self.exchanger.use_exchange = self.config.get("use_exchange", "Blockchain")
187 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
188 if quote_balance is None:
191 quote_text = "%.2f %s" % (quote_balance, quote_currency)
194 def load_wallet(self, wallet):
197 for item in self.wallet.get_tx_history(self.wallet.storage.get("current_account", None)):
198 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
199 tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
201 self.tx_list = tx_list
204 def requires_settings(self):
209 out = BasePlugin.toggle(self)
210 self.win.update_status()
215 self.exchanger.stop()
217 def history_tab_update(self):
218 if self.config.get('history_rates', 'unchecked') == "checked":
219 tx_list = self.tx_list
221 mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
222 maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
224 connection = httplib.HTTPSConnection('api.coindesk.com')
225 connection.request("GET", "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
228 resp = connection.getresponse()
229 if resp.reason == httplib.responses[httplib.NOT_FOUND]:
232 resp_hist = json.loads(resp.read())
236 self.gui.main_window.is_edit = True
237 self.gui.main_window.history_list.setColumnCount(6)
238 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
239 root = self.gui.main_window.history_list.invisibleRootItem()
240 childcount = root.childCount()
241 for i in range(childcount):
244 tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
246 newtx = self.wallet.get_tx_history()
247 v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
249 tx_info = {'timestamp':int(datetime.datetime.now().strftime("%s")), 'value': v }
251 tx_time = int(tx_info['timestamp'])
252 tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
253 tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
256 item.setText(5, tx_USD_val)
258 for i, width in enumerate(self.gui.main_window.column_widths['history']):
259 self.gui.main_window.history_list.setColumnWidth(i, width)
260 self.gui.main_window.history_list.setColumnWidth(4, 140)
261 self.gui.main_window.history_list.setColumnWidth(5, 120)
262 self.gui.main_window.is_edit = False
265 def settings_widget(self, window):
266 return EnterButton(_('Settings'), self.settings_dialog)
268 def settings_dialog(self):
270 layout = QGridLayout(d)
271 layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
272 layout.addWidget(QLabel(_('Currency: ')), 1, 0)
273 layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
275 combo_ex = QComboBox()
276 hist_checkbox = QCheckBox()
277 hist_checkbox.setEnabled(False)
278 if self.config.get('history_rates', 'unchecked') == 'unchecked':
279 hist_checkbox.setChecked(False)
281 hist_checkbox.setChecked(True)
282 ok_button = QPushButton(_("OK"))
285 cur_request = str(self.currencies[x])
286 if cur_request != self.config.get('currency', "EUR"):
287 self.config.set_key('currency', cur_request, True)
288 if cur_request == "USD" and self.config.get('use_exchange', "Blockchain") == "CoinDesk":
289 hist_checkbox.setEnabled(True)
291 hist_checkbox.setChecked(False)
292 hist_checkbox.setEnabled(False)
293 self.win.update_status()
296 cur_request = str(self.exchanges[x])
297 if cur_request != self.config.get('use_exchange', "Blockchain"):
298 self.config.set_key('use_exchange', cur_request, True)
299 if cur_request == "Blockchain":
300 self.exchanger.update_bc()
301 hist_checkbox.setChecked(False)
302 hist_checkbox.setEnabled(False)
303 elif cur_request == "CoinDesk":
304 self.exchanger.update_cd()
305 if self.config.get('currency', "EUR") == "USD":
306 hist_checkbox.setEnabled(True)
308 hist_checkbox.setChecked(False)
309 hist_checkbox.setEnabled(False)
310 elif cur_request == "Coinbase":
311 self.exchanger.update_cb()
312 hist_checkbox.setChecked(False)
313 hist_checkbox.setEnabled(False)
314 set_currencies(combo)
315 self.win.update_status()
317 def on_change_hist(checked):
319 self.config.set_key('history_rates', 'checked')
320 self.history_tab_update()
322 self.config.set_key('history_rates', 'unchecked')
323 self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
324 self.gui.main_window.history_list.setColumnCount(5)
325 for i,width in enumerate(self.gui.main_window.column_widths['history']):
326 self.gui.main_window.history_list.setColumnWidth(i, width)
328 def set_hist_check(hist_checkbox):
329 if self.config.get('use_exchange', "Blockchain") == "CoinDesk":
330 hist_checkbox.setEnabled(True)
332 hist_checkbox.setEnabled(False)
334 def set_currencies(combo):
335 current_currency = self.config.get('currency', "EUR")
340 combo.addItems(self.currencies)
342 index = self.currencies.index(current_currency)
345 combo.setCurrentIndex(index)
347 def set_exchanges(combo_ex):
352 combo_ex.addItems(self.exchanges)
354 index = self.exchanges.index(self.config.get('use_exchange', "Blockchain"))
357 combo_ex.setCurrentIndex(index)
362 set_exchanges(combo_ex)
363 set_currencies(combo)
364 set_hist_check(hist_checkbox)
365 combo.currentIndexChanged.connect(on_change)
366 combo_ex.currentIndexChanged.connect(on_change_ex)
367 hist_checkbox.stateChanged.connect(on_change_hist)
368 combo.connect(d, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
369 combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
370 ok_button.clicked.connect(lambda: ok_clicked())
371 layout.addWidget(combo,1,1)
372 layout.addWidget(combo_ex,0,1)
373 layout.addWidget(hist_checkbox,2,1)
374 layout.addWidget(ok_button,3,1)