From af6afd0ac2dcfafa35c6bfcfe20a819e8196e497 Mon Sep 17 00:00:00 2001 From: Sam Germain Date: Wed, 29 Sep 2021 22:27:21 -0600 Subject: [PATCH] Revert "Replace datetime.utcnow with datetime.now(timezone.utc)" This reverts commit c4ac8761836032c5e2d4042ffbd3ed79d5e46b31. --- freqtrade/freqtradebot.py | 12 ++++++------ tests/conftest.py | 2 +- tests/plugins/test_protections.py | 9 ++++----- tests/rpc/test_rpc.py | 12 ++++++------ tests/rpc/test_rpc_apiserver.py | 4 ++-- tests/rpc/test_rpc_telegram.py | 21 ++++++++++----------- tests/strategy/test_default_strategy.py | 4 ++-- tests/test_persistence.py | 2 +- 8 files changed, 32 insertions(+), 34 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 59ddafb16..ebc91f97f 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -594,7 +594,7 @@ class FreqtradeBot(LoggingMixin): # Fee is applied twice because we make a LIMIT_BUY and LIMIT_SELL fee = self.exchange.get_fee(symbol=pair, taker_or_maker='maker') - open_date = datetime.now(timezone.utc) + open_date = datetime.utcnow() if self.trading_mode == TradingMode.FUTURES: funding_fees = self.exchange.get_funding_fees_from_exchange(pair, open_date) else: @@ -610,7 +610,7 @@ class FreqtradeBot(LoggingMixin): fee_close=fee, open_rate=enter_limit_filled_price, open_rate_requested=enter_limit_requested, - open_date=datetime.now(timezone.utc), + open_date=datetime.utcnow(), exchange=self.exchange.id, open_order_id=order_id, strategy=self.strategy.get_strategy_name(), @@ -652,7 +652,7 @@ class FreqtradeBot(LoggingMixin): 'stake_currency': self.config['stake_currency'], 'fiat_currency': self.config.get('fiat_display_currency', None), 'amount': trade.amount, - 'open_date': trade.open_date or datetime.now(timezone.utc), + 'open_date': trade.open_date or datetime.utcnow(), 'current_rate': trade.open_rate_requested, } @@ -848,7 +848,7 @@ class FreqtradeBot(LoggingMixin): stop_price = trade.open_rate * (1 + stoploss) if self.create_stoploss_order(trade=trade, stop_price=stop_price): - trade.stoploss_last_update = datetime.now(timezone.utc) + trade.stoploss_last_update = datetime.utcnow() return False # If stoploss order is canceled for some reason we add it @@ -885,7 +885,7 @@ class FreqtradeBot(LoggingMixin): if self.exchange.stoploss_adjust(trade.stop_loss, order, side): # we check if the update is necessary update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60) - if (datetime.now(timezone.utc) - trade.stoploss_last_update).total_seconds() >= update_beat: + if (datetime.utcnow() - trade.stoploss_last_update).total_seconds() >= update_beat: # cancelling the current stoploss on exchange first logger.info(f"Cancelling current stoploss on exchange for pair {trade.pair} " f"(orderid:{order['id']}) in order to add another one ...") @@ -1241,7 +1241,7 @@ class FreqtradeBot(LoggingMixin): 'profit_ratio': profit_ratio, 'sell_reason': trade.sell_reason, 'open_date': trade.open_date, - 'close_date': trade.close_date or datetime.now(timezone.utc), + 'close_date': trade.close_date or datetime.utcnow(), 'stake_currency': self.config['stake_currency'], 'fiat_currency': self.config.get('fiat_display_currency', None), } diff --git a/tests/conftest.py b/tests/conftest.py index 40f1e6e56..b35ff17d6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -420,7 +420,7 @@ def get_default_conf(testdatadir): @pytest.fixture def update(): _update = Update(0) - _update.message = Message(0, datetime.now(timezone.utc)(), Chat(0, 0)) + _update.message = Message(0, datetime.utcnow(), Chat(0, 0)) return _update diff --git a/tests/plugins/test_protections.py b/tests/plugins/test_protections.py index 19ed2915e..c0a9ae72a 100644 --- a/tests/plugins/test_protections.py +++ b/tests/plugins/test_protections.py @@ -22,8 +22,8 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool, stake_amount=0.01, fee_open=fee, fee_close=fee, - open_date=datetime.now(timezone.utc)() - timedelta(minutes=min_ago_open or 200), - close_date=datetime.now(timezone.utc)() - timedelta(minutes=min_ago_close or 30), + open_date=datetime.utcnow() - timedelta(minutes=min_ago_open or 200), + close_date=datetime.utcnow() - timedelta(minutes=min_ago_close or 30), open_rate=open_rate, is_open=is_open, amount=0.01 / open_rate, @@ -45,10 +45,9 @@ def test_protectionmanager(mocker, default_conf): for handler in freqtrade.protections._protection_handlers: assert handler.name in constants.AVAILABLE_PROTECTIONS if not handler.has_global_stop: - assert handler.global_stop(datetime.now(timezone.utc)()) == (False, None, None) + assert handler.global_stop(datetime.utcnow()) == (False, None, None) if not handler.has_local_stop: - assert handler.stop_per_pair( - 'XRP/BTC', datetime.now(timezone.utc)()) == (False, None, None) + assert handler.stop_per_pair('XRP/BTC', datetime.utcnow()) == (False, None, None) @pytest.mark.parametrize('timeframe,expected,protconf', [ diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index f195ce0b8..586fadff8 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -265,7 +265,7 @@ def test_rpc_daily_profit(default_conf, update, ticker, fee, # Simulate buy & sell trade.update(limit_buy_order) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False # Try valid data @@ -282,7 +282,7 @@ def test_rpc_daily_profit(default_conf, update, ticker, fee, assert (day['fiat_value'] == 0.0 or day['fiat_value'] == 0.76748865) # ensure first day is current date - assert str(days['data'][0]['date']) == str(datetime.now(timezone.utc)().date()) + assert str(days['data'][0]['date']) == str(datetime.utcnow().date()) # Try invalid data with pytest.raises(RPCException, match=r'.*must be an integer greater than 0*'): @@ -409,7 +409,7 @@ def test_rpc_trade_statistics(default_conf, ticker, ticker_sell_up, fee, fetch_ticker=ticker_sell_up ) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False freqtradebot.enter_positions() @@ -423,7 +423,7 @@ def test_rpc_trade_statistics(default_conf, ticker, ticker_sell_up, fee, fetch_ticker=ticker_sell_up ) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False stats = rpc._rpc_trade_statistics(stake_currency, fiat_display_currency) @@ -489,7 +489,7 @@ def test_rpc_trade_statistics_closed(mocker, default_conf, ticker, fee, get_fee=fee ) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False for trade in Trade.query.order_by(Trade.id).all(): @@ -831,7 +831,7 @@ def test_performance_handle(default_conf, ticker, limit_buy_order, fee, # Simulate fulfilled LIMIT_SELL order for trade trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False res = rpc._rpc_performance() assert len(res) == 1 diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 4ed679762..afce87b88 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -546,7 +546,7 @@ def test_api_daily(botclient, mocker, ticker, fee, markets): assert len(rc.json()['data']) == 7 assert rc.json()['stake_currency'] == 'BTC' assert rc.json()['fiat_display_currency'] == 'USD' - assert rc.json()['data'][0]['date'] == str(datetime.now(timezone.utc)().date()) + assert rc.json()['data'][0]['date'] == str(datetime.utcnow().date()) def test_api_trades(botclient, mocker, fee, markets): @@ -983,7 +983,7 @@ def test_api_forcebuy(botclient, mocker, fee): stake_amount=1, open_rate=0.245441, open_order_id="123456", - open_date=datetime.now(timezone.utc)(), + open_date=datetime.utcnow(), is_open=False, fee_close=fee.return_value, fee_open=fee.return_value, diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 9f5fe71ca..23ccadca0 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -33,7 +33,6 @@ class DummyCls(Telegram): """ Dummy class for testing the Telegram @authorized_only decorator """ - def __init__(self, rpc: RPC, config) -> None: super().__init__(rpc, config) self.state = {'called': False} @@ -133,7 +132,7 @@ def test_authorized_only_unauthorized(default_conf, mocker, caplog) -> None: caplog.set_level(logging.DEBUG) chat = Chat(0xdeadbeef, 0) update = Update(randint(1, 100)) - update.message = Message(randint(1, 100), datetime.now(timezone.utc)(), chat) + update.message = Message(randint(1, 100), datetime.utcnow(), chat) default_conf['telegram']['enabled'] = False bot = FreqtradeBot(default_conf) @@ -344,7 +343,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee, # Simulate fulfilled LIMIT_SELL order for trade trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False # Try valid data @@ -354,7 +353,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee, telegram._daily(update=update, context=context) assert msg_mock.call_count == 1 assert 'Daily' in msg_mock.call_args_list[0][0][0] - assert str(datetime.now(timezone.utc)().date()) in msg_mock.call_args_list[0][0][0] + assert str(datetime.utcnow().date()) in msg_mock.call_args_list[0][0][0] assert str(' 0.00006217 BTC') in msg_mock.call_args_list[0][0][0] assert str(' 0.933 USD') in msg_mock.call_args_list[0][0][0] assert str(' 1 trade') in msg_mock.call_args_list[0][0][0] @@ -366,7 +365,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee, telegram._daily(update=update, context=context) assert msg_mock.call_count == 1 assert 'Daily' in msg_mock.call_args_list[0][0][0] - assert str(datetime.now(timezone.utc)().date()) in msg_mock.call_args_list[0][0][0] + assert str(datetime.utcnow().date()) in msg_mock.call_args_list[0][0][0] assert str(' 0.00006217 BTC') in msg_mock.call_args_list[0][0][0] assert str(' 0.933 USD') in msg_mock.call_args_list[0][0][0] assert str(' 1 trade') in msg_mock.call_args_list[0][0][0] @@ -383,7 +382,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee, for trade in trades: trade.update(limit_buy_order) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False # /daily 1 @@ -463,7 +462,7 @@ def test_profit_handle(default_conf, update, ticker, ticker_sell_up, fee, mocker.patch('freqtrade.exchange.Exchange.fetch_ticker', ticker_sell_up) trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False telegram._profit(update=update, context=MagicMock()) @@ -967,7 +966,7 @@ def test_performance_handle(default_conf, update, ticker, fee, # Simulate fulfilled LIMIT_SELL order for trade trade.update(limit_sell_order) - trade.close_date = datetime.now(timezone.utc)() + trade.close_date = datetime.utcnow() trade.is_open = False telegram._performance(update=update, context=MagicMock()) assert msg_mock.call_count == 1 @@ -998,9 +997,9 @@ def test_count_handle(default_conf, update, ticker, fee, mocker) -> None: msg = ('
  current    max    total stake\n---------  -----  -------------\n'
            '        1      {}          {}
').format( - default_conf['max_open_trades'], - default_conf['stake_amount'] - ) + default_conf['max_open_trades'], + default_conf['stake_amount'] + ) assert msg in msg_mock.call_args_list[0][0][0] diff --git a/tests/strategy/test_default_strategy.py b/tests/strategy/test_default_strategy.py index 2d09590da..a995491f2 100644 --- a/tests/strategy/test_default_strategy.py +++ b/tests/strategy/test_default_strategy.py @@ -37,10 +37,10 @@ def test_strategy_test_v2(result, fee): assert strategy.confirm_trade_entry(pair='ETH/BTC', order_type='limit', amount=0.1, rate=20000, time_in_force='gtc', - current_time=datetime.now(timezone.utc)(), side='long') is True + current_time=datetime.utcnow(), side='long') is True assert strategy.confirm_trade_exit(pair='ETH/BTC', trade=trade, order_type='limit', amount=0.1, rate=20000, time_in_force='gtc', sell_reason='roi', - current_time=datetime.now(timezone.utc)()) is True + current_time=datetime.utcnow()) is True # TODO-lev: Test for shorts? assert strategy.custom_stoploss(pair='ETH/BTC', trade=trade, current_time=datetime.now(), diff --git a/tests/test_persistence.py b/tests/test_persistence.py index 0c077899d..58ce47ea7 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -255,7 +255,7 @@ def test_interest(market_buy_order_usdt, fee, exchange, is_short, lev, minutes, stake_amount=20.0, amount=30.0, open_rate=2.0, - open_date=datetime.now(timezone.utc)() - timedelta(minutes=minutes), + open_date=datetime.utcnow() - timedelta(minutes=minutes), fee_open=fee.return_value, fee_close=fee.return_value, exchange=exchange,