From 33229c91cb160f836eecf28d4949e519034b6339 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 13:53:36 +0100 Subject: [PATCH 1/7] Add fetch_trading_fees endpoint --- freqtrade/exchange/exchange.py | 21 ++++++++++++ tests/exchange/test_exchange.py | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index e27a56aff..1d4fc8337 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1299,6 +1299,27 @@ class Exchange: except ccxt.BaseError as e: raise OperationalException(e) from e + @retrier + def fetch_trading_fees(self) -> Dict[str, Any]: + """ + Fetch user account trading fees + Can be cached, should not update often. + """ + if (self._config['dry_run'] or self.trading_mode != TradingMode.FUTURES + or not self.exchange_has('fetchTradingFees')): + return {} + try: + trading_fees: Dict[str, Any] = self._api.fetch_trading_fees() + self._log_exchange_response('fetch_trading_fees', trading_fees) + return trading_fees + except ccxt.DDoSProtection as e: + raise DDosProtection(e) from e + except (ccxt.NetworkError, ccxt.ExchangeError) as e: + raise TemporaryError( + f'Could not fetch trading fees due to {e.__class__.__name__}. Message: {e}') from e + except ccxt.BaseError as e: + raise OperationalException(e) from e + @retrier def fetch_bids_asks(self, symbols: List[str] = None, cached: bool = False) -> Dict: """ diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 815ebcec2..d19baf39a 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -1624,6 +1624,64 @@ def test_fetch_positions(default_conf, mocker, exchange_name): "fetch_positions", "fetch_positions") +def test_fetch_trading_fees(default_conf, mocker): + api_mock = MagicMock() + tick = { + '1INCH/USDT:USDT': { + 'info': {'user_id': '6266643', + 'taker_fee': '0.0018', + 'maker_fee': '0.0018', + 'gt_discount': False, + 'gt_taker_fee': '0', + 'gt_maker_fee': '0', + 'loan_fee': '0.18', + 'point_type': '1', + 'futures_taker_fee': '0.0005', + 'futures_maker_fee': '0'}, + 'symbol': '1INCH/USDT:USDT', + 'maker': 0.0, + 'taker': 0.0005}, + 'ETH/USDT:USDT': { + 'info': {'user_id': '6266643', + 'taker_fee': '0.0018', + 'maker_fee': '0.0018', + 'gt_discount': False, + 'gt_taker_fee': '0', + 'gt_maker_fee': '0', + 'loan_fee': '0.18', + 'point_type': '1', + 'futures_taker_fee': '0.0005', + 'futures_maker_fee': '0'}, + 'symbol': 'ETH/USDT:USDT', + 'maker': 0.0, + 'taker': 0.0005} + } + exchange_name = 'gateio' + default_conf['dry_run'] = False + default_conf['trading_mode'] = TradingMode.FUTURES + default_conf['margin_mode'] = MarginMode.ISOLATED + api_mock.fetch_trading_fees = MagicMock(return_value=tick) + mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) + exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) + # retrieve original ticker + tradingfees = exchange.fetch_trading_fees() + + assert '1INCH/USDT:USDT' in tradingfees + assert 'ETH/USDT:USDT' in tradingfees + assert api_mock.fetch_trading_fees.call_count == 1 + + api_mock.fetch_trading_fees.reset_mock() + + ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, + "fetch_trading_fees", "fetch_trading_fees") + + api_mock.fetch_trading_fees = MagicMock(return_value={}) + exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) + exchange.fetch_trading_fees() + mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) + assert exchange.fetch_trading_fees() == {} + + def test_fetch_bids_asks(default_conf, mocker): api_mock = MagicMock() tick = {'ETH/BTC': { From 9a8c24ddf3f199d05a15e0e011b8d85b4ea25e7b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 14:57:42 +0100 Subject: [PATCH 2/7] Update gateio to patch fees --- freqtrade/exchange/exchange.py | 4 ++++ freqtrade/exchange/gateio.py | 24 ++++++++++++++++++++++++ freqtrade/freqtradebot.py | 1 + tests/exchange/test_exchange.py | 6 ++---- 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 1d4fc8337..3a39f9300 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -75,6 +75,7 @@ class Exchange: "mark_ohlcv_price": "mark", "mark_ohlcv_timeframe": "8h", "ccxt_futures_name": "swap", + "needs_trading_fees": False, # use fetch_trading_fees to cache fees } _ft_has: Dict = {} _ft_has_futures: Dict = {} @@ -451,6 +452,9 @@ class Exchange: self._markets = self._api.load_markets() self._load_async_markets() self._last_markets_refresh = arrow.utcnow().int_timestamp + if self._ft_has['needs_trading_fees']: + self.trading_fees = self.fetch_trading_fees() + except ccxt.BaseError: logger.exception('Unable to initialize markets.') diff --git a/freqtrade/exchange/gateio.py b/freqtrade/exchange/gateio.py index 50ff0c872..726b5c7ed 100644 --- a/freqtrade/exchange/gateio.py +++ b/freqtrade/exchange/gateio.py @@ -27,6 +27,10 @@ class Gateio(Exchange): "stoploss_on_exchange": True, } + _ft_has_futures: Dict = { + "needs_trading_fees": True + } + _supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [ # TradingMode.SPOT always supported and not required in this list # (TradingMode.MARGIN, MarginMode.CROSS), @@ -42,6 +46,26 @@ class Gateio(Exchange): raise OperationalException( f'Exchange {self.name} does not support market orders.') + def fetch_order(self, order_id: str, pair: str, params={}) -> Dict: + order = super().fetch_order(order_id, pair, params) + + if self.trading_mode == TradingMode.FUTURES and order.get('fee') is None: + # Futures usually don't contain fees in the response. + # As such, futures orders on gateio will not contain a fee, which causes + # a repeated "update fee" cycle and wrong calculations. + # Therefore we patch the response with fees if it's not available. + # An alternative also contianing fees would be + # privateFuturesGetSettleAccountBook({"settle": "usdt"}) + + pair_fees = self.trading_fees.get(pair, {}) + if pair_fees and pair_fees['taker'] is not None: + order['fee'] = { + 'currency': self.get_pair_quote_currency(pair), + 'cost': abs(order['cost']) * pair_fees['taker'], + 'rate': pair_fees['taker'], + } + return order + def fetch_stoploss_order(self, order_id: str, pair: str, params={}) -> Dict: return self.fetch_order( order_id=order_id, diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 089a5804a..ebc129777 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1564,6 +1564,7 @@ class FreqtradeBot(LoggingMixin): if not order_obj: raise DependencyException( f"Order_obj not found for {order_id}. This should not have happened.") + self.handle_order_fee(trade, order_obj, order) trade.update_trade(order_obj) diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index d19baf39a..24ca47e8b 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -1663,11 +1663,9 @@ def test_fetch_trading_fees(default_conf, mocker): api_mock.fetch_trading_fees = MagicMock(return_value=tick) mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) - # retrieve original ticker - tradingfees = exchange.fetch_trading_fees() - assert '1INCH/USDT:USDT' in tradingfees - assert 'ETH/USDT:USDT' in tradingfees + assert '1INCH/USDT:USDT' in exchange.trading_fees + assert 'ETH/USDT:USDT' in exchange.trading_fees assert api_mock.fetch_trading_fees.call_count == 1 api_mock.fetch_trading_fees.reset_mock() From 9b8a2435f885b29a64dde0410c5db414869e60da Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 15:12:05 +0100 Subject: [PATCH 3/7] Add tests for fetch_order gateio patch --- tests/exchange/test_exchange.py | 4 ++-- tests/exchange/test_gateio.py | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 24ca47e8b..4f5aac199 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -1628,7 +1628,7 @@ def test_fetch_trading_fees(default_conf, mocker): api_mock = MagicMock() tick = { '1INCH/USDT:USDT': { - 'info': {'user_id': '6266643', + 'info': {'user_id': '', 'taker_fee': '0.0018', 'maker_fee': '0.0018', 'gt_discount': False, @@ -1642,7 +1642,7 @@ def test_fetch_trading_fees(default_conf, mocker): 'maker': 0.0, 'taker': 0.0005}, 'ETH/USDT:USDT': { - 'info': {'user_id': '6266643', + 'info': {'user_id': '', 'taker_fee': '0.0018', 'maker_fee': '0.0018', 'gt_discount': False, diff --git a/tests/exchange/test_gateio.py b/tests/exchange/test_gateio.py index 5a46e30a6..73a3b1623 100644 --- a/tests/exchange/test_gateio.py +++ b/tests/exchange/test_gateio.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock import pytest +from freqtrade.enums import MarginMode, TradingMode from freqtrade.exceptions import OperationalException from freqtrade.exchange import Gateio from freqtrade.resolvers.exchange_resolver import ExchangeResolver @@ -70,3 +71,40 @@ def test_stoploss_adjust_gateio(mocker, default_conf, sl1, sl2, sl3, side): } assert exchange.stoploss_adjust(sl1, order, side) assert not exchange.stoploss_adjust(sl2, order, side) + + +def test_fetch_order_gateio(mocker, default_conf): + tick = {'ETH/USDT:USDT': { + 'info': {'user_id': '', + 'taker_fee': '0.0018', + 'maker_fee': '0.0018', + 'gt_discount': False, + 'gt_taker_fee': '0', + 'gt_maker_fee': '0', + 'loan_fee': '0.18', + 'point_type': '1', + 'futures_taker_fee': '0.0005', + 'futures_maker_fee': '0'}, + 'symbol': 'ETH/USDT:USDT', + 'maker': 0.0, + 'taker': 0.0005} + } + default_conf['dry_run'] = False + default_conf['trading_mode'] = TradingMode.FUTURES + default_conf['margin_mode'] = MarginMode.ISOLATED + + api_mock = MagicMock() + api_mock.fetch_order = MagicMock(return_value={ + 'fee': None, + 'price': 3108.65, + 'cost': 0.310865, + 'amount': 1, # 1 contract + }) + exchange = get_patched_exchange(mocker, default_conf, api_mock=api_mock, id='gateio') + exchange.trading_fees = tick + order = exchange.fetch_order('22255', 'ETH/USDT:USDT') + + assert order['fee'] + assert order['fee']['rate'] == 0.0005 + assert order['fee']['currency'] == 'USDT' + assert order['fee']['cost'] == 0.0001554325 From f5578aba48f174190697ac63908b3d3993c3a10c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 15:15:16 +0100 Subject: [PATCH 4/7] Update trading_fee naming --- freqtrade/exchange/exchange.py | 3 ++- freqtrade/exchange/gateio.py | 2 +- tests/exchange/test_exchange.py | 4 ++-- tests/exchange/test_gateio.py | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 3a39f9300..67692cd27 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -93,6 +93,7 @@ class Exchange: self._api: ccxt.Exchange = None self._api_async: ccxt_async.Exchange = None self._markets: Dict = {} + self._trading_fees: Dict[str, Any] = {} self._leverage_tiers: Dict[str, List[Dict]] = {} self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) @@ -453,7 +454,7 @@ class Exchange: self._load_async_markets() self._last_markets_refresh = arrow.utcnow().int_timestamp if self._ft_has['needs_trading_fees']: - self.trading_fees = self.fetch_trading_fees() + self._trading_fees = self.fetch_trading_fees() except ccxt.BaseError: logger.exception('Unable to initialize markets.') diff --git a/freqtrade/exchange/gateio.py b/freqtrade/exchange/gateio.py index 726b5c7ed..23174bcd6 100644 --- a/freqtrade/exchange/gateio.py +++ b/freqtrade/exchange/gateio.py @@ -57,7 +57,7 @@ class Gateio(Exchange): # An alternative also contianing fees would be # privateFuturesGetSettleAccountBook({"settle": "usdt"}) - pair_fees = self.trading_fees.get(pair, {}) + pair_fees = self._trading_fees.get(pair, {}) if pair_fees and pair_fees['taker'] is not None: order['fee'] = { 'currency': self.get_pair_quote_currency(pair), diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 4f5aac199..5d16c3501 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -1664,8 +1664,8 @@ def test_fetch_trading_fees(default_conf, mocker): mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) - assert '1INCH/USDT:USDT' in exchange.trading_fees - assert 'ETH/USDT:USDT' in exchange.trading_fees + assert '1INCH/USDT:USDT' in exchange._trading_fees + assert 'ETH/USDT:USDT' in exchange._trading_fees assert api_mock.fetch_trading_fees.call_count == 1 api_mock.fetch_trading_fees.reset_mock() diff --git a/tests/exchange/test_gateio.py b/tests/exchange/test_gateio.py index 73a3b1623..9102d6704 100644 --- a/tests/exchange/test_gateio.py +++ b/tests/exchange/test_gateio.py @@ -101,7 +101,7 @@ def test_fetch_order_gateio(mocker, default_conf): 'amount': 1, # 1 contract }) exchange = get_patched_exchange(mocker, default_conf, api_mock=api_mock, id='gateio') - exchange.trading_fees = tick + exchange._trading_fees = tick order = exchange.fetch_order('22255', 'ETH/USDT:USDT') assert order['fee'] From f509959bd45b6dbe1ef569584cf7f7592b8b0743 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 16:19:29 +0100 Subject: [PATCH 5/7] Update --- freqtrade/exchange/gateio.py | 29 +++++++++++++++++------------ tests/exchange/test_gateio.py | 28 ++++++++++++++++++---------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/freqtrade/exchange/gateio.py b/freqtrade/exchange/gateio.py index 23174bcd6..656a1e30f 100644 --- a/freqtrade/exchange/gateio.py +++ b/freqtrade/exchange/gateio.py @@ -1,6 +1,7 @@ """ Gate.io exchange subclass """ import logging -from typing import Dict, List, Tuple +from datetime import datetime +from typing import Dict, List, Optional, Tuple from freqtrade.enums import MarginMode, TradingMode from freqtrade.exceptions import OperationalException @@ -46,25 +47,29 @@ class Gateio(Exchange): raise OperationalException( f'Exchange {self.name} does not support market orders.') - def fetch_order(self, order_id: str, pair: str, params={}) -> Dict: - order = super().fetch_order(order_id, pair, params) + def get_trades_for_order(self, order_id: str, pair: str, since: datetime, + params: Optional[Dict] = None) -> List: + trades = super().get_trades_for_order(order_id, pair, since, params) - if self.trading_mode == TradingMode.FUTURES and order.get('fee') is None: + if self.trading_mode == TradingMode.FUTURES: # Futures usually don't contain fees in the response. # As such, futures orders on gateio will not contain a fee, which causes # a repeated "update fee" cycle and wrong calculations. # Therefore we patch the response with fees if it's not available. # An alternative also contianing fees would be # privateFuturesGetSettleAccountBook({"settle": "usdt"}) - pair_fees = self._trading_fees.get(pair, {}) - if pair_fees and pair_fees['taker'] is not None: - order['fee'] = { - 'currency': self.get_pair_quote_currency(pair), - 'cost': abs(order['cost']) * pair_fees['taker'], - 'rate': pair_fees['taker'], - } - return order + if pair_fees: + for idx, trade in enumerate(trades): + if trade.get('fee', {}).get('cost') is None: + takerOrMaker = trade.get('takerOrMaker', 'taker') + if pair_fees.get(takerOrMaker) is not None: + trades[idx]['fee'] = { + 'currency': self.get_pair_quote_currency(pair), + 'cost': abs(trade['cost']) * pair_fees[takerOrMaker], + 'rate': pair_fees[takerOrMaker], + } + return trades def fetch_stoploss_order(self, order_id: str, pair: str, params={}) -> Dict: return self.fetch_order( diff --git a/tests/exchange/test_gateio.py b/tests/exchange/test_gateio.py index 9102d6704..c718c3838 100644 --- a/tests/exchange/test_gateio.py +++ b/tests/exchange/test_gateio.py @@ -1,3 +1,4 @@ +from datetime import datetime, timezone from unittest.mock import MagicMock import pytest @@ -72,8 +73,13 @@ def test_stoploss_adjust_gateio(mocker, default_conf, sl1, sl2, sl3, side): assert exchange.stoploss_adjust(sl1, order, side) assert not exchange.stoploss_adjust(sl2, order, side) +@pytest.mark.parametrize('takerormaker,rate,cost', [ + ('taker', 0.0005, 0.0001554325), + ('maker', 0.0, 0.0), -def test_fetch_order_gateio(mocker, default_conf): +]) +def test_fetch_my_trades_gateio(mocker, default_conf, takerormaker, rate, cost): + mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) tick = {'ETH/USDT:USDT': { 'info': {'user_id': '', 'taker_fee': '0.0018', @@ -94,17 +100,19 @@ def test_fetch_order_gateio(mocker, default_conf): default_conf['margin_mode'] = MarginMode.ISOLATED api_mock = MagicMock() - api_mock.fetch_order = MagicMock(return_value={ - 'fee': None, + api_mock.fetch_my_trades = MagicMock(return_value=[{ + 'fee': {'cost': None}, 'price': 3108.65, 'cost': 0.310865, + 'order': '22255', + 'takerOrMaker': takerormaker, 'amount': 1, # 1 contract - }) + }]) exchange = get_patched_exchange(mocker, default_conf, api_mock=api_mock, id='gateio') exchange._trading_fees = tick - order = exchange.fetch_order('22255', 'ETH/USDT:USDT') - - assert order['fee'] - assert order['fee']['rate'] == 0.0005 - assert order['fee']['currency'] == 'USDT' - assert order['fee']['cost'] == 0.0001554325 + trades = exchange.get_trades_for_order('22255', 'ETH/USDT:USDT', datetime.now(timezone.utc)) + trade = trades[0] + assert trade['fee'] + assert trade['fee']['rate'] == rate + assert trade['fee']['currency'] == 'USDT' + assert trade['fee']['cost'] == cost From d244391860f748d8195edde74615c47f3911939c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 26 Mar 2022 16:32:20 +0100 Subject: [PATCH 6/7] no need to "abs" cost will be fixed in ccxt --- freqtrade/exchange/gateio.py | 2 +- tests/exchange/test_gateio.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/exchange/gateio.py b/freqtrade/exchange/gateio.py index 656a1e30f..609cf4901 100644 --- a/freqtrade/exchange/gateio.py +++ b/freqtrade/exchange/gateio.py @@ -66,7 +66,7 @@ class Gateio(Exchange): if pair_fees.get(takerOrMaker) is not None: trades[idx]['fee'] = { 'currency': self.get_pair_quote_currency(pair), - 'cost': abs(trade['cost']) * pair_fees[takerOrMaker], + 'cost': trade['cost'] * pair_fees[takerOrMaker], 'rate': pair_fees[takerOrMaker], } return trades diff --git a/tests/exchange/test_gateio.py b/tests/exchange/test_gateio.py index c718c3838..ad30a7d86 100644 --- a/tests/exchange/test_gateio.py +++ b/tests/exchange/test_gateio.py @@ -73,10 +73,10 @@ def test_stoploss_adjust_gateio(mocker, default_conf, sl1, sl2, sl3, side): assert exchange.stoploss_adjust(sl1, order, side) assert not exchange.stoploss_adjust(sl2, order, side) + @pytest.mark.parametrize('takerormaker,rate,cost', [ ('taker', 0.0005, 0.0001554325), ('maker', 0.0, 0.0), - ]) def test_fetch_my_trades_gateio(mocker, default_conf, takerormaker, rate, cost): mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) From 0f1de435da4edbc45f2bbed32939e8677dea77ad Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 27 Mar 2022 08:28:44 +0200 Subject: [PATCH 7/7] Fix ccxt compat tests --- tests/exchange/test_ccxt_compat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/exchange/test_ccxt_compat.py b/tests/exchange/test_ccxt_compat.py index 5eb7e68d4..89b3bcc1f 100644 --- a/tests/exchange/test_ccxt_compat.py +++ b/tests/exchange/test_ccxt_compat.py @@ -134,7 +134,7 @@ def exchange_futures(request, exchange_conf, class_mocker): class_mocker.patch( 'freqtrade.exchange.binance.Binance.fill_leverage_tiers') - + class_mocker.patch('freqtrade.exchange.exchange.Exchange.fetch_trading_fees') exchange = ExchangeResolver.load_exchange(request.param, exchange_conf, validate=True) yield exchange, request.param