Replace datetime.utcnow with datetime.now(timezone.utc)

This commit is contained in:
Sam Germain 2021-09-29 22:16:44 -06:00
parent 545b62d746
commit c4ac876183
8 changed files with 34 additions and 32 deletions

View File

@ -594,7 +594,7 @@ class FreqtradeBot(LoggingMixin):
# Fee is applied twice because we make a LIMIT_BUY and LIMIT_SELL # Fee is applied twice because we make a LIMIT_BUY and LIMIT_SELL
fee = self.exchange.get_fee(symbol=pair, taker_or_maker='maker') fee = self.exchange.get_fee(symbol=pair, taker_or_maker='maker')
open_date = datetime.utcnow() open_date = datetime.now(timezone.utc)
if self.trading_mode == TradingMode.FUTURES: if self.trading_mode == TradingMode.FUTURES:
funding_fees = self.exchange.get_funding_fees_from_exchange(pair, open_date) funding_fees = self.exchange.get_funding_fees_from_exchange(pair, open_date)
else: else:
@ -610,7 +610,7 @@ class FreqtradeBot(LoggingMixin):
fee_close=fee, fee_close=fee,
open_rate=enter_limit_filled_price, open_rate=enter_limit_filled_price,
open_rate_requested=enter_limit_requested, open_rate_requested=enter_limit_requested,
open_date=datetime.utcnow(), open_date=datetime.now(timezone.utc),
exchange=self.exchange.id, exchange=self.exchange.id,
open_order_id=order_id, open_order_id=order_id,
strategy=self.strategy.get_strategy_name(), strategy=self.strategy.get_strategy_name(),
@ -652,7 +652,7 @@ class FreqtradeBot(LoggingMixin):
'stake_currency': self.config['stake_currency'], 'stake_currency': self.config['stake_currency'],
'fiat_currency': self.config.get('fiat_display_currency', None), 'fiat_currency': self.config.get('fiat_display_currency', None),
'amount': trade.amount, 'amount': trade.amount,
'open_date': trade.open_date or datetime.utcnow(), 'open_date': trade.open_date or datetime.now(timezone.utc),
'current_rate': trade.open_rate_requested, 'current_rate': trade.open_rate_requested,
} }
@ -848,7 +848,7 @@ class FreqtradeBot(LoggingMixin):
stop_price = trade.open_rate * (1 + stoploss) stop_price = trade.open_rate * (1 + stoploss)
if self.create_stoploss_order(trade=trade, stop_price=stop_price): if self.create_stoploss_order(trade=trade, stop_price=stop_price):
trade.stoploss_last_update = datetime.utcnow() trade.stoploss_last_update = datetime.now(timezone.utc)
return False return False
# If stoploss order is canceled for some reason we add it # 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): if self.exchange.stoploss_adjust(trade.stop_loss, order, side):
# we check if the update is necessary # we check if the update is necessary
update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60) update_beat = self.strategy.order_types.get('stoploss_on_exchange_interval', 60)
if (datetime.utcnow() - trade.stoploss_last_update).total_seconds() >= update_beat: if (datetime.now(timezone.utc) - trade.stoploss_last_update).total_seconds() >= update_beat:
# cancelling the current stoploss on exchange first # cancelling the current stoploss on exchange first
logger.info(f"Cancelling current stoploss on exchange for pair {trade.pair} " logger.info(f"Cancelling current stoploss on exchange for pair {trade.pair} "
f"(orderid:{order['id']}) in order to add another one ...") f"(orderid:{order['id']}) in order to add another one ...")
@ -1241,7 +1241,7 @@ class FreqtradeBot(LoggingMixin):
'profit_ratio': profit_ratio, 'profit_ratio': profit_ratio,
'sell_reason': trade.sell_reason, 'sell_reason': trade.sell_reason,
'open_date': trade.open_date, 'open_date': trade.open_date,
'close_date': trade.close_date or datetime.utcnow(), 'close_date': trade.close_date or datetime.now(timezone.utc),
'stake_currency': self.config['stake_currency'], 'stake_currency': self.config['stake_currency'],
'fiat_currency': self.config.get('fiat_display_currency', None), 'fiat_currency': self.config.get('fiat_display_currency', None),
} }

View File

@ -420,7 +420,7 @@ def get_default_conf(testdatadir):
@pytest.fixture @pytest.fixture
def update(): def update():
_update = Update(0) _update = Update(0)
_update.message = Message(0, datetime.utcnow(), Chat(0, 0)) _update.message = Message(0, datetime.now(timezone.utc)(), Chat(0, 0))
return _update return _update

View File

@ -22,8 +22,8 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool,
stake_amount=0.01, stake_amount=0.01,
fee_open=fee, fee_open=fee,
fee_close=fee, fee_close=fee,
open_date=datetime.utcnow() - timedelta(minutes=min_ago_open or 200), open_date=datetime.now(timezone.utc)() - timedelta(minutes=min_ago_open or 200),
close_date=datetime.utcnow() - timedelta(minutes=min_ago_close or 30), close_date=datetime.now(timezone.utc)() - timedelta(minutes=min_ago_close or 30),
open_rate=open_rate, open_rate=open_rate,
is_open=is_open, is_open=is_open,
amount=0.01 / open_rate, amount=0.01 / open_rate,
@ -45,9 +45,10 @@ def test_protectionmanager(mocker, default_conf):
for handler in freqtrade.protections._protection_handlers: for handler in freqtrade.protections._protection_handlers:
assert handler.name in constants.AVAILABLE_PROTECTIONS assert handler.name in constants.AVAILABLE_PROTECTIONS
if not handler.has_global_stop: if not handler.has_global_stop:
assert handler.global_stop(datetime.utcnow()) == (False, None, None) assert handler.global_stop(datetime.now(timezone.utc)()) == (False, None, None)
if not handler.has_local_stop: if not handler.has_local_stop:
assert handler.stop_per_pair('XRP/BTC', datetime.utcnow()) == (False, None, None) assert handler.stop_per_pair(
'XRP/BTC', datetime.now(timezone.utc)()) == (False, None, None)
@pytest.mark.parametrize('timeframe,expected,protconf', [ @pytest.mark.parametrize('timeframe,expected,protconf', [

View File

@ -265,7 +265,7 @@ def test_rpc_daily_profit(default_conf, update, ticker, fee,
# Simulate buy & sell # Simulate buy & sell
trade.update(limit_buy_order) trade.update(limit_buy_order)
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
# Try valid data # Try valid data
@ -282,7 +282,7 @@ def test_rpc_daily_profit(default_conf, update, ticker, fee,
assert (day['fiat_value'] == 0.0 or assert (day['fiat_value'] == 0.0 or
day['fiat_value'] == 0.76748865) day['fiat_value'] == 0.76748865)
# ensure first day is current date # ensure first day is current date
assert str(days['data'][0]['date']) == str(datetime.utcnow().date()) assert str(days['data'][0]['date']) == str(datetime.now(timezone.utc)().date())
# Try invalid data # Try invalid data
with pytest.raises(RPCException, match=r'.*must be an integer greater than 0*'): 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 fetch_ticker=ticker_sell_up
) )
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
freqtradebot.enter_positions() freqtradebot.enter_positions()
@ -423,7 +423,7 @@ def test_rpc_trade_statistics(default_conf, ticker, ticker_sell_up, fee,
fetch_ticker=ticker_sell_up fetch_ticker=ticker_sell_up
) )
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
stats = rpc._rpc_trade_statistics(stake_currency, fiat_display_currency) 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 get_fee=fee
) )
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
for trade in Trade.query.order_by(Trade.id).all(): 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 # Simulate fulfilled LIMIT_SELL order for trade
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
res = rpc._rpc_performance() res = rpc._rpc_performance()
assert len(res) == 1 assert len(res) == 1

View File

@ -546,7 +546,7 @@ def test_api_daily(botclient, mocker, ticker, fee, markets):
assert len(rc.json()['data']) == 7 assert len(rc.json()['data']) == 7
assert rc.json()['stake_currency'] == 'BTC' assert rc.json()['stake_currency'] == 'BTC'
assert rc.json()['fiat_display_currency'] == 'USD' assert rc.json()['fiat_display_currency'] == 'USD'
assert rc.json()['data'][0]['date'] == str(datetime.utcnow().date()) assert rc.json()['data'][0]['date'] == str(datetime.now(timezone.utc)().date())
def test_api_trades(botclient, mocker, fee, markets): def test_api_trades(botclient, mocker, fee, markets):
@ -983,7 +983,7 @@ def test_api_forcebuy(botclient, mocker, fee):
stake_amount=1, stake_amount=1,
open_rate=0.245441, open_rate=0.245441,
open_order_id="123456", open_order_id="123456",
open_date=datetime.utcnow(), open_date=datetime.now(timezone.utc)(),
is_open=False, is_open=False,
fee_close=fee.return_value, fee_close=fee.return_value,
fee_open=fee.return_value, fee_open=fee.return_value,

View File

@ -33,6 +33,7 @@ class DummyCls(Telegram):
""" """
Dummy class for testing the Telegram @authorized_only decorator Dummy class for testing the Telegram @authorized_only decorator
""" """
def __init__(self, rpc: RPC, config) -> None: def __init__(self, rpc: RPC, config) -> None:
super().__init__(rpc, config) super().__init__(rpc, config)
self.state = {'called': False} self.state = {'called': False}
@ -132,7 +133,7 @@ def test_authorized_only_unauthorized(default_conf, mocker, caplog) -> None:
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
chat = Chat(0xdeadbeef, 0) chat = Chat(0xdeadbeef, 0)
update = Update(randint(1, 100)) update = Update(randint(1, 100))
update.message = Message(randint(1, 100), datetime.utcnow(), chat) update.message = Message(randint(1, 100), datetime.now(timezone.utc)(), chat)
default_conf['telegram']['enabled'] = False default_conf['telegram']['enabled'] = False
bot = FreqtradeBot(default_conf) bot = FreqtradeBot(default_conf)
@ -343,7 +344,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
# Simulate fulfilled LIMIT_SELL order for trade # Simulate fulfilled LIMIT_SELL order for trade
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
# Try valid data # Try valid data
@ -353,7 +354,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
telegram._daily(update=update, context=context) telegram._daily(update=update, context=context)
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert 'Daily' in msg_mock.call_args_list[0][0][0] assert 'Daily' 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(datetime.now(timezone.utc)().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.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(' 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] assert str(' 1 trade') in msg_mock.call_args_list[0][0][0]
@ -365,7 +366,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
telegram._daily(update=update, context=context) telegram._daily(update=update, context=context)
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert 'Daily' in msg_mock.call_args_list[0][0][0] assert 'Daily' 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(datetime.now(timezone.utc)().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.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(' 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] assert str(' 1 trade') in msg_mock.call_args_list[0][0][0]
@ -382,7 +383,7 @@ def test_daily_handle(default_conf, update, ticker, limit_buy_order, fee,
for trade in trades: for trade in trades:
trade.update(limit_buy_order) trade.update(limit_buy_order)
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
# /daily 1 # /daily 1
@ -462,7 +463,7 @@ def test_profit_handle(default_conf, update, ticker, ticker_sell_up, fee,
mocker.patch('freqtrade.exchange.Exchange.fetch_ticker', ticker_sell_up) mocker.patch('freqtrade.exchange.Exchange.fetch_ticker', ticker_sell_up)
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
telegram._profit(update=update, context=MagicMock()) telegram._profit(update=update, context=MagicMock())
@ -966,7 +967,7 @@ def test_performance_handle(default_conf, update, ticker, fee,
# Simulate fulfilled LIMIT_SELL order for trade # Simulate fulfilled LIMIT_SELL order for trade
trade.update(limit_sell_order) trade.update(limit_sell_order)
trade.close_date = datetime.utcnow() trade.close_date = datetime.now(timezone.utc)()
trade.is_open = False trade.is_open = False
telegram._performance(update=update, context=MagicMock()) telegram._performance(update=update, context=MagicMock())
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
@ -997,9 +998,9 @@ def test_count_handle(default_conf, update, ticker, fee, mocker) -> None:
msg = ('<pre> current max total stake\n--------- ----- -------------\n' msg = ('<pre> current max total stake\n--------- ----- -------------\n'
' 1 {} {}</pre>').format( ' 1 {} {}</pre>').format(
default_conf['max_open_trades'], default_conf['max_open_trades'],
default_conf['stake_amount'] default_conf['stake_amount']
) )
assert msg in msg_mock.call_args_list[0][0][0] assert msg in msg_mock.call_args_list[0][0][0]

View File

@ -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, assert strategy.confirm_trade_entry(pair='ETH/BTC', order_type='limit', amount=0.1,
rate=20000, time_in_force='gtc', rate=20000, time_in_force='gtc',
current_time=datetime.utcnow(), side='long') is True current_time=datetime.now(timezone.utc)(), side='long') is True
assert strategy.confirm_trade_exit(pair='ETH/BTC', trade=trade, order_type='limit', amount=0.1, 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', rate=20000, time_in_force='gtc', sell_reason='roi',
current_time=datetime.utcnow()) is True current_time=datetime.now(timezone.utc)()) is True
# TODO-lev: Test for shorts? # TODO-lev: Test for shorts?
assert strategy.custom_stoploss(pair='ETH/BTC', trade=trade, current_time=datetime.now(), assert strategy.custom_stoploss(pair='ETH/BTC', trade=trade, current_time=datetime.now(),

View File

@ -255,7 +255,7 @@ def test_interest(market_buy_order_usdt, fee, exchange, is_short, lev, minutes,
stake_amount=20.0, stake_amount=20.0,
amount=30.0, amount=30.0,
open_rate=2.0, open_rate=2.0,
open_date=datetime.utcnow() - timedelta(minutes=minutes), open_date=datetime.now(timezone.utc)() - timedelta(minutes=minutes),
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
exchange=exchange, exchange=exchange,