-
Notifications
You must be signed in to change notification settings - Fork 857
/
Copy pathfiatconverter.py
71 lines (56 loc) · 1.97 KB
/
fiatconverter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Copyright (C) 2013-2019, Maxime Biais <[email protected]>
import urllib.request
import sys
import xml.sax
import logging
import time
class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
if "currency" in attributes and "rate" in attributes:
self.rates[attributes["currency"]] = float(attributes["rate"])
def endElement(self, tag):
pass
def characters(self, content):
pass
class FiatConverter:
__shared_state = {}
# Europa.eu is the official european central bank
rate_exchange_url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def __init__(self):
self.__dict__ = self.__shared_state
self.rates = {}
self.update_delay = 60 * 60 * 6 # every 6 hours
self.last_update = 0
self.bank_fee = 0.007 # TODO: bank fee
self.handler = XmlHandler()
def change_pivot(self, rates, pivot):
PVTEUR = 1.0 / rates[pivot]
for k in rates:
rates[k] = rates[k] * PVTEUR
return rates
def update_pairs(self):
url = self.rate_exchange_url
res = urllib.request.urlopen(url)
xml.sax.parseString(res.read().decode("utf8"), self.handler)
self.rates = self.handler.rates
self.rates["EUR"] = 1
def update(self):
timediff = time.time() - self.last_update
if timediff < self.update_delay:
return
self.last_update = time.time()
self.update_pairs()
def convert(self, price, code_from, code_to):
self.update()
rate_from = self.rates[code_from]
rate_to = self.rates[code_to]
return price / rate_from * rate_to
if __name__ == "__main__":
fc = FiatConverter()
print(fc.convert(12.0, "USD", "EUR"))
print(fc.convert(12.0, "EUR", "USD"))
print(fc.convert(fc.convert(12.0, "EUR", "USD"), "USD", "EUR"))
print(fc.rates)