2020-12-22 18:03:48 +00:00
|
|
|
# SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
# Copyright (c) 2020, The Monero Project.
|
|
|
|
# Copyright (c) 2020, dsc@xmr.pm
|
|
|
|
|
2021-04-05 17:50:26 +00:00
|
|
|
from datetime import datetime, timedelta
|
|
|
|
import re
|
|
|
|
|
2021-04-05 17:49:02 +00:00
|
|
|
from wowlet_backend.utils import httpget
|
|
|
|
from wowlet_backend.tasks import FeatherTask
|
2020-12-22 18:03:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class FiatRatesTask(FeatherTask):
|
2021-04-05 19:03:35 +00:00
|
|
|
def __init__(self, interval: int = 43200):
|
2020-12-22 18:03:48 +00:00
|
|
|
super(FiatRatesTask, self).__init__(interval)
|
|
|
|
|
|
|
|
self._cache_key = "fiat_rates"
|
|
|
|
self._cache_expiry = self.interval * 10
|
|
|
|
|
|
|
|
self._websocket_cmd = "fiat_rates"
|
|
|
|
|
2021-04-05 17:50:26 +00:00
|
|
|
self._http_endpoint = "https://sdw-wsrest.ecb.europa.eu/service/data/EXR/D.USD+GBP+JPY+CZK+CAD+ZAR+KRW+MXN+RUB+SEK+THB+NZD+AUD+CHF+TRY+CNY.EUR.SP00.A"
|
2020-12-22 18:03:48 +00:00
|
|
|
|
|
|
|
async def task(self):
|
|
|
|
"""Fetch fiat rates"""
|
2021-04-05 17:50:26 +00:00
|
|
|
start_from = "?startPeriod=" + (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
|
|
|
|
result = await httpget(self._http_endpoint + start_from, json=False)
|
|
|
|
|
|
|
|
results = {}
|
|
|
|
currency = ""
|
|
|
|
value = ""
|
|
|
|
|
|
|
|
# XML "parsing"
|
|
|
|
for line in result.split("\n"):
|
|
|
|
if "\"UNIT\"" in line:
|
|
|
|
if currency:
|
|
|
|
results[currency] = value
|
|
|
|
currency = re.search(r"value=\"(\w+)\"", line).group(1)
|
|
|
|
if "ObsValue value" in line:
|
|
|
|
value = float(re.search("ObsValue value=\"([0-9.]+)\"", line).group(1))
|
|
|
|
|
|
|
|
# Base currency is EUR, needs to be USD
|
|
|
|
results['EUR'] = 1
|
|
|
|
usd_rate = results['USD']
|
|
|
|
results = {k: round(v / usd_rate, 4) for k, v in results.items()}
|
|
|
|
return results
|