Add exception handling to all exchange functions

This commit is contained in:
enenn 2018-02-09 19:15:54 +01:00
parent f2215182dd
commit 478c3e299e
2 changed files with 48 additions and 17 deletions

View File

@ -52,9 +52,6 @@ def init(config: dict) -> None:
except KeyError: except KeyError:
raise OperationalException('Exchange {} is not supported'.format(name)) raise OperationalException('Exchange {} is not supported'.format(name))
# we need load api markets
_API.load_markets()
# Check if all pairs are available # Check if all pairs are available
validate_pairs(config['exchange']['pair_whitelist']) validate_pairs(config['exchange']['pair_whitelist'])
@ -166,13 +163,16 @@ def get_balance(currency: str) -> float:
if _CONF['dry_run']: if _CONF['dry_run']:
return 999.9 return 999.9
return _API.fetch_balance()[currency]['free'] # ccxt exception is already handled by get_balances
balances = get_balances()
return balances[currency]['free']
def get_balances() -> dict: def get_balances() -> dict:
if _CONF['dry_run']: if _CONF['dry_run']:
return {} return {}
try:
balances = _API.fetch_balance() balances = _API.fetch_balance()
# Remove additional info from ccxt results # Remove additional info from ccxt results
balances.pop("info", None) balances.pop("info", None)
@ -181,19 +181,36 @@ def get_balances() -> dict:
balances.pop("used", None) balances.pop("used", None)
return balances return balances
except ccxt.NetworkError as e:
raise NetworkException(
'Could not get balance due to networking error. Message: {}'.format(e)
)
except ccxt.BaseError as e:
raise OperationalException(e)
def get_ticker(pair: str, refresh: Optional[bool] = True) -> dict: def get_ticker(pair: str, refresh: Optional[bool] = True) -> dict:
try:
# TODO: add caching # TODO: add caching
return _API.fetch_ticker(pair) return _API.fetch_ticker(pair)
except ccxt.NetworkError as e:
raise NetworkException(
'Could not load tickers due to networking error. Message: {}'.format(e)
)
except ccxt.BaseError as e:
raise OperationalException(e)
@cached(TTLCache(maxsize=100, ttl=30)) @cached(TTLCache(maxsize=100, ttl=30))
def get_ticker_history(pair: str, tick_interval: str) -> List[Dict]: def get_ticker_history(pair: str, tick_interval: str) -> List[Dict]:
# TODO: check if exchange supports fetch_ohlcv if not _API.hasFetchOHLCV():
raise OperationalException(
'Exhange {} does not support fetching historical candlestick data.'.format(_API.name)
)
try:
history = _API.fetch_ohlcv(pair, timeframe=tick_interval) history = _API.fetch_ohlcv(pair, timeframe=tick_interval)
history_json = [] history_json = []
try:
for candlestick in history: for candlestick in history:
history_json.append({ history_json.append({
'T': datetime.fromtimestamp(candlestick[0]/1000.0).strftime('%Y-%m-%dT%H:%M:%S.%f'), 'T': datetime.fromtimestamp(candlestick[0]/1000.0).strftime('%Y-%m-%dT%H:%M:%S.%f'),
@ -207,6 +224,12 @@ def get_ticker_history(pair: str, tick_interval: str) -> List[Dict]:
except IndexError as e: except IndexError as e:
logger.warning('Empty ticker history. Msg %s', str(e)) logger.warning('Empty ticker history. Msg %s', str(e))
return [] return []
except ccxt.NetworkError as e:
raise NetworkException(
'Could not load ticker history due to networking error. Message: {}'.format(e)
)
except ccxt.BaseError as e:
raise OperationalException('Could not fetch ticker data. Msg: {}'.format(e))
def cancel_order(order_id: str, pair: str) -> None: def cancel_order(order_id: str, pair: str) -> None:
@ -254,7 +277,14 @@ def get_pair_detail_url(pair: str) -> str:
def get_markets() -> List[dict]: def get_markets() -> List[dict]:
try:
return _API.fetch_markets() return _API.fetch_markets()
except ccxt.NetworkError as e:
raise NetworkException(
'Could not load markets due to networking error. Message: {}'.format(e)
)
except ccxt.BaseError as e:
raise OperationalException(e)
def get_name() -> str: def get_name() -> str:

View File

@ -246,6 +246,7 @@ def test_get_ticker_history(default_conf, mocker):
5, # volume (in quote currency) 5, # volume (in quote currency)
] ]
] ]
api_mock.hasFetchOHLVC = MagicMock(return_value=True)
api_mock.fetch_ohlcv = MagicMock(return_value=tick) api_mock.fetch_ohlcv = MagicMock(return_value=tick)
mocker.patch('freqtrade.exchange._API', api_mock) mocker.patch('freqtrade.exchange._API', api_mock)