lbry-sdk/lbry/service/exchange_rate_manager.py

217 lines
7.3 KiB
Python
Raw Normal View History

2019-12-15 07:02:18 +01:00
import json
2016-07-28 11:30:13 +02:00
import time
2019-12-15 07:02:18 +01:00
import asyncio
2016-07-28 11:30:13 +02:00
import logging
2019-03-20 06:46:23 +01:00
from decimal import Decimal
2019-12-15 07:02:18 +01:00
from typing import Optional, Iterable, Type
from aiohttp.client_exceptions import ContentTypeError
from lbry.error import InvalidExchangeRateResponseError, CurrencyConversionError
2019-06-21 02:55:47 +02:00
from lbry.utils import aiohttp_request
2020-06-05 06:35:22 +02:00
from lbry.blockchain.dewies import lbc_to_dewies
2016-12-05 22:51:16 +01:00
2016-07-28 11:30:13 +02:00
log = logging.getLogger(__name__)
class ExchangeRate:
2016-07-28 11:30:13 +02:00
def __init__(self, market, spot, ts):
if not int(time.time()) - ts < 600:
raise ValueError('The timestamp is too dated.')
if not spot > 0:
raise ValueError('Spot must be greater than 0.')
2016-07-28 11:30:13 +02:00
self.currency_pair = (market[0:3], market[3:6])
self.spot = spot
self.ts = ts
2017-02-28 02:18:57 +01:00
def __repr__(self):
2019-12-15 07:02:18 +01:00
return f"Currency pair:{self.currency_pair}, spot:{self.spot}, ts:{self.ts}"
2017-02-28 02:18:57 +01:00
2016-07-28 11:30:13 +02:00
def as_dict(self):
return {'spot': self.spot, 'ts': self.ts}
2019-12-15 07:02:18 +01:00
class MarketFeed:
name: str = ""
market: str = ""
url: str = ""
2019-12-15 07:02:18 +01:00
params = {}
fee = 0
2019-10-14 11:17:18 +02:00
2019-12-15 07:02:18 +01:00
update_interval = 300
request_timeout = 50
2019-10-14 11:17:18 +02:00
2019-12-15 07:02:18 +01:00
def __init__(self):
self.rate: Optional[float] = None
self.last_check = 0
self._last_response = None
self._task: Optional[asyncio.Task] = None
2019-12-15 07:02:18 +01:00
self.event = asyncio.Event()
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
@property
def has_rate(self):
2017-02-28 02:18:57 +01:00
return self.rate is not None
2019-12-15 07:02:18 +01:00
@property
def is_online(self):
2019-12-15 07:02:18 +01:00
return self.last_check+self.update_interval+self.request_timeout > time.time()
2016-07-28 11:30:13 +02:00
def get_rate_from_response(self, json_response):
raise NotImplementedError()
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
async def get_response(self):
async with aiohttp_request('get', self.url, params=self.params, timeout=self.request_timeout) as response:
try:
self._last_response = await response.json()
except ContentTypeError as e:
self._last_response = {}
log.warning("Could not parse exchange rate response from %s: %s", self.name, e.message)
log.debug(await response.text())
2019-12-15 07:02:18 +01:00
return self._last_response
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
async def get_rate(self):
2019-10-14 11:17:18 +02:00
try:
2019-12-15 07:02:18 +01:00
data = await self.get_response()
rate = self.get_rate_from_response(data)
rate = rate / (1.0 - self.fee)
log.debug("Saving rate update %f for %s from %s", rate, self.market, self.name)
self.rate = ExchangeRate(self.market, rate, int(time.time()))
self.last_check = time.time()
self.event.set()
return self.rate
except asyncio.CancelledError:
raise
except asyncio.TimeoutError:
log.warning("Timed out fetching exchange rate from %s.", self.name)
except json.JSONDecodeError as e:
log.warning("Could not parse exchange rate response from %s: %s", self.name, e.doc)
except InvalidExchangeRateResponseError as e:
log.warning(str(e))
except Exception as e:
log.exception("Exchange rate error (%s from %s):", self.market, self.name)
async def keep_updated(self):
while True:
2019-12-15 07:02:18 +01:00
await self.get_rate()
await asyncio.sleep(self.update_interval)
2016-07-28 11:30:13 +02:00
def start(self):
if not self._task:
2019-12-15 07:02:18 +01:00
self._task = asyncio.create_task(self.keep_updated())
2016-07-28 11:30:13 +02:00
def stop(self):
if self._task and not self._task.done():
self._task.cancel()
self._task = None
2019-12-15 07:02:18 +01:00
self.event.clear()
2016-07-28 11:30:13 +02:00
class BittrexFeed(MarketFeed):
2019-12-15 07:02:18 +01:00
name = "Bittrex"
market = "BTCLBC"
url = "https://bittrex.com/api/v1.1/public/getmarkethistory"
params = {'market': 'BTC-LBC', 'count': 50}
fee = 0.0025
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
def get_rate_from_response(self, json_response):
2017-02-28 02:18:57 +01:00
if 'result' not in json_response:
raise InvalidExchangeRateResponseError(self.name, 'result not found')
2017-02-28 02:18:57 +01:00
trades = json_response['result']
if len(trades) == 0:
2019-12-15 07:02:18 +01:00
raise InvalidExchangeRateResponseError(self.name, 'trades not found')
2017-02-28 02:18:57 +01:00
totals = sum([i['Total'] for i in trades])
qtys = sum([i['Quantity'] for i in trades])
if totals <= 0 or qtys <= 0:
2019-12-15 07:02:18 +01:00
raise InvalidExchangeRateResponseError(self.name, 'quantities were not positive')
2018-07-24 18:36:00 +02:00
vwap = totals / qtys
return float(1.0 / vwap)
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
class LBRYFeed(MarketFeed):
name = "lbry.com"
market = "BTCLBC"
url = "https://api.lbry.com/lbc/exchange_rate"
2019-12-15 07:02:18 +01:00
def get_rate_from_response(self, json_response):
if 'data' not in json_response:
raise InvalidExchangeRateResponseError(self.name, 'result not found')
return 1.0 / json_response['data']['lbc_btc']
2019-12-15 07:02:18 +01:00
class LBRYBTCFeed(LBRYFeed):
market = "USDBTC"
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
def get_rate_from_response(self, json_response):
2017-09-07 19:55:36 +02:00
if 'data' not in json_response:
raise InvalidExchangeRateResponseError(self.name, 'result not found')
return 1.0 / json_response['data']['btc_usd']
2016-07-28 11:30:13 +02:00
2019-12-15 07:02:18 +01:00
class CryptonatorFeed(MarketFeed):
name = "cryptonator.com"
market = "BTCLBC"
url = "https://api.cryptonator.com/api/ticker/btc-lbc"
2019-12-15 07:02:18 +01:00
def get_rate_from_response(self, json_response):
2017-10-08 16:15:53 +02:00
if 'ticker' not in json_response or len(json_response['ticker']) == 0 or \
2018-07-24 18:36:00 +02:00
'success' not in json_response or json_response['success'] is not True:
raise InvalidExchangeRateResponseError(self.name, 'result not found')
return float(json_response['ticker']['price'])
2019-12-15 07:02:18 +01:00
class CryptonatorBTCFeed(CryptonatorFeed):
market = "USDBTC"
url = "https://api.cryptonator.com/api/ticker/usd-btc"
2019-12-15 07:02:18 +01:00
FEEDS: Iterable[Type[MarketFeed]] = (
LBRYFeed,
LBRYBTCFeed,
BittrexFeed,
2020-01-03 21:28:29 +01:00
# CryptonatorFeed,
# CryptonatorBTCFeed,
2019-12-15 07:02:18 +01:00
)
class ExchangeRateManager:
2019-12-15 07:02:18 +01:00
def __init__(self, feeds=FEEDS):
self.market_feeds = [Feed() for Feed in feeds]
def wait(self):
return asyncio.wait(
[feed.event.wait() for feed in self.market_feeds],
)
2016-07-28 11:30:13 +02:00
def start(self):
log.info("Starting exchange rate manager")
for feed in self.market_feeds:
feed.start()
def stop(self):
log.info("Stopping exchange rate manager")
for source in self.market_feeds:
source.stop()
def convert_currency(self, from_currency, to_currency, amount):
2017-02-28 02:18:57 +01:00
rates = [market.rate for market in self.market_feeds]
log.debug("Converting %f %s to %s, rates: %s", amount, from_currency, to_currency, rates)
if from_currency == to_currency:
return round(amount, 8)
2016-07-28 11:30:13 +02:00
for market in self.market_feeds:
2019-12-15 07:02:18 +01:00
if (market.has_rate and market.is_online and
2018-07-24 18:36:00 +02:00
market.rate.currency_pair == (from_currency, to_currency)):
return round(amount * Decimal(market.rate.spot), 8)
2016-07-28 11:30:13 +02:00
for market in self.market_feeds:
2019-12-15 07:02:18 +01:00
if (market.has_rate and market.is_online and
2018-07-24 18:36:00 +02:00
market.rate.currency_pair[0] == from_currency):
return round(self.convert_currency(
market.rate.currency_pair[1], to_currency, amount * Decimal(market.rate.spot)), 8)
raise CurrencyConversionError(
f'Unable to convert {amount} from {from_currency} to {to_currency}')
2016-07-28 11:30:13 +02:00
def to_dewies(self, currency, amount) -> int:
converted = self.convert_currency(currency, "LBC", amount)
return lbc_to_dewies(str(converted))
2016-07-28 11:30:13 +02:00
def fee_dict(self):
return {market: market.rate.as_dict() for market in self.market_feeds}