electrum-bitcoinprivate/plugins/exchange_rate.py

533 lines
20 KiB
Python
Raw Normal View History

2013-09-23 07:14:28 -07:00
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import datetime
2015-04-27 21:28:20 -07:00
import requests
2013-09-23 07:14:28 -07:00
import threading
import time
2013-09-23 07:14:28 -07:00
from decimal import Decimal
2015-02-27 14:10:45 -08:00
from electrum.bitcoin import COIN
2014-08-31 02:42:40 -07:00
from electrum.plugins import BasePlugin, hook
2013-09-23 07:14:28 -07:00
from electrum.i18n import _
from electrum.util import ThreadJob
2013-09-24 01:06:03 -07:00
from electrum_gui.qt.util import *
from electrum_gui.qt.amountedit import AmountEdit
2013-09-23 07:14:28 -07:00
EXCHANGES = ["BitcoinAverage",
"BitcoinVenezuela",
"BTCParalelo",
2014-03-31 12:02:21 -07:00
"Bitcurex",
"Bitmarket",
"BitPay",
"Blockchain",
"BTCChina",
"CaVirtEx",
"Coinbase",
"CoinDesk",
"itBit",
"LocalBitcoins",
"Winkdex"]
EXCH_SUPPORT_HIST = [("CoinDesk", "USD"),
("Winkdex", "USD"),
("BitcoinVenezuela", "ARS"),
("BitcoinVenezuela", "VEF")]
class Exchanger(ThreadJob):
2013-09-23 07:14:28 -07:00
def __init__(self, parent):
self.parent = parent
self.quote_currencies = None
self.timeout = 0
2013-09-23 07:14:28 -07:00
def get_json(self, site, get_string):
2015-04-27 21:28:20 -07:00
resp = requests.request('GET', 'https://' + site + get_string, headers={"User-Agent":"Electrum"})
return resp.json()
2013-09-23 07:14:28 -07:00
def exchange(self, btc_amount, quote_currency):
if self.quote_currencies is None:
return None
quote_currencies = self.quote_currencies.copy()
2013-09-23 07:14:28 -07:00
if quote_currency not in quote_currencies:
return None
2015-04-27 19:50:41 -07:00
return btc_amount * Decimal(str(quote_currencies[quote_currency]))
2013-09-23 07:14:28 -07:00
def update_rate(self):
update_rates = {
"BitcoinAverage": self.update_ba,
"BitcoinVenezuela": self.update_bv,
"BTCParalelo": self.update_bpl,
2014-03-31 12:02:21 -07:00
"Bitcurex": self.update_bx,
"Bitmarket": self.update_bm,
"BitPay": self.update_bp,
"Blockchain": self.update_bc,
"BTCChina": self.update_CNY,
"CaVirtEx": self.update_cv,
"CoinDesk": self.update_cd,
"Coinbase": self.update_cb,
"itBit": self.update_ib,
"LocalBitcoins": self.update_lb,
"Winkdex": self.update_wd,
}
try:
rates = update_rates[self.parent.exchange]()
except Exception as e:
self.parent.print_error(e)
rates = {}
self.quote_currencies = rates
self.parent.set_currencies(rates)
self.parent.refresh_fields()
2013-09-23 07:14:28 -07:00
def run(self):
if self.timeout <= time.time():
self.update_rate()
self.timeout = time.time() + 150
def update_cd(self):
resp_currencies = self.get_json('api.coindesk.com', "/v1/bpi/supported-currencies.json")
quote_currencies = {}
for cur in resp_currencies:
quote_currencies[str(cur["currency"])] = 0.0
current_cur = self.parent.config.get("currency", "EUR")
if current_cur in quote_currencies:
resp_rate = self.get_json('api.coindesk.com', "/v1/bpi/currentprice/" + str(current_cur) + ".json")
2015-04-27 19:50:41 -07:00
quote_currencies[str(current_cur)] = Decimal(str(resp_rate["bpi"][str(current_cur)]["rate_float"]))
return quote_currencies
def update_ib(self):
available_currencies = ["USD", "EUR", "SGD"]
quote_currencies = {}
for cur in available_currencies:
quote_currencies[cur] = 0.0
current_cur = self.parent.config.get("currency", "EUR")
if current_cur in available_currencies:
resp_rate = self.get_json('api.itbit.com', "/v1/markets/XBT" + str(current_cur) + "/ticker")
2015-04-27 19:50:41 -07:00
quote_currencies[str(current_cur)] = Decimal(str(resp_rate["lastPrice"]))
return quote_currencies
def update_wd(self):
winkresp = self.get_json('winkdex.com', "/api/v0/price")
2015-04-27 19:50:41 -07:00
return {"USD": Decimal(str(winkresp["price"]))/Decimal("100.0")}
def update_cv(self):
jsonresp = self.get_json('www.cavirtex.com', "/api/CAD/ticker.json")
cadprice = jsonresp["last"]
2015-04-27 19:50:41 -07:00
return {"CAD": Decimal(str(cadprice))}
2014-03-31 12:02:21 -07:00
def update_bm(self):
jsonresp = self.get_json('www.bitmarket.pl', "/json/BTCPLN/ticker.json")
2014-03-31 12:02:21 -07:00
pln_price = jsonresp["last"]
2015-04-27 19:50:41 -07:00
return {"PLN": Decimal(str(pln_price))}
2014-03-31 12:02:21 -07:00
def update_bx(self):
jsonresp = self.get_json('pln.bitcurex.com', "/data/ticker.json")
2014-03-31 12:02:21 -07:00
pln_price = jsonresp["last"]
2015-04-27 19:50:41 -07:00
return {"PLN": Decimal(str(pln_price))}
2014-03-31 12:02:21 -07:00
def update_CNY(self):
jsonresp = self.get_json('data.btcchina.com', "/data/ticker")
cnyprice = jsonresp["ticker"]["last"]
2015-04-27 19:50:41 -07:00
return {"CNY": Decimal(str(cnyprice))}
def update_bp(self):
jsonresp = self.get_json('bitpay.com', "/api/rates")
2015-04-27 19:50:41 -07:00
return dict([(str(r["code"]), Decimal(r["rate"])) for r in jsonresp])
def update_cb(self):
jsonresp = self.get_json('coinbase.com', "/api/v1/currencies/exchange_rates")
2015-04-27 19:42:25 -07:00
return dict([(r[7:].upper(), Decimal(str(jsonresp[r]))) for r in jsonresp if r.startswith("btc_to_")])
def update_bc(self):
jsonresp = self.get_json('blockchain.info', "/ticker")
2015-04-27 19:42:25 -07:00
return dict([(r, Decimal(str(jsonresp[r]["15m"]))) for r in jsonresp])
def update_lb(self):
jsonresp = self.get_json('localbitcoins.com', "/bitcoinaverage/ticker-all-currencies/")
2015-04-27 19:42:25 -07:00
return dict([(r, Decimal(jsonresp[r]["rates"]["last"])) for r in jsonresp])
def update_bv(self):
jsonresp = self.get_json('api.bitcoinvenezuela.com', "/")
2015-04-27 19:24:10 -07:00
return dict([(r, Decimal(jsonresp["BTC"][r])) for r in jsonresp["BTC"]])
def update_bpl(self):
jsonresp = self.get_json('btcparalelo.com', "/api/price")
2015-04-27 19:24:10 -07:00
return {"VEF": Decimal(jsonresp["price"])}
def update_ba(self):
jsonresp = self.get_json('api.bitcoinaverage.com', "/ticker/global/all")
2015-04-27 19:42:25 -07:00
return dict([(r, Decimal(jsonresp[r]["last"])) for r in jsonresp if not r == "timestamp"])
2013-09-23 07:14:28 -07:00
class Plugin(BasePlugin):
2013-10-08 02:38:40 -07:00
def __init__(self,a,b):
BasePlugin.__init__(self,a,b)
self.exchange = self.config.get('use_exchange', "Blockchain")
self.currencies = [self.fiat_unit()]
2015-05-23 01:38:19 -07:00
# Do price discovery
self.exchanger = Exchanger(self)
self.win = None
2015-08-23 10:22:52 -07:00
self.resp_hist = {}
self.fields = {}
self.network = None
@hook
def set_network(self, network):
if self.network:
self.network.remove_job(self.exchanger)
self.network = network
if network:
network.add_job(self.exchanger)
2013-10-08 02:38:40 -07:00
2014-08-31 02:42:40 -07:00
@hook
def init_qt(self, gui):
self.gui = gui
2013-09-23 07:14:28 -07:00
self.win = self.gui.main_window
2013-10-08 02:38:40 -07:00
self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
self.btc_rate = Decimal("0.0")
2014-09-19 04:36:30 -07:00
self.tx_list = {}
2015-05-23 01:38:19 -07:00
self.gui.exchanger = self.exchanger #
self.add_send_edit()
self.add_receive_edit()
self.win.update_status()
def close(self):
2015-05-23 01:38:19 -07:00
BasePlugin.close(self)
self.set_network(None)
self.exchanger = None
2015-05-23 01:38:19 -07:00
self.gui.exchanger = None
self.send_fiat_e.hide()
self.receive_fiat_e.hide()
self.win.update_status()
2013-09-23 07:14:28 -07:00
def set_currencies(self, currency_options):
self.currencies = sorted(currency_options)
2015-05-23 01:38:19 -07:00
if self.win:
self.win.emit(SIGNAL("refresh_currencies()"))
self.win.emit(SIGNAL("refresh_currencies_combo()"))
2014-08-31 02:42:40 -07:00
@hook
def get_fiat_balance_text(self, btc_balance, r):
# return balance as: 1.23 USD
r[0] = self.create_fiat_balance_text(Decimal(btc_balance) / COIN)
def get_fiat_price_text(self, r):
# return BTC price as: 123.45 USD
r[0] = self.create_fiat_balance_text(1)
quote = r[0]
if quote:
r[0] = "%s"%quote
2014-08-31 02:42:40 -07:00
@hook
def get_fiat_status_text(self, btc_balance, r2):
# return status as: (1.23 USD) 1 BTC~123.45 USD
text = ""
r = {}
self.get_fiat_price_text(r)
quote = r.get(0)
if quote:
price_text = "1 BTC~%s"%quote
fiat_currency = quote[-3:]
btc_price = self.btc_rate
fiat_balance = Decimal(btc_price) * Decimal(btc_balance) / COIN
balance_text = "(%.2f %s)" % (fiat_balance,fiat_currency)
text = " " + balance_text + " " + price_text + " "
r2[0] = text
2013-09-23 07:14:28 -07:00
def create_fiat_balance_text(self, btc_balance):
quote_currency = self.fiat_unit()
cur_rate = self.exchanger.exchange(Decimal("1.0"), quote_currency)
2014-03-05 13:03:56 -08:00
if cur_rate is None:
2013-09-23 07:14:28 -07:00
quote_text = ""
else:
2014-03-05 13:03:56 -08:00
quote_balance = btc_balance * Decimal(cur_rate)
self.btc_rate = cur_rate
quote_text = "%.2f %s" % (quote_balance, quote_currency)
2013-09-23 07:14:28 -07:00
return quote_text
2014-08-31 02:42:40 -07:00
@hook
def load_wallet(self, wallet, window):
tx_list = {}
for item in self.wallet.get_history(self.wallet.storage.get("current_account", None)):
2015-03-30 03:58:52 -07:00
tx_hash, conf, value, timestamp, balance = item
tx_list[tx_hash] = {'value': value, 'timestamp': timestamp }
self.tx_list = tx_list
self.set_network(wallet.network)
t = threading.Thread(target=self.request_history_rates, args=())
t.setDaemon(True)
t.start()
2013-09-23 07:14:28 -07:00
def requires_settings(self):
return True
2014-09-19 04:36:30 -07:00
def request_history_rates(self):
if self.config.get('history_rates') != "checked":
return
if not self.tx_list:
return
try:
mintimestr = datetime.datetime.fromtimestamp(int(min(self.tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
except Exception:
return
maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
if self.exchange == "CoinDesk":
try:
2014-09-19 04:36:30 -07:00
self.resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
except Exception:
return
elif self.exchange == "Winkdex":
try:
2014-09-19 04:36:30 -07:00
self.resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results']
except Exception:
return
elif self.exchange == "BitcoinVenezuela":
2014-09-19 04:36:30 -07:00
cur_currency = self.fiat_unit()
if cur_currency == "VEF":
try:
2014-09-19 04:36:30 -07:00
self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
except Exception:
return
2014-09-19 04:36:30 -07:00
elif cur_currency == "ARS":
try:
2014-09-19 04:36:30 -07:00
self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
except Exception:
return
2014-09-19 04:36:30 -07:00
else:
return
self.win.need_update.set()
@hook
def history_tab_update(self):
if self.config.get('history_rates') != "checked":
return
if not self.resp_hist:
return
if not self.wallet:
return
2014-09-19 04:48:49 -07:00
self.win.is_edit = True
2015-08-23 10:22:52 -07:00
self.win.history_list.setColumnCount(7)
self.win.history_list.setHeaderLabels( [ '', '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
2014-09-19 04:48:49 -07:00
root = self.win.history_list.invisibleRootItem()
2014-09-19 04:36:30 -07:00
childcount = root.childCount()
for i in range(childcount):
item = root.child(i)
try:
tx_info = self.tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
except Exception:
2015-05-02 02:08:35 -07:00
newtx = self.wallet.get_history()
2015-05-02 02:21:19 -07:00
v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][2]
tx_info = {'timestamp':int(time.time()), 'value': v}
2014-09-19 04:36:30 -07:00
pass
tx_time = int(tx_info['timestamp'])
tx_value = Decimal(str(tx_info['value'])) / COIN
if self.exchange == "CoinDesk":
2014-09-19 04:36:30 -07:00
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try:
tx_fiat_val = "%.2f %s" % (tx_value * Decimal(self.resp_hist['bpi'][tx_time_str]), "USD")
2014-09-19 04:36:30 -07:00
except KeyError:
tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/COIN , "USD")
elif self.exchange == "Winkdex":
2014-09-19 04:36:30 -07:00
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
try:
tx_rate = self.resp_hist[[x['timestamp'] for x in self.resp_hist].index(tx_time_str)]['price']
tx_fiat_val = "%.2f %s" % (tx_value * Decimal(tx_rate)/Decimal("100.0"), "USD")
2014-09-19 04:36:30 -07:00
except ValueError:
tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/COIN , "USD")
2014-09-19 04:36:30 -07:00
except KeyError:
tx_fiat_val = _("No data")
elif self.exchange == "BitcoinVenezuela":
2014-09-19 04:36:30 -07:00
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try:
num = self.resp_hist[tx_time_str].replace(',','')
tx_fiat_val = "%.2f %s" % (tx_value * Decimal(num), self.fiat_unit())
2014-09-19 04:36:30 -07:00
except KeyError:
tx_fiat_val = _("No data")
2014-09-19 04:36:30 -07:00
tx_fiat_val = " "*(12-len(tx_fiat_val)) + tx_fiat_val
2015-08-23 10:22:52 -07:00
item.setText(6, tx_fiat_val)
item.setFont(6, QFont(MONOSPACE_FONT))
2014-09-19 04:36:30 -07:00
if Decimal(str(tx_info['value'])) < 0:
2015-08-23 10:22:52 -07:00
item.setForeground(6, QBrush(QColor("#BC1E1E")))
2014-09-19 04:36:30 -07:00
2015-08-23 10:22:52 -07:00
self.win.history_list.setColumnWidth(6, 120)
2014-09-19 04:48:49 -07:00
self.win.is_edit = False
2013-10-08 02:38:40 -07:00
def settings_widget(self, window):
return EnterButton(_('Settings'), self.settings_dialog)
def settings_dialog(self):
d = QDialog()
d.setWindowTitle("Settings")
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
layout.addWidget(QLabel(_('Currency: ')), 1, 0)
layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
2013-10-08 02:38:40 -07:00
combo = QComboBox()
combo_ex = QComboBox()
combo_ex.addItems(EXCHANGES)
combo_ex.setCurrentIndex(combo_ex.findText(self.exchange))
hist_checkbox = QCheckBox()
hist_checkbox.setEnabled(False)
hist_checkbox.setChecked(self.config.get('history_rates', 'unchecked') != 'unchecked')
ok_button = QPushButton(_("OK"))
2013-09-23 07:14:28 -07:00
2013-10-08 02:38:40 -07:00
def on_change(x):
try:
cur_request = str(self.currencies[x])
except Exception:
return
if cur_request != self.fiat_unit():
2013-09-23 07:14:28 -07:00
self.config.set_key('currency', cur_request, True)
if (self.exchange, cur_request) in EXCH_SUPPORT_HIST:
hist_checkbox.setEnabled(True)
else:
disable_check()
2013-10-08 02:38:40 -07:00
self.win.update_status()
try:
self.fiat_button
except:
pass
else:
self.fiat_button.setText(cur_request)
2013-10-08 02:38:40 -07:00
def disable_check():
hist_checkbox.setChecked(False)
hist_checkbox.setEnabled(False)
def on_change_ex(exchange):
exchange = str(exchange)
if exchange != self.exchange:
self.exchange = exchange
self.config.set_key('use_exchange', exchange, True)
self.currencies = []
combo.clear()
self.timeout = 0
cur_currency = self.fiat_unit()
if (exchange, cur_currency) in EXCH_SUPPORT_HIST:
hist_checkbox.setEnabled(True)
else:
disable_check()
set_currencies(combo)
self.win.update_status()
def on_change_hist(checked):
if checked:
self.config.set_key('history_rates', 'checked')
2014-09-19 04:36:30 -07:00
self.request_history_rates()
else:
self.config.set_key('history_rates', 'unchecked')
2015-08-23 10:22:52 -07:00
self.win.history_list.setHeaderLabels( [ '', '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
self.win.history_list.setColumnCount(6)
def set_hist_check(hist_checkbox):
hist_checkbox.setEnabled(self.exchange in ["CoinDesk", "Winkdex", "BitcoinVenezuela"])
2013-10-08 02:38:40 -07:00
def set_currencies(combo):
try:
combo.blockSignals(True)
current_currency = self.fiat_unit()
2013-10-08 02:38:40 -07:00
combo.clear()
2013-11-10 12:30:57 -08:00
except Exception:
2013-10-08 02:38:40 -07:00
return
combo.addItems(self.currencies)
try:
index = self.currencies.index(current_currency)
2013-11-10 12:30:57 -08:00
except Exception:
2013-10-08 02:38:40 -07:00
index = 0
combo.blockSignals(False)
2013-10-08 02:38:40 -07:00
combo.setCurrentIndex(index)
def ok_clicked():
if self.exchange in ["CoinDesk", "itBit"]:
self.timeout = 0
d.accept();
2013-10-08 02:38:40 -07:00
set_currencies(combo)
set_hist_check(hist_checkbox)
2013-10-08 02:38:40 -07:00
combo.currentIndexChanged.connect(on_change)
combo_ex.currentIndexChanged.connect(on_change_ex)
hist_checkbox.stateChanged.connect(on_change_hist)
combo.connect(self.win, SIGNAL('refresh_currencies_combo()'), lambda: set_currencies(combo))
combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'), lambda: set_exchanges(combo_ex))
ok_button.clicked.connect(lambda: ok_clicked())
layout.addWidget(combo,1,1)
layout.addWidget(combo_ex,0,1)
layout.addWidget(hist_checkbox,2,1)
layout.addWidget(ok_button,3,1)
if d.exec_():
return True
else:
return False
2013-09-23 07:14:28 -07:00
def fiat_unit(self):
return self.config.get("currency", "EUR")
def refresh_fields(self):
'''Update the display at the new rate'''
for field in self.fields.values():
field.textEdited.emit(field.text())
2015-03-14 11:47:57 -07:00
def add_send_edit(self):
self.send_fiat_e = AmountEdit(self.fiat_unit)
2015-03-14 11:47:57 -07:00
btc_e = self.win.amount_e
fee_e = self.win.fee_e
self.connect_fields(btc_e, self.send_fiat_e, fee_e)
self.win.send_grid.addWidget(self.send_fiat_e, 4, 3, Qt.AlignHCenter)
btc_e.frozen.connect(lambda: self.send_fiat_e.setFrozen(btc_e.isReadOnly()))
2015-03-14 11:47:57 -07:00
def add_receive_edit(self):
self.receive_fiat_e = AmountEdit(self.fiat_unit)
2015-03-14 11:47:57 -07:00
btc_e = self.win.receive_amount_e
self.connect_fields(btc_e, self.receive_fiat_e, None)
self.win.receive_grid.addWidget(self.receive_fiat_e, 2, 3, Qt.AlignHCenter)
2015-03-14 11:47:57 -07:00
def connect_fields(self, btc_e, fiat_e, fee_e):
def fiat_changed():
fiat_e.setStyleSheet(BLACK_FG)
self.fields[(fiat_e, btc_e)] = fiat_e
try:
2015-03-14 11:47:57 -07:00
fiat_amount = Decimal(str(fiat_e.text()))
except:
2015-03-14 11:47:57 -07:00
btc_e.setText("")
if fee_e: fee_e.setText("")
return
exchange_rate = self.exchanger.exchange(Decimal("1.0"), self.fiat_unit())
if exchange_rate is not None:
btc_amount = fiat_amount/exchange_rate
btc_e.setAmount(int(btc_amount*Decimal(COIN)))
btc_e.setStyleSheet(BLUE_FG)
if fee_e: self.win.update_fee()
2015-03-14 11:47:57 -07:00
fiat_e.textEdited.connect(fiat_changed)
def btc_changed():
btc_e.setStyleSheet(BLACK_FG)
self.fields[(fiat_e, btc_e)] = btc_e
if self.exchanger is None:
return
2015-03-14 11:47:57 -07:00
btc_amount = btc_e.get_amount()
if btc_amount is None:
2015-03-14 11:47:57 -07:00
fiat_e.setText("")
return
fiat_amount = self.exchanger.exchange(Decimal(btc_amount)/Decimal(COIN), self.fiat_unit())
if fiat_amount is not None:
2015-03-14 11:47:57 -07:00
pos = fiat_e.cursorPosition()
fiat_e.setText("%.2f"%fiat_amount)
fiat_e.setCursorPosition(pos)
fiat_e.setStyleSheet(BLUE_FG)
2015-03-14 11:47:57 -07:00
btc_e.textEdited.connect(btc_changed)
self.fields[(fiat_e, btc_e)] = btc_e
@hook
def do_clear(self):
self.send_fiat_e.setText('')