Browse Source

request history rates asynchronously

283
ThomasV 11 years ago
parent
commit
6cd00eb36b
  1. 10
      gui/qt/main_window.py
  2. 9
      gui/qt/util.py
  3. 76
      plugins/exchange_rate.py

10
gui/qt/main_window.py

@ -49,19 +49,11 @@ from qrtextedit import QRTextEdit
from decimal import Decimal from decimal import Decimal
import platform
import httplib import httplib
import socket import socket
import webbrowser import webbrowser
import csv import csv
if platform.system() == 'Windows':
MONOSPACE_FONT = 'Lucida Console'
elif platform.system() == 'Darwin':
MONOSPACE_FONT = 'Monaco'
else:
MONOSPACE_FONT = 'monospace'
# status of payment requests # status of payment requests
@ -77,7 +69,7 @@ import re
from util import MyTreeWidget, HelpButton, EnterButton, line_dialog, text_dialog, ok_cancel_buttons, close_button, WaitingDialog from util import MyTreeWidget, HelpButton, EnterButton, line_dialog, text_dialog, ok_cancel_buttons, close_button, WaitingDialog
from util import filename_field, ok_cancel_buttons2, address_field from util import filename_field, ok_cancel_buttons2, address_field
from util import MONOSPACE_FONT
def format_status(x): def format_status(x):
if x == PR_UNPAID: if x == PR_UNPAID:

9
gui/qt/util.py

@ -6,6 +6,15 @@ import time
import traceback import traceback
import sys import sys
import threading import threading
import platform
if platform.system() == 'Windows':
MONOSPACE_FONT = 'Lucida Console'
elif platform.system() == 'Darwin':
MONOSPACE_FONT = 'Monaco'
else:
MONOSPACE_FONT = 'monospace'
class WaitingDialog(QThread): class WaitingDialog(QThread):
def __init__(self, parent, message, run_task, on_complete=None): def __init__(self, parent, message, run_task, on_complete=None):

76
plugins/exchange_rate.py

@ -347,6 +347,8 @@ class Plugin(BasePlugin):
self.win = self.gui.main_window self.win = self.gui.main_window
self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status) self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
self.btc_rate = Decimal("0.0") self.btc_rate = Decimal("0.0")
self.resp_hist = {}
self.tx_list = {}
if self.exchanger is None: if self.exchanger is None:
# Do price discovery # Do price discovery
self.exchanger = Exchanger(self) self.exchanger = Exchanger(self)
@ -416,52 +418,60 @@ class Plugin(BasePlugin):
tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance} tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
self.tx_list = tx_list self.tx_list = tx_list
self.cur_exchange = self.config.get('use_exchange', "Blockchain")
threading.Thread(target=self.request_history_rates, args=()).start()
def requires_settings(self): def requires_settings(self):
return True return True
@hook def request_history_rates(self):
def history_tab_update(self): if self.config.get('history_rates') != "checked":
if self.config.get('history_rates', 'unchecked') == "checked": return
cur_exchange = self.config.get('use_exchange', "Blockchain") if not self.tx_list:
try:
tx_list = self.tx_list
except Exception:
return return
try: try:
mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d') mintimestr = datetime.datetime.fromtimestamp(int(min(self.tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
except Exception: except Exception:
return return
maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d') maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
if cur_exchange == "CoinDesk": if self.cur_exchange == "CoinDesk":
try: try:
resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr) self.resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
except Exception: except Exception:
return return
elif cur_exchange == "Winkdex": elif self.cur_exchange == "Winkdex":
try: try:
resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results'] self.resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results']
except Exception: except Exception:
return return
elif cur_exchange == "BitcoinVenezuela": elif self.cur_exchange == "BitcoinVenezuela":
cur_currency = self.fiat_unit() cur_currency = self.fiat_unit()
if cur_currency == "VEF": if cur_currency == "VEF":
try: try:
resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC'] self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
except Exception: except Exception:
return return
elif cur_currency == "ARS": elif cur_currency == "ARS":
try: try:
resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC'] self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
except Exception: except Exception:
return return
else: else:
return 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
self.gui.main_window.is_edit = True self.gui.main_window.is_edit = True
self.gui.main_window.history_list.setColumnCount(6) self.gui.main_window.history_list.setColumnCount(6)
self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] ) self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
@ -470,41 +480,39 @@ class Plugin(BasePlugin):
for i in range(childcount): for i in range(childcount):
item = root.child(i) item = root.child(i)
try: try:
tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())] tx_info = self.tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
except Exception: except Exception:
newtx = self.wallet.get_tx_history() newtx = self.wallet.get_tx_history()
v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3] v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
tx_info = {'timestamp':int(time.time()), 'value': v } tx_info = {'timestamp':int(time.time()), 'value': v }
pass pass
tx_time = int(tx_info['timestamp']) tx_time = int(tx_info['timestamp'])
if cur_exchange == "CoinDesk": if self.cur_exchange == "CoinDesk":
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try: try:
tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD") tx_fiat_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(self.resp_hist['bpi'][tx_time_str]), "USD")
except KeyError: except KeyError:
tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD") tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
elif cur_exchange == "Winkdex": elif self.cur_exchange == "Winkdex":
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00" tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
try: try:
tx_rate = resp_hist[[x['timestamp'] for x in resp_hist].index(tx_time_str)]['price'] tx_rate = self.resp_hist[[x['timestamp'] for x in self.resp_hist].index(tx_time_str)]['price']
tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD") tx_fiat_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD")
except ValueError: except ValueError:
tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD") tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
except KeyError: except KeyError:
tx_USD_val = _("No data") tx_fiat_val = _("No data")
elif cur_exchange == "BitcoinVenezuela": elif self.cur_exchange == "BitcoinVenezuela":
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try: try:
num = resp_hist[tx_time_str].replace(',','') num = self.resp_hist[tx_time_str].replace(',','')
tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency) tx_fiat_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
except KeyError: except KeyError:
tx_BTCVEN_val = _("No data") tx_fiat_val = _("No data")
if cur_exchange in ["CoinDesk", "Winkdex"]: tx_fiat_val = " "*(12-len(tx_fiat_val)) + tx_fiat_val
item.setText(5, tx_USD_val) item.setText(5, tx_fiat_val)
elif cur_exchange == "BitcoinVenezuela": item.setFont(5, QFont(MONOSPACE_FONT))
item.setText(5, tx_BTCVEN_val)
if Decimal(str(tx_info['value'])) < 0: if Decimal(str(tx_info['value'])) < 0:
item.setForeground(5, QBrush(QColor("#BC1E1E"))) item.setForeground(5, QBrush(QColor("#BC1E1E")))
@ -574,7 +582,7 @@ class Plugin(BasePlugin):
def on_change_hist(checked): def on_change_hist(checked):
if checked: if checked:
self.config.set_key('history_rates', 'checked') self.config.set_key('history_rates', 'checked')
self.history_tab_update() self.request_history_rates()
else: else:
self.config.set_key('history_rates', 'unchecked') self.config.set_key('history_rates', 'unchecked')
self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] ) self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )

Loading…
Cancel
Save