diff --git a/.env-sample b/.env-sample index 54d6637c..f5612fb4 100644 --- a/.env-sample +++ b/.env-sample @@ -6,8 +6,8 @@ LND_GRPC_HOST='127.0.0.1:10009' REDIS_URL='' -# Market price public API -MARKET_PRICE_API = 'https://blockchain.info/ticker' +# List of market price public APIs. If the currency is available in more than 1 API, will use median price. +MARKET_PRICE_APIS = https://blockchain.info/ticker, https://api.yadio.io/exrates/BTC # Host e.g. robotestagw3dcxmd66r4rgksb4nmmr43fh77bzn2ia2eucduyeafnyd.onion HOST_NAME = '' diff --git a/api/logics.py b/api/logics.py index bdf2ddd9..df5592b6 100644 --- a/api/logics.py +++ b/api/logics.py @@ -10,7 +10,6 @@ import math FEE = float(config('FEE')) BOND_SIZE = float(config('BOND_SIZE')) -MARKET_PRICE_API = config('MARKET_PRICE_API') ESCROW_USERNAME = config('ESCROW_USERNAME') PENALTY_TIMEOUT = int(config('PENALTY_TIMEOUT')) diff --git a/api/utils.py b/api/utils.py index 6c23d924..f97cb569 100644 --- a/api/utils.py +++ b/api/utils.py @@ -1,18 +1,32 @@ import requests, ring, os from decouple import config - +from statistics import median market_cache = {} @ring.dict(market_cache, expire=30) #keeps in cache for 30 seconds def get_exchange_rate(currency): - # TODO Add fallback Public APIs and error handling - # Think about polling price data in a different way (e.g. store locally every t seconds) + ''' + Checks for exchange rates in several public APIs. + Returns the median price. + ''' + + APIS = config('MARKET_PRICE_APIS', cast=lambda v: [s.strip() for s in v.split(',')]) + exchange_rates = [] - market_prices = requests.get(config('MARKET_PRICE_API')).json() - exchange_rate = float(market_prices[currency]['last']) + for api_url in APIS: + print(api_url) + try: + if 'blockchain.info' in api_url: + blockchain_prices = requests.get(api_url).json() + exchange_rates.append(float(blockchain_prices[currency]['last'])) + elif 'yadio.io' in api_url: + yadio_prices = requests.get(api_url).json() + exchange_rates.append(float(yadio_prices['BTC'][currency])) + except: + pass - return exchange_rate + return median(exchange_rates) lnd_v_cache = {}