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. 162
      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):

162
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,103 +418,109 @@ 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:
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.cur_exchange == "CoinDesk":
try: try:
tx_list = self.tx_list 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 self.cur_exchange == "Winkdex":
try: try:
mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d') self.resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results']
except Exception: except Exception:
return return
maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d') elif self.cur_exchange == "BitcoinVenezuela":
cur_currency = self.fiat_unit()
if cur_exchange == "CoinDesk": if cur_currency == "VEF":
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.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
except Exception: except Exception:
return return
elif cur_exchange == "Winkdex": elif cur_currency == "ARS":
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('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
except Exception: except Exception:
return return
elif cur_exchange == "BitcoinVenezuela": else:
cur_currency = self.fiat_unit() return
if cur_currency == "VEF":
try: self.win.need_update.set()
resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
except Exception: @hook
return def history_tab_update(self):
elif cur_currency == "ARS": if self.config.get('history_rates') != "checked":
try: return
resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC'] if not self.resp_hist:
except Exception: return
return
else:
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')] )
root = self.gui.main_window.history_list.invisibleRootItem() root = self.gui.main_window.history_list.invisibleRootItem()
childcount = root.childCount() childcount = root.childCount()
for i in range(childcount): for i in range(childcount):
item = root.child(i) item = root.child(i)
try:
tx_info = self.tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
except Exception:
newtx = self.wallet.get_tx_history()
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 }
pass
tx_time = int(tx_info['timestamp'])
if self.cur_exchange == "CoinDesk":
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try: try:
tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())] tx_fiat_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(self.resp_hist['bpi'][tx_time_str]), "USD")
except Exception: except KeyError:
newtx = self.wallet.get_tx_history() tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3] elif self.cur_exchange == "Winkdex":
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" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD")
except ValueError:
tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
except KeyError:
tx_fiat_val = _("No data")
elif self.cur_exchange == "BitcoinVenezuela":
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" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
except KeyError:
tx_fiat_val = _("No data")
tx_info = {'timestamp':int(time.time()), 'value': v } tx_fiat_val = " "*(12-len(tx_fiat_val)) + tx_fiat_val
pass item.setText(5, tx_fiat_val)
tx_time = int(tx_info['timestamp']) item.setFont(5, QFont(MONOSPACE_FONT))
if cur_exchange == "CoinDesk": if Decimal(str(tx_info['value'])) < 0:
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') item.setForeground(5, QBrush(QColor("#BC1E1E")))
try:
tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD") for i, width in enumerate(self.gui.main_window.column_widths['history']):
except KeyError: self.gui.main_window.history_list.setColumnWidth(i, width)
tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD") self.gui.main_window.history_list.setColumnWidth(4, 140)
elif cur_exchange == "Winkdex": self.gui.main_window.history_list.setColumnWidth(5, 120)
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00" self.gui.main_window.is_edit = False
try:
tx_rate = resp_hist[[x['timestamp'] for x in resp_hist].index(tx_time_str)]['price']
tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD")
except ValueError:
tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
except KeyError:
tx_USD_val = _("No data")
elif cur_exchange == "BitcoinVenezuela":
tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
try:
num = resp_hist[tx_time_str].replace(',','')
tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
except KeyError:
tx_BTCVEN_val = _("No data")
if cur_exchange in ["CoinDesk", "Winkdex"]:
item.setText(5, tx_USD_val)
elif cur_exchange == "BitcoinVenezuela":
item.setText(5, tx_BTCVEN_val)
if Decimal(str(tx_info['value'])) < 0:
item.setForeground(5, QBrush(QColor("#BC1E1E")))
for i, width in enumerate(self.gui.main_window.column_widths['history']):
self.gui.main_window.history_list.setColumnWidth(i, width)
self.gui.main_window.history_list.setColumnWidth(4, 140)
self.gui.main_window.history_list.setColumnWidth(5, 120)
self.gui.main_window.is_edit = False
def settings_widget(self, window): def settings_widget(self, window):
@ -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