electrum-bitcoinprivate/lib/exchange_rate.py

60 lines
1.8 KiB
Python
Raw Normal View History

from PyQt4.QtCore import SIGNAL
2012-06-30 05:43:42 -07:00
import decimal
import httplib
import json
import threading
2012-06-30 05:43:42 -07:00
class Exchanger(threading.Thread):
2012-06-30 04:47:08 -07:00
def __init__(self, parent):
threading.Thread.__init__(self)
self.daemon = True
self.parent = parent
self.quote_currencies = None
self.lock = threading.Lock()
# Do price discovery
self.start()
2012-06-30 04:47:08 -07:00
def exchange(self, btc_amount, quote_currency):
with self.lock:
if self.quote_currencies is None:
return None
quote_currencies = self.quote_currencies.copy()
if quote_currency not in quote_currencies:
return None
return btc_amount * quote_currencies[quote_currency]
def run(self):
self.discovery()
2012-06-30 05:43:42 -07:00
def discovery(self):
try:
connection = httplib.HTTPConnection('blockchain.info')
connection.request("GET", "/ticker")
except:
return
2012-06-30 05:43:42 -07:00
response = connection.getresponse()
2012-08-22 19:50:21 -07:00
if response.reason == httplib.responses[httplib.NOT_FOUND]:
2012-06-30 05:43:42 -07:00
return
response = json.loads(response.read())
quote_currencies = {}
2012-06-30 05:43:42 -07:00
try:
for r in response:
quote_currencies[r] = self._lookup_rate(response, r)
with self.lock:
self.quote_currencies = quote_currencies
self.parent.emit(SIGNAL("refresh_balance()"))
2012-06-30 05:43:42 -07:00
except KeyError:
pass
2013-01-05 06:23:35 -08:00
def get_currencies(self):
return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
2012-06-30 04:47:08 -07:00
2012-08-22 20:11:38 -07:00
def _lookup_rate(self, response, quote_id):
2013-01-05 06:23:35 -08:00
return decimal.Decimal(str(response[str(quote_id)]["15m"]))
2012-06-30 04:47:08 -07:00
if __name__ == "__main__":
exch = Exchanger(("BRL", "CNY", "EUR", "GBP", "RUB", "USD"))
2012-06-30 04:47:08 -07:00
print exch.exchange(1, "EUR")