From f92d47a16bb61fc9631b0cac29cb63b68cab25f3 Mon Sep 17 00:00:00 2001 From: Sam Germain Date: Fri, 31 Dec 2021 05:28:25 -0600 Subject: [PATCH] exchange._contracts_to_amount and exchange._amount_to_contracts safe checks --- freqtrade/exchange/exchange.py | 12 ++++++++++-- tests/exchange/test_exchange.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 1f395b014..cdb6de52a 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -875,15 +875,23 @@ class Exchange: def _amount_to_contracts(self, pair: str, amount: float): + contract_size = None if ('contractSize' in self.markets[pair]): - return amount / self.markets[pair]['contractSize'] + contract_size = self.markets[pair]['contractSize'] + + if (contract_size and self.trading_mode == TradingMode.FUTURES): + return amount / contract_size else: return amount def _contracts_to_amount(self, pair: str, num_contracts: float): + contract_size = None if ('contractSize' in self.markets[pair]): - return num_contracts * self.markets[pair]['contractSize'] + contract_size = self.markets[pair]['contractSize'] + + if (contract_size and self.trading_mode == TradingMode.FUTURES): + return num_contracts * contract_size else: return num_contracts diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 429ba153f..94aee0e14 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -3897,6 +3897,7 @@ def test__trades_contracts_to_amount( @pytest.mark.parametrize('pair,param_amount,param_size', [ ('XLTCUSDT', 40, 4000), ('LTC/ETH', 30, 30), + ('LTC/USD', 30, 30), ('ETH/USDT:USDT', 10, 1), ]) def test__amount_to_contracts( @@ -3908,9 +3909,32 @@ def test__amount_to_contracts( param_size ): api_mock = MagicMock() - default_conf['trading_mode'] = 'futures' + default_conf['trading_mode'] = 'spot' default_conf['collateral'] = 'isolated' - mocker.patch('freqtrade.exchange.Exchange.markets', markets) + mocker.patch('freqtrade.exchange.Exchange.markets', { + 'LTC/USD': { + 'symbol': 'LTC/USD', + 'contractSize': None, + }, + 'XLTCUSDT': { + 'symbol': 'XLTCUSDT', + 'contractSize': 0.01, + }, + 'LTC/ETH': { + 'symbol': 'LTC/ETH', + }, + 'ETH/USDT:USDT': { + 'symbol': 'ETH/USDT:USDT', + 'contractSize': 10, + } + }) + exchange = get_patched_exchange(mocker, default_conf, api_mock) + result_size = exchange._amount_to_contracts(pair, param_amount) + assert result_size == param_amount + result_amount = exchange._contracts_to_amount(pair, param_size) + assert result_amount == param_size + + default_conf['trading_mode'] = 'futures' exchange = get_patched_exchange(mocker, default_conf, api_mock) result_size = exchange._amount_to_contracts(pair, param_amount) assert result_size == param_size