Fixing wineprefix directory cleanup
[electrum-nvc.git] / lib / exchange_rate.py
1 from PyQt4.QtCore import SIGNAL
2 import decimal
3 import httplib
4 import json
5 import threading
6
7 class Exchanger(threading.Thread):
8
9     def __init__(self, parent):
10         threading.Thread.__init__(self)
11         self.daemon = True
12         self.parent = parent
13         self.quote_currencies = None
14         self.lock = threading.Lock()
15         # Do price discovery
16         self.start()
17
18     def exchange(self, btc_amount, quote_currency):
19         with self.lock:
20             if self.quote_currencies is None:
21                 return None
22             quote_currencies = self.quote_currencies.copy()
23         if quote_currency not in quote_currencies:
24             return None
25         return btc_amount * quote_currencies[quote_currency]
26
27     def run(self):
28         self.discovery()
29
30     def discovery(self):
31         try:
32             connection = httplib.HTTPSConnection('blockchain.info')
33             connection.request("GET", "/ticker")
34         except:
35             return
36         response = connection.getresponse()
37         if response.reason == httplib.responses[httplib.NOT_FOUND]:
38             return
39         response = json.loads(response.read())
40         quote_currencies = {}
41         try:
42             for r in response:
43                 quote_currencies[r] = self._lookup_rate(response, r)
44             with self.lock:
45                 self.quote_currencies = quote_currencies
46             self.parent.emit(SIGNAL("refresh_balance()"))
47         except KeyError:
48             pass
49             
50     def get_currencies(self):
51         return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
52
53     def _lookup_rate(self, response, quote_id):
54         return decimal.Decimal(str(response[str(quote_id)]["15m"]))
55
56 if __name__ == "__main__":
57     exch = Exchanger(("BRL", "CNY", "EUR", "GBP", "RUB", "USD"))
58     print exch.exchange(1, "EUR")
59