making ruff happy

This commit is contained in:
Jakub Werner (jakubikan) 2024-03-22 21:29:33 +01:00
parent cbc98d384e
commit ff2eaeb3b4
2 changed files with 55 additions and 31 deletions

View File

@ -53,8 +53,9 @@ class Binance(Exchange):
] ]
def __init__(self, *args, **kwargs) -> None: def __init__(self, *args, **kwargs) -> None:
super(Binance, self).__init__(*args, **kwargs) super(__class__, self).__init__(*args, **kwargs)
self._spot_delist_schedule_cache: TTLCache = TTLCache(maxsize=100, ttl=300) self._spot_delist_schedule_cache: TTLCache = TTLCache(
maxsize=100, ttl=300)
self._spot_delist_schedule_cache_lock = Lock() self._spot_delist_schedule_cache_lock = Lock()
def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers: def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers:
@ -63,7 +64,8 @@ class Binance(Exchange):
# Binance's future result has no bid/ask values. # Binance's future result has no bid/ask values.
# Therefore we must fetch that from fetch_bids_asks and combine the two results. # Therefore we must fetch that from fetch_bids_asks and combine the two results.
bidsasks = self.fetch_bids_asks(symbols, cached) bidsasks = self.fetch_bids_asks(symbols, cached)
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False) tickers = deep_merge_dicts(
bidsasks, tickers, allow_null_overrides=False)
return tickers return tickers
@retrier @retrier
@ -76,9 +78,11 @@ class Binance(Exchange):
try: try:
if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']: if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']:
position_side = self._api.fapiPrivateGetPositionSideDual() position_side = self._api.fapiPrivateGetPositionSideDual()
self._log_exchange_response('position_side_setting', position_side) self._log_exchange_response(
'position_side_setting', position_side)
assets_margin = self._api.fapiPrivateGetMultiAssetsMargin() assets_margin = self._api.fapiPrivateGetMultiAssetsMargin()
self._log_exchange_response('multi_asset_margin', assets_margin) self._log_exchange_response(
'multi_asset_margin', assets_margin)
msg = "" msg = ""
if position_side.get('dualSidePosition') is True: if position_side.get('dualSidePosition') is True:
msg += ( msg += (
@ -94,7 +98,7 @@ class Binance(Exchange):
except (ccxt.NetworkError, ccxt.ExchangeError) as e: except (ccxt.NetworkError, ccxt.ExchangeError) as e:
raise TemporaryError( raise TemporaryError(
f'Error in additional_exchange_init due to {e.__class__.__name__}. Message: {e}' f'Error in additional_exchange_init due to {e.__class__.__name__}. Message: {e}'
) from e ) from e
except ccxt.BaseError as e: except ccxt.BaseError as e:
raise OperationalException(e) from e raise OperationalException(e) from e
@ -182,7 +186,8 @@ class Binance(Exchange):
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100% # mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
# maintenance_amt: (CUM) Maintenance Amount of position # maintenance_amt: (CUM) Maintenance Amount of position
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount) mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(
pair, stake_amount)
if (maintenance_amt is None): if (maintenance_amt is None):
raise OperationalException( raise OperationalException(
@ -242,7 +247,7 @@ class Binance(Exchange):
if delist_time: if delist_time:
return delist_time return delist_time
try: try:
delist_schedule = self._api.sapi_get_spot_delist_schedule() delist_schedule = self._api.sapi_get_spot_delist_schedule()
if delist_schedule is None: if delist_schedule is None:
@ -262,4 +267,4 @@ class Binance(Exchange):
raise TemporaryError( raise TemporaryError(
f'Could not get delist schedule {e.__class__.__name__}. Message: {e}') from e f'Could not get delist schedule {e.__class__.__name__}. Message: {e}') from e
except ccxt.BaseError as e: except ccxt.BaseError as e:
raise OperationalException(e) from e raise OperationalException(e) from e

View File

@ -18,10 +18,11 @@ from tests.exchange.test_exchange import ccxt_exceptionhandlers
('buy', 'limit', 'PO', {'timeInForce': 'PO'}), ('buy', 'limit', 'PO', {'timeInForce': 'PO'}),
('sell', 'limit', 'PO', {'timeInForce': 'PO'}), ('sell', 'limit', 'PO', {'timeInForce': 'PO'}),
('sell', 'market', 'PO', {}), ('sell', 'market', 'PO', {}),
]) ])
def test__get_params_binance(default_conf, mocker, side, type, time_in_force, expected): def test__get_params_binance(default_conf, mocker, side, type, time_in_force, expected):
exchange = get_patched_exchange(mocker, default_conf, id='binance') exchange = get_patched_exchange(mocker, default_conf, id='binance')
assert exchange._get_params(side, type, 1, False, time_in_force) == expected assert exchange._get_params(
side, type, 1, False, time_in_force) == expected
@pytest.mark.parametrize('trademode', [TradingMode.FUTURES, TradingMode.SPOT]) @pytest.mark.parametrize('trademode', [TradingMode.FUTURES, TradingMode.SPOT])
@ -58,7 +59,8 @@ def test_create_stoploss_order_binance(default_conf, mocker, limitratio, expecte
amount=1, amount=1,
stop_price=190, stop_price=190,
side=side, side=side,
order_types={'stoploss': 'limit', 'stoploss_on_exchange_limit_ratio': 1.05}, order_types={'stoploss': 'limit',
'stoploss_on_exchange_limit_ratio': 1.05},
leverage=1.0 leverage=1.0
) )
@ -88,13 +90,16 @@ def test_create_stoploss_order_binance(default_conf, mocker, limitratio, expecte
if trademode == TradingMode.SPOT: if trademode == TradingMode.SPOT:
params_dict = {'stopPrice': 220} params_dict = {'stopPrice': 220}
else: else:
params_dict = {'stopPrice': 220, 'reduceOnly': True, 'workingType': 'MARK_PRICE'} params_dict = {'stopPrice': 220,
'reduceOnly': True, 'workingType': 'MARK_PRICE'}
assert api_mock.create_order.call_args_list[0][1]['params'] == params_dict assert api_mock.create_order.call_args_list[0][1]['params'] == params_dict
# test exception handling # test exception handling
with pytest.raises(DependencyException): with pytest.raises(DependencyException):
api_mock.create_order = MagicMock(side_effect=ccxt.InsufficientFunds("0 balance")) api_mock.create_order = MagicMock(
exchange = get_patched_exchange(mocker, default_conf, api_mock, 'binance') side_effect=ccxt.InsufficientFunds("0 balance"))
exchange = get_patched_exchange(
mocker, default_conf, api_mock, 'binance')
exchange.create_stoploss( exchange.create_stoploss(
pair='ETH/BTC', pair='ETH/BTC',
amount=1, amount=1,
@ -106,7 +111,8 @@ def test_create_stoploss_order_binance(default_conf, mocker, limitratio, expecte
with pytest.raises(InvalidOrderException): with pytest.raises(InvalidOrderException):
api_mock.create_order = MagicMock( api_mock.create_order = MagicMock(
side_effect=ccxt.InvalidOrder("binance Order would trigger immediately.")) side_effect=ccxt.InvalidOrder("binance Order would trigger immediately."))
exchange = get_patched_exchange(mocker, default_conf, api_mock, 'binance') exchange = get_patched_exchange(
mocker, default_conf, api_mock, 'binance')
exchange.create_stoploss( exchange.create_stoploss(
pair='ETH/BTC', pair='ETH/BTC',
amount=1, amount=1,
@ -383,7 +389,8 @@ def test_fill_leverage_tiers_binance(default_conf, mocker):
default_conf['dry_run'] = False default_conf['dry_run'] = False
default_conf['trading_mode'] = TradingMode.FUTURES default_conf['trading_mode'] = TradingMode.FUTURES
default_conf['margin_mode'] = MarginMode.ISOLATED default_conf['margin_mode'] = MarginMode.ISOLATED
exchange = get_patched_exchange(mocker, default_conf, api_mock, id="binance") exchange = get_patched_exchange(
mocker, default_conf, api_mock, id="binance")
exchange.fill_leverage_tiers() exchange.fill_leverage_tiers()
assert exchange._leverage_tiers == { assert exchange._leverage_tiers == {
@ -486,7 +493,8 @@ def test_fill_leverage_tiers_binance(default_conf, mocker):
api_mock = MagicMock() api_mock = MagicMock()
api_mock.load_leverage_tiers = MagicMock() api_mock.load_leverage_tiers = MagicMock()
type(api_mock).has = PropertyMock(return_value={'fetchLeverageTiers': True}) type(api_mock).has = PropertyMock(
return_value={'fetchLeverageTiers': True})
ccxt_exceptionhandlers( ccxt_exceptionhandlers(
mocker, mocker,
@ -502,7 +510,8 @@ def test_fill_leverage_tiers_binance_dryrun(default_conf, mocker, leverage_tiers
api_mock = MagicMock() api_mock = MagicMock()
default_conf['trading_mode'] = TradingMode.FUTURES default_conf['trading_mode'] = TradingMode.FUTURES
default_conf['margin_mode'] = MarginMode.ISOLATED default_conf['margin_mode'] = MarginMode.ISOLATED
exchange = get_patched_exchange(mocker, default_conf, api_mock, id="binance") exchange = get_patched_exchange(
mocker, default_conf, api_mock, id="binance")
exchange.fill_leverage_tiers() exchange.fill_leverage_tiers()
assert len(exchange._leverage_tiers.keys()) > 100 assert len(exchange._leverage_tiers.keys()) > 100
for key, value in leverage_tiers.items(): for key, value in leverage_tiers.items():
@ -514,17 +523,23 @@ def test_fill_leverage_tiers_binance_dryrun(default_conf, mocker, leverage_tiers
def test_additional_exchange_init_binance(default_conf, mocker): def test_additional_exchange_init_binance(default_conf, mocker):
api_mock = MagicMock() api_mock = MagicMock()
api_mock.fapiPrivateGetPositionSideDual = MagicMock(return_value={"dualSidePosition": True}) api_mock.fapiPrivateGetPositionSideDual = MagicMock(
api_mock.fapiPrivateGetMultiAssetsMargin = MagicMock(return_value={"multiAssetsMargin": True}) return_value={"dualSidePosition": True})
api_mock.fapiPrivateGetMultiAssetsMargin = MagicMock(
return_value={"multiAssetsMargin": True})
default_conf['dry_run'] = False default_conf['dry_run'] = False
default_conf['trading_mode'] = TradingMode.FUTURES default_conf['trading_mode'] = TradingMode.FUTURES
default_conf['margin_mode'] = MarginMode.ISOLATED default_conf['margin_mode'] = MarginMode.ISOLATED
with pytest.raises(OperationalException, with pytest.raises(OperationalException,
match=r"Hedge Mode is not supported.*\nMulti-Asset Mode is not supported.*"): match=r"Hedge Mode is not supported.*\nMulti-Asset Mode is not supported.*"):
get_patched_exchange(mocker, default_conf, id="binance", api_mock=api_mock) get_patched_exchange(mocker, default_conf,
api_mock.fapiPrivateGetPositionSideDual = MagicMock(return_value={"dualSidePosition": False}) id="binance", api_mock=api_mock)
api_mock.fapiPrivateGetMultiAssetsMargin = MagicMock(return_value={"multiAssetsMargin": False}) api_mock.fapiPrivateGetPositionSideDual = MagicMock(
exchange = get_patched_exchange(mocker, default_conf, id="binance", api_mock=api_mock) return_value={"dualSidePosition": False})
api_mock.fapiPrivateGetMultiAssetsMargin = MagicMock(
return_value={"multiAssetsMargin": False})
exchange = get_patched_exchange(
mocker, default_conf, id="binance", api_mock=api_mock)
assert exchange assert exchange
ccxt_exceptionhandlers(mocker, default_conf, api_mock, 'binance', ccxt_exceptionhandlers(mocker, default_conf, api_mock, 'binance',
"additional_exchange_init", "fapiPrivateGetPositionSideDual") "additional_exchange_init", "fapiPrivateGetPositionSideDual")
@ -539,7 +554,8 @@ def test__set_leverage_binance(mocker, default_conf):
default_conf['trading_mode'] = TradingMode.FUTURES default_conf['trading_mode'] = TradingMode.FUTURES
default_conf['margin_mode'] = MarginMode.ISOLATED default_conf['margin_mode'] = MarginMode.ISOLATED
exchange = get_patched_exchange(mocker, default_conf, api_mock, id="binance") exchange = get_patched_exchange(
mocker, default_conf, api_mock, id="binance")
exchange._set_leverage(3.2, 'BTC/USDT:USDT') exchange._set_leverage(3.2, 'BTC/USDT:USDT')
assert api_mock.set_leverage.call_count == 1 assert api_mock.set_leverage.call_count == 1
# Leverage is rounded to 3. # Leverage is rounded to 3.
@ -592,7 +608,8 @@ async def test__async_get_historic_ohlcv_binance(default_conf, mocker, caplog, c
# Called twice - one "init" call - and one to get the actual data. # Called twice - one "init" call - and one to get the actual data.
assert exchange._api_async.fetch_ohlcv.call_count == 2 assert exchange._api_async.fetch_ohlcv.call_count == 2
assert res == ohlcv assert res == ohlcv
assert log_has_re(r"Candle-data for ETH/BTC available starting with .*", caplog) assert log_has_re(
r"Candle-data for ETH/BTC available starting with .*", caplog)
@pytest.mark.parametrize('pair,nominal_value,mm_ratio,amt', [ @pytest.mark.parametrize('pair,nominal_value,mm_ratio,amt', [
@ -615,13 +632,15 @@ def test_get_maintenance_ratio_and_amt_binance(
mocker.patch(f'{EXMS}.exchange_has', return_value=True) mocker.patch(f'{EXMS}.exchange_has', return_value=True)
exchange = get_patched_exchange(mocker, default_conf, id="binance") exchange = get_patched_exchange(mocker, default_conf, id="binance")
exchange._leverage_tiers = leverage_tiers exchange._leverage_tiers = leverage_tiers
(result_ratio, result_amt) = exchange.get_maintenance_ratio_and_amt(pair, nominal_value) (result_ratio, result_amt) = exchange.get_maintenance_ratio_and_amt(
pair, nominal_value)
assert (round(result_ratio, 8), round(result_amt, 8)) == (mm_ratio, amt) assert (round(result_ratio, 8), round(result_amt, 8)) == (mm_ratio, amt)
def test_get_spot_delist_schedule(mocker, default_conf) -> None: def test_get_spot_delist_schedule(mocker, default_conf) -> None:
exchange = get_patched_exchange(mocker, default_conf, id='binance') exchange = get_patched_exchange(mocker, default_conf, id='binance')
exchange._api.sapi_get_spot_delist_schedule = MagicMock(return_value=[{'delistTime': '1712113200000', 'symbols': ['DREPBTC', 'DREPUSDT', 'MOBBTC', 'MOBUSDT', 'PNTUSDT']}]) exchange._api.sapi_get_spot_delist_schedule = MagicMock(return_value=[
{'delistTime': '1712113200000', 'symbols': ['DREPBTC', 'DREPUSDT', 'MOBBTC', 'MOBUSDT', 'PNTUSDT']}])
assert exchange.get_spot_pair_delist_time(
assert exchange.get_spot_pair_delist_time('DREP/USDT', False) == 1712113200000 'DREP/USDT', False) == 1712113200000