59e0c9266c020e48726c54b5c80b3a25fc859ed9
[electrum-nvc.git] / lib / exchange_rate.py
1 import decimal
2 import httplib
3 import json
4
5 class Exchanger:
6
7     def __init__(self, quote_currencies, refresh_balance):
8         self.refresh_balance = refresh_balance
9         self.quote_currencies = {}
10
11     def exchange(self, btc_amount, quote_currency):
12         return btc_amount * self.quote_currencies[quote_currency]
13
14     def discovery(self):
15         connection = httplib.HTTPSConnection('intersango.com')
16         connection.request("GET", "/api/ticker.php")
17         response = connection.getresponse()
18         if response.status == 404:
19             return
20         response = json.loads(response.read())
21         # 1 = BTC:GBP
22         # 2 = BTC:EUR
23         # 3 = BTC:USD
24         # 4 = BTC:PLN
25         try:
26             self.quote_currencies["GBP"] = self.lookup_rate(response, 1)
27             self.quote_currencies["EUR"] = self.lookup_rate(response, 2)
28             self.quote_currencies["USD"] = self.lookup_rate(response, 3)
29             self.refresh_balance()
30         except KeyError:
31             pass
32
33     def lookup_rate(self, response, quote_id):
34         return decimal.Decimal(response[str(quote_id)]["last"])
35
36 if __name__ == "__main__":
37     exch = Exchanger(("EUR", "USD", "GBP"))
38     print exch.exchange(1, "EUR")
39