1
0

request history rates asynchronously

This commit is contained in:
ThomasV
2014-09-19 13:36:30 +02:00
parent 692f49e7af
commit 6cd00eb36b
3 changed files with 101 additions and 92 deletions

View File

@@ -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:

View File

@@ -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):

View File

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