cbfa9ca7b2b919896b72c6bb54760205a522d890
[electrum-nvc.git] / gui / gui_classic / 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.HTTPConnection('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         try:
40             response = json.loads(response.read())
41         except:
42             return
43         quote_currencies = {}
44         try:
45             for r in response:
46                 quote_currencies[r] = self._lookup_rate(response, r)
47             with self.lock:
48                 self.quote_currencies = quote_currencies
49             self.parent.emit(SIGNAL("refresh_balance()"))
50         except KeyError:
51             pass
52             
53     def get_currencies(self):
54         return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys())
55
56     def _lookup_rate(self, response, quote_id):
57         return decimal.Decimal(str(response[str(quote_id)]["15m"]))
58
59 if __name__ == "__main__":
60     exch = Exchanger(("BRL", "CNY", "EUR", "GBP", "RUB", "USD"))
61     print exch.exchange(1, "EUR")
62