refactor: tests - update timezone.utc to UTC

This commit is contained in:
Matthias
2025-07-04 09:01:13 +02:00
parent 79f0271720
commit deb8bde078
19 changed files with 145 additions and 145 deletions

View File

@@ -4,7 +4,7 @@ import logging
import platform import platform
import re import re
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, Mock, PropertyMock from unittest.mock import MagicMock, Mock, PropertyMock
@@ -126,7 +126,7 @@ def get_args(args):
def generate_trades_history(n_rows, start_date: datetime | None = None, days=5): def generate_trades_history(n_rows, start_date: datetime | None = None, days=5):
np.random.seed(42) np.random.seed(42)
if not start_date: if not start_date:
start_date = datetime(2020, 1, 1, tzinfo=timezone.utc) start_date = datetime(2020, 1, 1, tzinfo=UTC)
# Generate random data # Generate random data
end_date = start_date + timedelta(days=days) end_date = start_date + timedelta(days=days)

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from freqtrade.persistence.models import Order, Trade from freqtrade.persistence.models import Order, Trade
@@ -43,7 +43,7 @@ def mock_trade_1(fee, is_short: bool):
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
is_open=True, is_open=True,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=17), open_date=datetime.now(tz=UTC) - timedelta(minutes=17),
open_rate=0.123, open_rate=0.123,
exchange="binance", exchange="binance",
strategy="StrategyTestV3", strategy="StrategyTestV3",
@@ -106,8 +106,8 @@ def mock_trade_2(fee, is_short: bool):
timeframe=5, timeframe=5,
enter_tag="TEST1", enter_tag="TEST1",
exit_reason="sell_signal", exit_reason="sell_signal",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=UTC) - timedelta(minutes=20),
close_date=datetime.now(tz=timezone.utc) - timedelta(minutes=2), close_date=datetime.now(tz=UTC) - timedelta(minutes=2),
is_short=is_short, is_short=is_short,
) )
o = Order.parse_from_ccxt_object(mock_order_2(is_short), "ETC/BTC", entry_side(is_short)) o = Order.parse_from_ccxt_object(mock_order_2(is_short), "ETC/BTC", entry_side(is_short))
@@ -168,8 +168,8 @@ def mock_trade_3(fee, is_short: bool):
strategy="StrategyTestV3", strategy="StrategyTestV3",
timeframe=5, timeframe=5,
exit_reason="roi", exit_reason="roi",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=UTC) - timedelta(minutes=20),
close_date=datetime.now(tz=timezone.utc), close_date=datetime.now(tz=UTC),
is_short=is_short, is_short=is_short,
) )
o = Order.parse_from_ccxt_object(mock_order_3(is_short), "XRP/BTC", entry_side(is_short)) o = Order.parse_from_ccxt_object(mock_order_3(is_short), "XRP/BTC", entry_side(is_short))
@@ -205,7 +205,7 @@ def mock_trade_4(fee, is_short: bool):
amount_requested=124.0, amount_requested=124.0,
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=14), open_date=datetime.now(tz=UTC) - timedelta(minutes=14),
is_open=True, is_open=True,
open_rate=0.123, open_rate=0.123,
exchange="binance", exchange="binance",
@@ -260,7 +260,7 @@ def mock_trade_5(fee, is_short: bool):
amount_requested=124.0, amount_requested=124.0,
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=12), open_date=datetime.now(tz=UTC) - timedelta(minutes=12),
is_open=True, is_open=True,
open_rate=0.123, open_rate=0.123,
exchange="binance", exchange="binance",
@@ -316,7 +316,7 @@ def mock_trade_6(fee, is_short: bool):
stake_amount=0.001, stake_amount=0.001,
amount=2.0, amount=2.0,
amount_requested=2.0, amount_requested=2.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=5), open_date=datetime.now(tz=UTC) - timedelta(minutes=5),
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
is_open=True, is_open=True,
@@ -410,7 +410,7 @@ def short_trade(fee):
strategy="DefaultStrategy", strategy="DefaultStrategy",
timeframe=5, timeframe=5,
exit_reason="sell_signal", exit_reason="sell_signal",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=UTC) - timedelta(minutes=20),
# close_date=datetime.now(tz=timezone.utc) - timedelta(minutes=2), # close_date=datetime.now(tz=timezone.utc) - timedelta(minutes=2),
is_short=True, is_short=True,
) )
@@ -500,8 +500,8 @@ def leverage_trade(fee):
strategy="DefaultStrategy", strategy="DefaultStrategy",
timeframe=5, timeframe=5,
exit_reason="sell_signal", exit_reason="sell_signal",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=300), open_date=datetime.now(tz=UTC) - timedelta(minutes=300),
close_date=datetime.now(tz=timezone.utc), close_date=datetime.now(tz=UTC),
interest_rate=0.0005, interest_rate=0.0005,
) )
o = Order.parse_from_ccxt_object(leverage_order(), "DOGE/BTC", "sell") o = Order.parse_from_ccxt_object(leverage_order(), "DOGE/BTC", "sell")

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from freqtrade.persistence.models import Order, Trade from freqtrade.persistence.models import Order, Trade
@@ -55,8 +55,8 @@ def mock_trade_usdt_1(fee, is_short: bool):
stake_amount=20.0, stake_amount=20.0,
amount=2.0, amount=2.0,
amount_requested=2.0, amount_requested=2.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(days=2, minutes=20), open_date=datetime.now(tz=UTC) - timedelta(days=2, minutes=20),
close_date=datetime.now(tz=timezone.utc) - timedelta(days=2, minutes=5), close_date=datetime.now(tz=UTC) - timedelta(days=2, minutes=5),
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
is_open=False, is_open=False,
@@ -127,8 +127,8 @@ def mock_trade_usdt_2(fee, is_short: bool):
timeframe=5, timeframe=5,
enter_tag="TEST1", enter_tag="TEST1",
exit_reason="exit_signal", exit_reason="exit_signal",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=UTC) - timedelta(minutes=20),
close_date=datetime.now(tz=timezone.utc) - timedelta(minutes=2), close_date=datetime.now(tz=UTC) - timedelta(minutes=2),
is_short=is_short, is_short=is_short,
) )
o = Order.parse_from_ccxt_object(mock_order_usdt_2(is_short), "NEO/USDT", entry_side(is_short)) o = Order.parse_from_ccxt_object(mock_order_usdt_2(is_short), "NEO/USDT", entry_side(is_short))
@@ -190,8 +190,8 @@ def mock_trade_usdt_3(fee, is_short: bool):
timeframe=5, timeframe=5,
enter_tag="TEST3", enter_tag="TEST3",
exit_reason="roi", exit_reason="roi",
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=UTC) - timedelta(minutes=20),
close_date=datetime.now(tz=timezone.utc), close_date=datetime.now(tz=UTC),
is_short=is_short, is_short=is_short,
) )
o = Order.parse_from_ccxt_object(mock_order_usdt_3(is_short), "XRP/USDT", entry_side(is_short)) o = Order.parse_from_ccxt_object(mock_order_usdt_3(is_short), "XRP/USDT", entry_side(is_short))
@@ -228,7 +228,7 @@ def mock_trade_usdt_4(fee, is_short: bool):
amount_requested=10.01, amount_requested=10.01,
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=14), open_date=datetime.now(tz=UTC) - timedelta(minutes=14),
is_open=True, is_open=True,
open_rate=2.0, open_rate=2.0,
exchange="binance", exchange="binance",
@@ -280,7 +280,7 @@ def mock_trade_usdt_5(fee, is_short: bool):
amount_requested=10.01, amount_requested=10.01,
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=12), open_date=datetime.now(tz=UTC) - timedelta(minutes=12),
is_open=True, is_open=True,
open_rate=2.0, open_rate=2.0,
exchange="binance", exchange="binance",
@@ -332,7 +332,7 @@ def mock_trade_usdt_6(fee, is_short: bool):
stake_amount=20.0, stake_amount=20.0,
amount=2.0, amount=2.0,
amount_requested=2.0, amount_requested=2.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=5), open_date=datetime.now(tz=UTC) - timedelta(minutes=5),
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
is_open=True, is_open=True,
@@ -374,7 +374,7 @@ def mock_trade_usdt_7(fee, is_short: bool):
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
is_open=True, is_open=True,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=17), open_date=datetime.now(tz=UTC) - timedelta(minutes=17),
open_rate=2.0, open_rate=2.0,
exchange="binance", exchange="binance",
strategy="StrategyTestV2", strategy="StrategyTestV2",

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock from unittest.mock import MagicMock
from zipfile import ZipFile from zipfile import ZipFile
@@ -182,19 +182,19 @@ def test_extract_trades_of_period(testdatadir):
"profit_abs": [0.0, 1, -2, -5], "profit_abs": [0.0, 1, -2, -5],
"open_date": to_datetime( "open_date": to_datetime(
[ [
datetime(2017, 11, 13, 15, 40, 0, tzinfo=timezone.utc), datetime(2017, 11, 13, 15, 40, 0, tzinfo=UTC),
datetime(2017, 11, 14, 9, 41, 0, tzinfo=timezone.utc), datetime(2017, 11, 14, 9, 41, 0, tzinfo=UTC),
datetime(2017, 11, 14, 14, 20, 0, tzinfo=timezone.utc), datetime(2017, 11, 14, 14, 20, 0, tzinfo=UTC),
datetime(2017, 11, 15, 3, 40, 0, tzinfo=timezone.utc), datetime(2017, 11, 15, 3, 40, 0, tzinfo=UTC),
], ],
utc=True, utc=True,
), ),
"close_date": to_datetime( "close_date": to_datetime(
[ [
datetime(2017, 11, 13, 16, 40, 0, tzinfo=timezone.utc), datetime(2017, 11, 13, 16, 40, 0, tzinfo=UTC),
datetime(2017, 11, 14, 10, 41, 0, tzinfo=timezone.utc), datetime(2017, 11, 14, 10, 41, 0, tzinfo=UTC),
datetime(2017, 11, 14, 15, 25, 0, tzinfo=timezone.utc), datetime(2017, 11, 14, 15, 25, 0, tzinfo=UTC),
datetime(2017, 11, 15, 3, 55, 0, tzinfo=timezone.utc), datetime(2017, 11, 15, 3, 55, 0, tzinfo=UTC),
], ],
utc=True, utc=True,
), ),
@@ -203,10 +203,10 @@ def test_extract_trades_of_period(testdatadir):
trades1 = extract_trades_of_period(data, trades) trades1 = extract_trades_of_period(data, trades)
# First and last trade are dropped as they are out of range # First and last trade are dropped as they are out of range
assert len(trades1) == 2 assert len(trades1) == 2
assert trades1.iloc[0].open_date == datetime(2017, 11, 14, 9, 41, 0, tzinfo=timezone.utc) assert trades1.iloc[0].open_date == datetime(2017, 11, 14, 9, 41, 0, tzinfo=UTC)
assert trades1.iloc[0].close_date == datetime(2017, 11, 14, 10, 41, 0, tzinfo=timezone.utc) assert trades1.iloc[0].close_date == datetime(2017, 11, 14, 10, 41, 0, tzinfo=UTC)
assert trades1.iloc[-1].open_date == datetime(2017, 11, 14, 14, 20, 0, tzinfo=timezone.utc) assert trades1.iloc[-1].open_date == datetime(2017, 11, 14, 14, 20, 0, tzinfo=UTC)
assert trades1.iloc[-1].close_date == datetime(2017, 11, 14, 15, 25, 0, tzinfo=timezone.utc) assert trades1.iloc[-1].close_date == datetime(2017, 11, 14, 15, 25, 0, tzinfo=UTC)
def test_analyze_trade_parallelism(testdatadir): def test_analyze_trade_parallelism(testdatadir):
@@ -293,7 +293,7 @@ def test_combined_dataframes_with_rel_mean(testdatadir):
pairs = ["ETH/BTC", "ADA/BTC"] pairs = ["ETH/BTC", "ADA/BTC"]
data = load_data(datadir=testdatadir, pairs=pairs, timeframe="5m") data = load_data(datadir=testdatadir, pairs=pairs, timeframe="5m")
df = combined_dataframes_with_rel_mean( df = combined_dataframes_with_rel_mean(
data, datetime(2018, 1, 12, tzinfo=timezone.utc), datetime(2018, 1, 28, tzinfo=timezone.utc) data, datetime(2018, 1, 12, tzinfo=UTC), datetime(2018, 1, 28, tzinfo=UTC)
) )
assert isinstance(df, DataFrame) assert isinstance(df, DataFrame)
assert "ETH/BTC" not in df.columns assert "ETH/BTC" not in df.columns
@@ -596,7 +596,7 @@ def test_calculate_max_drawdown_abs(profits, relative, highd, lowdays, result, r
[1000, 500, 1000, 11000, 10000] # absolute results [1000, 500, 1000, 11000, 10000] # absolute results
[1000, 50%, 0%, 0%, ~9%] # Relative drawdowns [1000, 50%, 0%, 0%, ~9%] # Relative drawdowns
""" """
init_date = datetime(2020, 1, 1, tzinfo=timezone.utc) init_date = datetime(2020, 1, 1, tzinfo=UTC)
dates = [init_date + timedelta(days=i) for i in range(len(profits))] dates = [init_date + timedelta(days=i) for i in range(len(profits))]
df = DataFrame(zip(profits, dates, strict=False), columns=["profit_abs", "open_date"]) df = DataFrame(zip(profits, dates, strict=False), columns=["profit_abs", "open_date"])
# sort by profit and reset index # sort by profit and reset index

View File

@@ -1,7 +1,7 @@
# pragma pylint: disable=missing-docstring, protected-access, C0103 # pragma pylint: disable=missing-docstring, protected-access, C0103
import re import re
from datetime import datetime, timezone from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock from unittest.mock import MagicMock
@@ -165,19 +165,19 @@ def test_datahandler_ohlcv_data_min_max(testdatadir):
# Empty pair # Empty pair
min_max = dh.ohlcv_data_min_max("UNITTEST/BTC", "8m", "spot") min_max = dh.ohlcv_data_min_max("UNITTEST/BTC", "8m", "spot")
assert len(min_max) == 3 assert len(min_max) == 3
assert min_max[0] == datetime.fromtimestamp(0, tz=timezone.utc) assert min_max[0] == datetime.fromtimestamp(0, tz=UTC)
assert min_max[0] == min_max[1] assert min_max[0] == min_max[1]
# Empty pair2 # Empty pair2
min_max = dh.ohlcv_data_min_max("NOPAIR/XXX", "41m", "spot") min_max = dh.ohlcv_data_min_max("NOPAIR/XXX", "41m", "spot")
assert len(min_max) == 3 assert len(min_max) == 3
assert min_max[0] == datetime.fromtimestamp(0, tz=timezone.utc) assert min_max[0] == datetime.fromtimestamp(0, tz=UTC)
assert min_max[0] == min_max[1] assert min_max[0] == min_max[1]
# Existing pair ... # Existing pair ...
min_max = dh.ohlcv_data_min_max("UNITTEST/BTC", "1m", "spot") min_max = dh.ohlcv_data_min_max("UNITTEST/BTC", "1m", "spot")
assert len(min_max) == 3 assert len(min_max) == 3
assert min_max[0] == datetime(2017, 11, 4, 23, 2, tzinfo=timezone.utc) assert min_max[0] == datetime(2017, 11, 4, 23, 2, tzinfo=UTC)
assert min_max[1] == datetime(2017, 11, 14, 22, 59, tzinfo=timezone.utc) assert min_max[1] == datetime(2017, 11, 14, 22, 59, tzinfo=UTC)
def test_datahandler__check_empty_df(testdatadir, caplog): def test_datahandler__check_empty_df(testdatadir, caplog):
@@ -467,14 +467,14 @@ def test_datahandler_trades_data_min_max(testdatadir):
# Empty pair # Empty pair
min_max = dh.trades_data_min_max("NADA/ETH", TradingMode.SPOT) min_max = dh.trades_data_min_max("NADA/ETH", TradingMode.SPOT)
assert len(min_max) == 3 assert len(min_max) == 3
assert min_max[0] == datetime.fromtimestamp(0, tz=timezone.utc) assert min_max[0] == datetime.fromtimestamp(0, tz=UTC)
assert min_max[0] == min_max[1] assert min_max[0] == min_max[1]
# Existing pair ... # Existing pair ...
min_max = dh.trades_data_min_max("XRP/ETH", TradingMode.SPOT) min_max = dh.trades_data_min_max("XRP/ETH", TradingMode.SPOT)
assert len(min_max) == 3 assert len(min_max) == 3
assert min_max[0] == datetime(2019, 10, 11, 0, 0, 11, 620000, tzinfo=timezone.utc) assert min_max[0] == datetime(2019, 10, 11, 0, 0, 11, 620000, tzinfo=UTC)
assert min_max[1] == datetime(2019, 10, 13, 11, 19, 28, 844000, tzinfo=timezone.utc) assert min_max[1] == datetime(2019, 10, 13, 11, 19, 28, 844000, tzinfo=UTC)
def test_gethandlerclass(): def test_gethandlerclass():

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@@ -222,8 +222,8 @@ def test_get_producer_df(default_conf):
timeframe = default_conf["timeframe"] timeframe = default_conf["timeframe"]
candle_type = CandleType.SPOT candle_type = CandleType.SPOT
empty_la = datetime.fromtimestamp(0, tz=timezone.utc) empty_la = datetime.fromtimestamp(0, tz=UTC)
now = datetime.now(timezone.utc) now = datetime.now(UTC)
# no data has been added, any request should return an empty dataframe # no data has been added, any request should return an empty dataframe
dataframe, la = dataprovider.get_producer_df(pair, timeframe, candle_type) dataframe, la = dataprovider.get_producer_df(pair, timeframe, candle_type)
@@ -404,7 +404,7 @@ def test_get_analyzed_dataframe(mocker, default_conf, ohlcv_history):
dataframe, time = dp.get_analyzed_dataframe("NOTHING/BTC", timeframe) dataframe, time = dp.get_analyzed_dataframe("NOTHING/BTC", timeframe)
assert dataframe.empty assert dataframe.empty
assert isinstance(time, datetime) assert isinstance(time, datetime)
assert time == datetime(1970, 1, 1, tzinfo=timezone.utc) assert time == datetime(1970, 1, 1, tzinfo=UTC)
# Test backtest mode # Test backtest mode
default_conf["runmode"] = RunMode.BACKTEST default_conf["runmode"] = RunMode.BACKTEST
@@ -478,7 +478,7 @@ def test_dp__add_external_df(default_conf_usdt):
default_conf_usdt["timeframe"] = timeframe default_conf_usdt["timeframe"] = timeframe
dp = DataProvider(default_conf_usdt, None) dp = DataProvider(default_conf_usdt, None)
df = generate_test_data(timeframe, 24, "2022-01-01 00:00:00+00:00") df = generate_test_data(timeframe, 24, "2022-01-01 00:00:00+00:00")
last_analyzed = datetime.now(timezone.utc) last_analyzed = datetime.now(UTC)
res = dp._add_external_df("ETH/USDT", df, last_analyzed, timeframe, CandleType.SPOT) res = dp._add_external_df("ETH/USDT", df, last_analyzed, timeframe, CandleType.SPOT)
assert res[0] is False assert res[0] is False

View File

@@ -1,6 +1,6 @@
# pragma pylint: disable=missing-docstring, C0103 # pragma pylint: disable=missing-docstring, C0103
from datetime import timezone from datetime import UTC
import pandas as pd import pandas as pd
from numpy import nan from numpy import nan
@@ -16,15 +16,15 @@ def test_get_tick_size_over_time():
# Create test dataframe with different levels of precision # Create test dataframe with different levels of precision
data = { data = {
"date": [ "date": [
Timestamp("2020-01-01 00:00:00", tz=timezone.utc), Timestamp("2020-01-01 00:00:00", tz=UTC),
Timestamp("2020-01-02 00:00:00", tz=timezone.utc), Timestamp("2020-01-02 00:00:00", tz=UTC),
Timestamp("2020-01-03 00:00:00", tz=timezone.utc), Timestamp("2020-01-03 00:00:00", tz=UTC),
Timestamp("2020-01-15 00:00:00", tz=timezone.utc), Timestamp("2020-01-15 00:00:00", tz=UTC),
Timestamp("2020-01-16 00:00:00", tz=timezone.utc), Timestamp("2020-01-16 00:00:00", tz=UTC),
Timestamp("2020-01-31 00:00:00", tz=timezone.utc), Timestamp("2020-01-31 00:00:00", tz=UTC),
Timestamp("2020-02-01 00:00:00", tz=timezone.utc), Timestamp("2020-02-01 00:00:00", tz=UTC),
Timestamp("2020-02-15 00:00:00", tz=timezone.utc), Timestamp("2020-02-15 00:00:00", tz=UTC),
Timestamp("2020-03-15 00:00:00", tz=timezone.utc), Timestamp("2020-03-15 00:00:00", tz=UTC),
], ],
"open": [1.23456, 1.234, 1.23, 1.2, 1.23456, 1.234, 2.3456, 2.34, 2.34], "open": [1.23456, 1.234, 1.23, 1.2, 1.23456, 1.234, 2.3456, 2.34, 2.34],
"high": [1.23457, 1.235, 1.24, 1.3, 1.23456, 1.235, 2.3457, 2.34, 2.34], "high": [1.23457, 1.235, 1.24, 1.3, 1.23456, 1.235, 2.3457, 2.34, 2.34],

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
from shutil import copytree from shutil import copytree
from unittest.mock import PropertyMock from unittest.mock import PropertyMock
@@ -50,10 +50,10 @@ def test_import_kraken_trades_from_csv(testdatadir, tmp_path, caplog, default_co
assert len(trades) == 340 assert len(trades) == 340
assert trades["date"].min().to_pydatetime() == datetime( assert trades["date"].min().to_pydatetime() == datetime(
2023, 1, 1, 0, 3, 56, tzinfo=timezone.utc 2023, 1, 1, 0, 3, 56, tzinfo=UTC
) )
assert trades["date"].max().to_pydatetime() == datetime( assert trades["date"].max().to_pydatetime() == datetime(
2023, 1, 2, 23, 17, 3, tzinfo=timezone.utc 2023, 1, 2, 23, 17, 3, tzinfo=UTC
) )
# ID is not filled # ID is not filled
assert len(trades.loc[trades["id"] != ""]) == 0 assert len(trades.loc[trades["id"] != ""]) == 0

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@@ -73,7 +73,7 @@ async def test_bybit_fetch_funding_rate(default_conf, mocker):
def test_bybit_get_funding_fees(default_conf, mocker): def test_bybit_get_funding_fees(default_conf, mocker):
now = datetime.now(timezone.utc) now = datetime.now(UTC)
exchange = get_patched_exchange(mocker, default_conf, exchange="bybit") exchange = get_patched_exchange(mocker, default_conf, exchange="bybit")
exchange._fetch_and_calculate_funding_fees = MagicMock() exchange._fetch_and_calculate_funding_fees = MagicMock()
exchange.get_funding_fees("BTC/USDT:USDT", 1, False, now) exchange.get_funding_fees("BTC/USDT:USDT", 1, False, now)
@@ -117,7 +117,7 @@ def test_bybit_fetch_orders(default_conf, mocker, limit_order):
return True return True
mocker.patch(f"{EXMS}.exchange_has", side_effect=exchange_has) mocker.patch(f"{EXMS}.exchange_has", side_effect=exchange_has)
start_time = datetime.now(timezone.utc) - timedelta(days=20) start_time = datetime.now(UTC) - timedelta(days=20)
exchange = get_patched_exchange(mocker, default_conf, api_mock, exchange="bybit") exchange = get_patched_exchange(mocker, default_conf, api_mock, exchange="bybit")
# Not available in dry-run # Not available in dry-run

View File

@@ -1,7 +1,7 @@
import copy import copy
import logging import logging
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from random import randint from random import randint
from unittest.mock import MagicMock, Mock, PropertyMock, patch from unittest.mock import MagicMock, Mock, PropertyMock, patch
@@ -1728,7 +1728,7 @@ def test_fetch_orders(default_conf, mocker, exchange_name, limit_order):
api_mock.fetch_closed_orders = MagicMock(return_value=[limit_order["buy"]]) api_mock.fetch_closed_orders = MagicMock(return_value=[limit_order["buy"]])
mocker.patch(f"{EXMS}.exchange_has", return_value=True) mocker.patch(f"{EXMS}.exchange_has", return_value=True)
start_time = datetime.now(timezone.utc) - timedelta(days=20) start_time = datetime.now(UTC) - timedelta(days=20)
expected = 1 expected = 1
if exchange_name == "bybit": if exchange_name == "bybit":
expected = 3 expected = 3
@@ -2106,7 +2106,7 @@ def test___now_is_time_to_refresh(default_conf, mocker, exchange_name, time_mach
exchange = get_patched_exchange(mocker, default_conf, exchange=exchange_name) exchange = get_patched_exchange(mocker, default_conf, exchange=exchange_name)
pair = "BTC/USDT" pair = "BTC/USDT"
candle_type = CandleType.SPOT candle_type = CandleType.SPOT
start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=timezone.utc) start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=UTC)
time_machine.move_to(start_dt, tick=False) time_machine.move_to(start_dt, tick=False)
assert (pair, "5m", candle_type) not in exchange._pairs_last_refresh_time assert (pair, "5m", candle_type) not in exchange._pairs_last_refresh_time
@@ -2129,7 +2129,7 @@ def test___now_is_time_to_refresh(default_conf, mocker, exchange_name, time_mach
assert exchange._now_is_time_to_refresh(pair, "5m", candle_type) is True assert exchange._now_is_time_to_refresh(pair, "5m", candle_type) is True
# Test with 1d data # Test with 1d data
start_day_dt = datetime(2023, 12, 1, 0, 0, 0, tzinfo=timezone.utc) start_day_dt = datetime(2023, 12, 1, 0, 0, 0, tzinfo=UTC)
last_closed_candle_1d = dt_ts(start_day_dt - timedelta(days=1)) last_closed_candle_1d = dt_ts(start_day_dt - timedelta(days=1))
exchange._pairs_last_refresh_time[(pair, "1d", candle_type)] = last_closed_candle_1d exchange._pairs_last_refresh_time[(pair, "1d", candle_type)] = last_closed_candle_1d
@@ -2197,7 +2197,7 @@ def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name, candle_
async def test__async_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name, candle_type): async def test__async_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name, candle_type):
ohlcv = [ ohlcv = [
[ [
int((datetime.now(timezone.utc).timestamp() - 1000) * 1000), int((datetime.now(UTC).timestamp() - 1000) * 1000),
1, # open 1, # open
2, # high 2, # high
3, # low 3, # low
@@ -2501,7 +2501,7 @@ def test_refresh_latest_trades(
@pytest.mark.parametrize("candle_type", [CandleType.FUTURES, CandleType.MARK, CandleType.SPOT]) @pytest.mark.parametrize("candle_type", [CandleType.FUTURES, CandleType.MARK, CandleType.SPOT])
def test_refresh_latest_ohlcv_cache(mocker, default_conf, candle_type, time_machine) -> None: def test_refresh_latest_ohlcv_cache(mocker, default_conf, candle_type, time_machine) -> None:
start = datetime(2021, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc) start = datetime(2021, 8, 1, 0, 0, 0, 0, tzinfo=UTC)
ohlcv = generate_test_data_raw("1h", 100, start.strftime("%Y-%m-%d")) ohlcv = generate_test_data_raw("1h", 100, start.strftime("%Y-%m-%d"))
time_machine.move_to(start + timedelta(hours=99, minutes=30)) time_machine.move_to(start + timedelta(hours=99, minutes=30))
@@ -2595,7 +2595,7 @@ def test_refresh_latest_ohlcv_cache(mocker, default_conf, candle_type, time_mach
def test_refresh_ohlcv_with_cache(mocker, default_conf, time_machine) -> None: def test_refresh_ohlcv_with_cache(mocker, default_conf, time_machine) -> None:
start = datetime(2021, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc) start = datetime(2021, 8, 1, 0, 0, 0, 0, tzinfo=UTC)
ohlcv = generate_test_data_raw("1h", 100, start.strftime("%Y-%m-%d")) ohlcv = generate_test_data_raw("1h", 100, start.strftime("%Y-%m-%d"))
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
pairs = [ pairs = [
@@ -2903,7 +2903,7 @@ def test_get_entry_rate(
mocker, default_conf, caplog, side, ask, bid, last, last_ab, expected, time_machine mocker, default_conf, caplog, side, ask, bid, last, last_ab, expected, time_machine
) -> None: ) -> None:
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=timezone.utc) start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=UTC)
time_machine.move_to(start_dt, tick=False) time_machine.move_to(start_dt, tick=False)
if last_ab is None: if last_ab is None:
del default_conf["entry_pricing"]["price_last_balance"] del default_conf["entry_pricing"]["price_last_balance"]
@@ -2940,7 +2940,7 @@ def test_get_exit_rate(
default_conf, mocker, caplog, side, bid, ask, last, last_ab, expected, time_machine default_conf, mocker, caplog, side, bid, ask, last, last_ab, expected, time_machine
) -> None: ) -> None:
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=timezone.utc) start_dt = datetime(2023, 12, 1, 0, 10, 0, tzinfo=UTC)
time_machine.move_to(start_dt, tick=False) time_machine.move_to(start_dt, tick=False)
default_conf["exit_pricing"]["price_side"] = side default_conf["exit_pricing"]["price_side"] = side
@@ -4019,7 +4019,7 @@ def test_get_trades_for_order(default_conf, mocker, exchange_name, trading_mode,
assert api_mock.fetch_my_trades.call_args[0][1] == 1525478395000 assert api_mock.fetch_my_trades.call_args[0][1] == 1525478395000
assert ( assert (
api_mock.fetch_my_trades.call_args[0][1] api_mock.fetch_my_trades.call_args[0][1]
== int(since.replace(tzinfo=timezone.utc).timestamp() - 5) * 1000 == int(since.replace(tzinfo=UTC).timestamp() - 5) * 1000
) )
ccxt_exceptionhandlers( ccxt_exceptionhandlers(
@@ -4785,7 +4785,7 @@ def test_calculate_backoff(retrycount, max_retries, expected):
@pytest.mark.parametrize("exchange_name", EXCHANGES) @pytest.mark.parametrize("exchange_name", EXCHANGES)
def test_get_funding_fees(default_conf_usdt, mocker, exchange_name, caplog): def test_get_funding_fees(default_conf_usdt, mocker, exchange_name, caplog):
now = datetime.now(timezone.utc) now = datetime.now(UTC)
default_conf_usdt["trading_mode"] = "futures" default_conf_usdt["trading_mode"] = "futures"
default_conf_usdt["margin_mode"] = "isolated" default_conf_usdt["margin_mode"] = "isolated"
exchange = get_patched_exchange(mocker, default_conf_usdt, exchange=exchange_name) exchange = get_patched_exchange(mocker, default_conf_usdt, exchange=exchange_name)
@@ -5002,8 +5002,8 @@ def test_calculate_funding_fees(
): ):
exchange = get_patched_exchange(mocker, default_conf) exchange = get_patched_exchange(mocker, default_conf)
kraken = get_patched_exchange(mocker, default_conf, exchange="kraken") kraken = get_patched_exchange(mocker, default_conf, exchange="kraken")
prior_date = timeframe_to_prev_date("1h", datetime.now(timezone.utc) - timedelta(hours=1)) prior_date = timeframe_to_prev_date("1h", datetime.now(UTC) - timedelta(hours=1))
trade_date = timeframe_to_prev_date("1h", datetime.now(timezone.utc)) trade_date = timeframe_to_prev_date("1h", datetime.now(UTC))
funding_rates = DataFrame( funding_rates = DataFrame(
[ [
{"date": prior_date, "open": funding_rate}, # Line not used. {"date": prior_date, "open": funding_rate}, # Line not used.
@@ -5072,9 +5072,9 @@ def test_combine_funding_and_mark(
futures_funding_rate, futures_funding_rate,
): ):
exchange = get_patched_exchange(mocker, default_conf) exchange = get_patched_exchange(mocker, default_conf)
prior2_date = timeframe_to_prev_date("1h", datetime.now(timezone.utc) - timedelta(hours=2)) prior2_date = timeframe_to_prev_date("1h", datetime.now(UTC) - timedelta(hours=2))
prior_date = timeframe_to_prev_date("1h", datetime.now(timezone.utc) - timedelta(hours=1)) prior_date = timeframe_to_prev_date("1h", datetime.now(UTC) - timedelta(hours=1))
trade_date = timeframe_to_prev_date("1h", datetime.now(timezone.utc)) trade_date = timeframe_to_prev_date("1h", datetime.now(UTC))
funding_rates = DataFrame( funding_rates = DataFrame(
[ [
{"date": prior2_date, "open": funding_rate}, {"date": prior2_date, "open": funding_rate},

View File

@@ -1,5 +1,5 @@
# pragma pylint: disable=missing-docstring, protected-access, invalid-name # pragma pylint: disable=missing-docstring, protected-access, invalid-name
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from math import isnan, nan from math import isnan, nan
import pytest import pytest
@@ -117,7 +117,7 @@ def test_check_exchange(default_conf, caplog) -> None:
def test_date_minus_candles(): def test_date_minus_candles():
date = datetime(2019, 8, 12, 13, 25, 0, tzinfo=timezone.utc) date = datetime(2019, 8, 12, 13, 25, 0, tzinfo=UTC)
assert date_minus_candles("5m", 3, date) == date - timedelta(minutes=15) assert date_minus_candles("5m", 3, date) == date - timedelta(minutes=15)
assert date_minus_candles("5m", 5, date) == date - timedelta(minutes=25) assert date_minus_candles("5m", 5, date) == date - timedelta(minutes=25)
@@ -167,59 +167,59 @@ def test_timeframe_to_resample_freq(timeframe, expected):
def test_timeframe_to_prev_date(): def test_timeframe_to_prev_date():
# 2019-08-12 13:22:08 # 2019-08-12 13:22:08
date = datetime.fromtimestamp(1565616128, tz=timezone.utc) date = datetime.fromtimestamp(1565616128, tz=UTC)
tf_list = [ tf_list = [
# 5m -> 2019-08-12 13:20:00 # 5m -> 2019-08-12 13:20:00
("5m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc)), ("5m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=UTC)),
# 10m -> 2019-08-12 13:20:00 # 10m -> 2019-08-12 13:20:00
("10m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc)), ("10m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=UTC)),
# 1h -> 2019-08-12 13:00:00 # 1h -> 2019-08-12 13:00:00
("1h", datetime(2019, 8, 12, 13, 00, 0, tzinfo=timezone.utc)), ("1h", datetime(2019, 8, 12, 13, 00, 0, tzinfo=UTC)),
# 2h -> 2019-08-12 12:00:00 # 2h -> 2019-08-12 12:00:00
("2h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=timezone.utc)), ("2h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=UTC)),
# 4h -> 2019-08-12 12:00:00 # 4h -> 2019-08-12 12:00:00
("4h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=timezone.utc)), ("4h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=UTC)),
# 1d -> 2019-08-12 00:00:00 # 1d -> 2019-08-12 00:00:00
("1d", datetime(2019, 8, 12, 00, 00, 0, tzinfo=timezone.utc)), ("1d", datetime(2019, 8, 12, 00, 00, 0, tzinfo=UTC)),
] ]
for interval, result in tf_list: for interval, result in tf_list:
assert timeframe_to_prev_date(interval, date) == result assert timeframe_to_prev_date(interval, date) == result
date = datetime.now(tz=timezone.utc) date = datetime.now(tz=UTC)
assert timeframe_to_prev_date("5m") < date assert timeframe_to_prev_date("5m") < date
# Does not round # Does not round
time = datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc) time = datetime(2019, 8, 12, 13, 20, 0, tzinfo=UTC)
assert timeframe_to_prev_date("5m", time) == time assert timeframe_to_prev_date("5m", time) == time
time = datetime(2019, 8, 12, 13, 0, 0, tzinfo=timezone.utc) time = datetime(2019, 8, 12, 13, 0, 0, tzinfo=UTC)
assert timeframe_to_prev_date("1h", time) == time assert timeframe_to_prev_date("1h", time) == time
def test_timeframe_to_next_date(): def test_timeframe_to_next_date():
# 2019-08-12 13:22:08 # 2019-08-12 13:22:08
date = datetime.fromtimestamp(1565616128, tz=timezone.utc) date = datetime.fromtimestamp(1565616128, tz=UTC)
tf_list = [ tf_list = [
# 5m -> 2019-08-12 13:25:00 # 5m -> 2019-08-12 13:25:00
("5m", datetime(2019, 8, 12, 13, 25, 0, tzinfo=timezone.utc)), ("5m", datetime(2019, 8, 12, 13, 25, 0, tzinfo=UTC)),
# 10m -> 2019-08-12 13:30:00 # 10m -> 2019-08-12 13:30:00
("10m", datetime(2019, 8, 12, 13, 30, 0, tzinfo=timezone.utc)), ("10m", datetime(2019, 8, 12, 13, 30, 0, tzinfo=UTC)),
# 1h -> 2019-08-12 14:00:00 # 1h -> 2019-08-12 14:00:00
("1h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=timezone.utc)), ("1h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=UTC)),
# 2h -> 2019-08-12 14:00:00 # 2h -> 2019-08-12 14:00:00
("2h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=timezone.utc)), ("2h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=UTC)),
# 4h -> 2019-08-12 14:00:00 # 4h -> 2019-08-12 14:00:00
("4h", datetime(2019, 8, 12, 16, 00, 0, tzinfo=timezone.utc)), ("4h", datetime(2019, 8, 12, 16, 00, 0, tzinfo=UTC)),
# 1d -> 2019-08-13 00:00:00 # 1d -> 2019-08-13 00:00:00
("1d", datetime(2019, 8, 13, 0, 0, 0, tzinfo=timezone.utc)), ("1d", datetime(2019, 8, 13, 0, 0, 0, tzinfo=UTC)),
] ]
for interval, result in tf_list: for interval, result in tf_list:
assert timeframe_to_next_date(interval, date) == result assert timeframe_to_next_date(interval, date) == result
date = datetime.now(tz=timezone.utc) date = datetime.now(tz=UTC)
assert timeframe_to_next_date("5m") > date assert timeframe_to_next_date("5m") > date
date = datetime(2019, 8, 12, 13, 30, 0, tzinfo=timezone.utc) date = datetime(2019, 8, 12, 13, 30, 0, tzinfo=UTC)
assert timeframe_to_next_date("5m", date) == date + timedelta(minutes=5) assert timeframe_to_next_date("5m", date) == date + timedelta(minutes=5)

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@@ -113,7 +113,7 @@ def test_fetch_my_trades_gate(mocker, default_conf, takerormaker, rate, cost):
) )
exchange = get_patched_exchange(mocker, default_conf, api_mock=api_mock, exchange="gate") exchange = get_patched_exchange(mocker, default_conf, api_mock=api_mock, exchange="gate")
exchange._trading_fees = tick exchange._trading_fees = tick
trades = exchange.get_trades_for_order("22255", "ETH/USDT:USDT", datetime.now(timezone.utc)) trades = exchange.get_trades_for_order("22255", "ETH/USDT:USDT", datetime.now(UTC))
trade = trades[0] trade = trades[0]
assert trade["fee"] assert trade["fee"]
assert trade["fee"]["rate"] == rate assert trade["fee"]["rate"] == rate

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import MagicMock, PropertyMock from unittest.mock import MagicMock, PropertyMock
import pytest import pytest
@@ -306,7 +306,7 @@ def test_hyperliquid_dry_run_liquidation_price(default_conf, mocker):
def test_hyperliquid_get_funding_fees(default_conf, mocker): def test_hyperliquid_get_funding_fees(default_conf, mocker):
now = datetime.now(timezone.utc) now = datetime.now(UTC)
exchange = get_patched_exchange(mocker, default_conf, exchange="hyperliquid") exchange = get_patched_exchange(mocker, default_conf, exchange="hyperliquid")
exchange._fetch_and_calculate_funding_fees = MagicMock() exchange._fetch_and_calculate_funding_fees = MagicMock()
exchange.get_funding_fees("BTC/USDC:USDC", 1, False, now) exchange.get_funding_fees("BTC/USDC:USDC", 1, False, now)

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, MagicMock, PropertyMock from unittest.mock import AsyncMock, MagicMock, PropertyMock
import ccxt import ccxt
@@ -15,7 +15,7 @@ from tests.exchange.test_exchange import ccxt_exceptionhandlers
def test_okx_ohlcv_candle_limit(default_conf, mocker): def test_okx_ohlcv_candle_limit(default_conf, mocker):
exchange = get_patched_exchange(mocker, default_conf, exchange="okx") exchange = get_patched_exchange(mocker, default_conf, exchange="okx")
timeframes = ("1m", "5m", "1h") timeframes = ("1m", "5m", "1h")
start_time = int(datetime(2021, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) start_time = int(datetime(2021, 1, 1, tzinfo=UTC).timestamp() * 1000)
for timeframe in timeframes: for timeframe in timeframes:
assert exchange.ohlcv_candle_limit(timeframe, CandleType.SPOT) == 300 assert exchange.ohlcv_candle_limit(timeframe, CandleType.SPOT) == 300
@@ -29,7 +29,7 @@ def test_okx_ohlcv_candle_limit(default_conf, mocker):
assert exchange.ohlcv_candle_limit(timeframe, CandleType.FUNDING_RATE, start_time) == 100 assert exchange.ohlcv_candle_limit(timeframe, CandleType.FUNDING_RATE, start_time) == 100
one_call = int( one_call = int(
( (
datetime.now(timezone.utc) datetime.now(UTC)
- timedelta(minutes=290 * timeframe_to_minutes(timeframe)) - timedelta(minutes=290 * timeframe_to_minutes(timeframe))
).timestamp() ).timestamp()
* 1000 * 1000
@@ -40,7 +40,7 @@ def test_okx_ohlcv_candle_limit(default_conf, mocker):
one_call = int( one_call = int(
( (
datetime.now(timezone.utc) datetime.now(UTC)
- timedelta(minutes=320 * timeframe_to_minutes(timeframe)) - timedelta(minutes=320 * timeframe_to_minutes(timeframe))
).timestamp() ).timestamp()
* 1000 * 1000
@@ -693,7 +693,7 @@ def test_fetch_orders_okx(default_conf, mocker, limit_order):
api_mock.fetch_closed_orders = MagicMock(return_value=[limit_order["buy"]]) api_mock.fetch_closed_orders = MagicMock(return_value=[limit_order["buy"]])
mocker.patch(f"{EXMS}.exchange_has", return_value=True) mocker.patch(f"{EXMS}.exchange_has", return_value=True)
start_time = datetime.now(timezone.utc) - timedelta(days=20) start_time = datetime.now(UTC) - timedelta(days=20)
exchange = get_patched_exchange(mocker, default_conf, api_mock, exchange="okx") exchange = get_patched_exchange(mocker, default_conf, api_mock, exchange="okx")
# Not available in dry-run # Not available in dry-run
@@ -727,7 +727,7 @@ def test_fetch_orders_okx(default_conf, mocker, limit_order):
api_mock.fetch_closed_orders.reset_mock() api_mock.fetch_closed_orders.reset_mock()
# regular closed_orders endpoint only has history for 7 days. # regular closed_orders endpoint only has history for 7 days.
exchange.fetch_orders("mocked", datetime.now(timezone.utc) - timedelta(days=6)) exchange.fetch_orders("mocked", datetime.now(UTC) - timedelta(days=6))
assert api_mock.fetch_orders.call_count == 0 assert api_mock.fetch_orders.call_count == 0
assert api_mock.fetch_open_orders.call_count == 1 assert api_mock.fetch_open_orders.call_count == 1
assert api_mock.fetch_closed_orders.call_count == 1 assert api_mock.fetch_closed_orders.call_count == 1

View File

@@ -5,7 +5,7 @@ However, these tests should give a good idea to determine if a new exchange is
suitable to run with freqtrade. suitable to run with freqtrade.
""" """
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import pytest import pytest
@@ -248,7 +248,7 @@ class TestCCXTExchange:
len(exch.klines(pair_tf)) > exch.ohlcv_candle_limit(timeframe, CandleType.SPOT) * 0.90 len(exch.klines(pair_tf)) > exch.ohlcv_candle_limit(timeframe, CandleType.SPOT) * 0.90
) )
# Check if last-timeframe is within the last 2 intervals # Check if last-timeframe is within the last 2 intervals
now = datetime.now(timezone.utc) - timedelta(minutes=(timeframe_to_minutes(timeframe) * 2)) now = datetime.now(UTC) - timedelta(minutes=(timeframe_to_minutes(timeframe) * 2))
assert exch.klines(pair_tf).iloc[-1]["date"] >= timeframe_to_prev_date(timeframe, now) assert exch.klines(pair_tf).iloc[-1]["date"] >= timeframe_to_prev_date(timeframe, now)
def test_ccxt_fetch_ohlcv_startdate(self, exchange: EXCHANGE_FIXTURE_TYPE): def test_ccxt_fetch_ohlcv_startdate(self, exchange: EXCHANGE_FIXTURE_TYPE):
@@ -266,7 +266,7 @@ class TestCCXTExchange:
assert isinstance(ohlcv, dict) assert isinstance(ohlcv, dict)
assert len(ohlcv[pair_tf]) == len(exch.klines(pair_tf)) assert len(ohlcv[pair_tf]) == len(exch.klines(pair_tf))
# Check if last-timeframe is within the last 2 intervals # Check if last-timeframe is within the last 2 intervals
now = datetime.now(timezone.utc) - timedelta(minutes=(timeframe_to_minutes(timeframe) * 2)) now = datetime.now(UTC) - timedelta(minutes=(timeframe_to_minutes(timeframe) * 2))
assert exch.klines(pair_tf).iloc[-1]["date"] >= timeframe_to_prev_date(timeframe, now) assert exch.klines(pair_tf).iloc[-1]["date"] >= timeframe_to_prev_date(timeframe, now)
assert exch.klines(pair_tf)["date"].astype(int).iloc[0] // 1e6 == since_ms assert exch.klines(pair_tf)["date"].astype(int).iloc[0] // 1e6 == since_ms
@@ -274,7 +274,7 @@ class TestCCXTExchange:
self, exchange, exchangename, pair, timeframe, candle_type, factor=0.9 self, exchange, exchangename, pair, timeframe, candle_type, factor=0.9
): ):
timeframe_ms = timeframe_to_msecs(timeframe) timeframe_ms = timeframe_to_msecs(timeframe)
now = timeframe_to_prev_date(timeframe, datetime.now(timezone.utc)) now = timeframe_to_prev_date(timeframe, datetime.now(UTC))
for offset in (360, 120, 30, 10, 5, 2): for offset in (360, 120, 30, 10, 5, 2):
since = now - timedelta(days=offset) since = now - timedelta(days=offset)
since_ms = int(since.timestamp() * 1000) since_ms = int(since.timestamp() * 1000)
@@ -336,7 +336,7 @@ class TestCCXTExchange:
exchange, exchangename = exchange_futures exchange, exchangename = exchange_futures
pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"]) pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"])
since = int((datetime.now(timezone.utc) - timedelta(days=5)).timestamp() * 1000) since = int((datetime.now(UTC) - timedelta(days=5)).timestamp() * 1000)
timeframe_ff = exchange._ft_has.get( timeframe_ff = exchange._ft_has.get(
"funding_fee_timeframe", exchange._ft_has["mark_ohlcv_timeframe"] "funding_fee_timeframe", exchange._ft_has["mark_ohlcv_timeframe"]
) )
@@ -371,7 +371,7 @@ class TestCCXTExchange:
def test_ccxt_fetch_mark_price_history(self, exchange_futures: EXCHANGE_FIXTURE_TYPE): def test_ccxt_fetch_mark_price_history(self, exchange_futures: EXCHANGE_FIXTURE_TYPE):
exchange, exchangename = exchange_futures exchange, exchangename = exchange_futures
pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"]) pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"])
since = int((datetime.now(timezone.utc) - timedelta(days=5)).timestamp() * 1000) since = int((datetime.now(UTC) - timedelta(days=5)).timestamp() * 1000)
pair_tf = (pair, "1h", CandleType.MARK) pair_tf = (pair, "1h", CandleType.MARK)
mark_ohlcv = exchange.refresh_latest_ohlcv([pair_tf], since_ms=since, drop_incomplete=False) mark_ohlcv = exchange.refresh_latest_ohlcv([pair_tf], since_ms=since, drop_incomplete=False)
@@ -389,7 +389,7 @@ class TestCCXTExchange:
def test_ccxt__calculate_funding_fees(self, exchange_futures: EXCHANGE_FIXTURE_TYPE): def test_ccxt__calculate_funding_fees(self, exchange_futures: EXCHANGE_FIXTURE_TYPE):
exchange, exchangename = exchange_futures exchange, exchangename = exchange_futures
pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"]) pair = EXCHANGES[exchangename].get("futures_pair", EXCHANGES[exchangename]["pair"])
since = datetime.now(timezone.utc) - timedelta(days=5) since = datetime.now(UTC) - timedelta(days=5)
funding_fee = exchange._fetch_and_calculate_funding_fees( funding_fee = exchange._fetch_and_calculate_funding_fees(
pair, 20, is_short=False, open_date=since pair, 20, is_short=False, open_date=since
@@ -403,7 +403,7 @@ class TestCCXTExchange:
if not (lookback := EXCHANGES[exchangename].get("trades_lookback_hours")): if not (lookback := EXCHANGES[exchangename].get("trades_lookback_hours")):
pytest.skip("test_fetch_trades not enabled for this exchange") pytest.skip("test_fetch_trades not enabled for this exchange")
pair = EXCHANGES[exchangename]["pair"] pair = EXCHANGES[exchangename]["pair"]
since = int((datetime.now(timezone.utc) - timedelta(hours=lookback)).timestamp() * 1000) since = int((datetime.now(UTC) - timedelta(hours=lookback)).timestamp() * 1000)
res = exch.loop.run_until_complete(exch._async_get_trade_history(pair, since, None, None)) res = exch.loop.run_until_complete(exch._async_get_trade_history(pair, since, None, None))
assert len(res) == 2 assert len(res) == 2
res_pair, res_trades = res res_pair, res_trades = res

View File

@@ -1,5 +1,5 @@
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timezone from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from unittest.mock import PropertyMock from unittest.mock import PropertyMock
@@ -28,7 +28,7 @@ from tests.freqai.conftest import get_patched_freqai_strategy
def test_freqai_backtest_start_backtest_list(freqai_conf, mocker, testdatadir, caplog): def test_freqai_backtest_start_backtest_list(freqai_conf, mocker, testdatadir, caplog):
patch_exchange(mocker) patch_exchange(mocker)
now = datetime.now(timezone.utc) now = datetime.now(UTC)
mocker.patch( mocker.patch(
"freqtrade.plugins.pairlistmanager.PairListManager.whitelist", "freqtrade.plugins.pairlistmanager.PairListManager.whitelist",
PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]), PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]),
@@ -73,7 +73,7 @@ def test_freqai_backtest_load_data(
): ):
patch_exchange(mocker) patch_exchange(mocker)
now = datetime.now(timezone.utc) now = datetime.now(UTC)
mocker.patch( mocker.patch(
"freqtrade.plugins.pairlistmanager.PairListManager.whitelist", "freqtrade.plugins.pairlistmanager.PairListManager.whitelist",
PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]), PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]),
@@ -98,7 +98,7 @@ def test_freqai_backtest_load_data(
def test_freqai_backtest_live_models_model_not_found(freqai_conf, mocker, testdatadir, caplog): def test_freqai_backtest_live_models_model_not_found(freqai_conf, mocker, testdatadir, caplog):
patch_exchange(mocker) patch_exchange(mocker)
now = datetime.now(timezone.utc) now = datetime.now(UTC)
mocker.patch( mocker.patch(
"freqtrade.plugins.pairlistmanager.PairListManager.whitelist", "freqtrade.plugins.pairlistmanager.PairListManager.whitelist",
PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]), PropertyMock(return_value=["HULUMULU/USDT", "XRP/USDT"]),
@@ -163,6 +163,6 @@ def test_freqai_backtest_consistent_timerange(mocker, freqai_conf):
backtesting = Backtesting(deepcopy(freqai_conf)) backtesting = Backtesting(deepcopy(freqai_conf))
backtesting.start() backtesting.start()
assert gbs.call_args[1]["min_date"] == datetime(2021, 11, 20, 0, 0, tzinfo=timezone.utc) assert gbs.call_args[1]["min_date"] == datetime(2021, 11, 20, 0, 0, tzinfo=UTC)
assert gbs.call_args[1]["max_date"] == datetime(2021, 11, 21, 0, 0, tzinfo=timezone.utc) assert gbs.call_args[1]["max_date"] == datetime(2021, 11, 21, 0, 0, tzinfo=UTC)
Backtesting.cleanup() Backtesting.cleanup()

View File

@@ -1,5 +1,5 @@
import shutil import shutil
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock from unittest.mock import MagicMock
@@ -67,9 +67,9 @@ def test_split_timerange(
def test_check_if_model_expired(mocker, freqai_conf): def test_check_if_model_expired(mocker, freqai_conf):
dk = get_patched_data_kitchen(mocker, freqai_conf) dk = get_patched_data_kitchen(mocker, freqai_conf)
now = datetime.now(tz=timezone.utc).timestamp() now = datetime.now(tz=UTC).timestamp()
assert dk.check_if_model_expired(now) is False assert dk.check_if_model_expired(now) is False
now = (datetime.now(tz=timezone.utc) - timedelta(hours=2)).timestamp() now = (datetime.now(tz=UTC) - timedelta(hours=2)).timestamp()
assert dk.check_if_model_expired(now) is True assert dk.check_if_model_expired(now) is True
shutil.rmtree(Path(dk.full_path)) shutil.rmtree(Path(dk.full_path))

View File

@@ -3,7 +3,7 @@
import random import random
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import ANY, MagicMock, PropertyMock from unittest.mock import ANY, MagicMock, PropertyMock
@@ -687,7 +687,7 @@ def test_backtest__check_trade_exit(default_conf, mocker) -> None:
backtesting._set_strategy(backtesting.strategylist[0]) backtesting._set_strategy(backtesting.strategylist[0])
pair = "UNITTEST/BTC" pair = "UNITTEST/BTC"
row = [ row = [
pd.Timestamp(year=2020, month=1, day=1, hour=4, minute=55, tzinfo=timezone.utc), pd.Timestamp(year=2020, month=1, day=1, hour=4, minute=55, tzinfo=UTC),
200, # Open 200, # Open
201.5, # High 201.5, # High
195, # Low 195, # Low
@@ -705,7 +705,7 @@ def test_backtest__check_trade_exit(default_conf, mocker) -> None:
assert isinstance(trade, LocalTrade) assert isinstance(trade, LocalTrade)
row_sell = [ row_sell = [
pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0, tzinfo=timezone.utc), pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0, tzinfo=UTC),
200, # Open 200, # Open
210.5, # High 210.5, # High
195, # Low 195, # Low
@@ -723,7 +723,7 @@ def test_backtest__check_trade_exit(default_conf, mocker) -> None:
res = backtesting._check_trade_exit(trade, row_sell, row_sell[0].to_pydatetime()) res = backtesting._check_trade_exit(trade, row_sell, row_sell[0].to_pydatetime())
assert res is not None assert res is not None
assert res.exit_reason == ExitType.ROI.value assert res.exit_reason == ExitType.ROI.value
assert res.close_date_utc == datetime(2020, 1, 1, 5, 0, tzinfo=timezone.utc) assert res.close_date_utc == datetime(2020, 1, 1, 5, 0, tzinfo=UTC)
# Enter new trade # Enter new trade
trade = backtesting._enter_trade(pair, row=row, direction="long") trade = backtesting._enter_trade(pair, row=row, direction="long")
@@ -928,7 +928,7 @@ def test_backtest_one_detail(default_conf_usdt, mocker, testdatadir, use_detail)
assert len(t["orders"]) == 2 assert len(t["orders"]) == 2
entryo = t["orders"][0] entryo = t["orders"][0]
entry_ts = datetime.fromtimestamp(entryo["order_filled_timestamp"] // 1000, tz=timezone.utc) entry_ts = datetime.fromtimestamp(entryo["order_filled_timestamp"] // 1000, tz=UTC)
if entry_ts > t["open_date"]: if entry_ts > t["open_date"]:
late_entry += 1 late_entry += 1
@@ -1039,7 +1039,7 @@ def test_backtest_one_detail_futures(
assert len(t["orders"]) == 2 assert len(t["orders"]) == 2
entryo = t["orders"][0] entryo = t["orders"][0]
entry_ts = datetime.fromtimestamp(entryo["order_filled_timestamp"] // 1000, tz=timezone.utc) entry_ts = datetime.fromtimestamp(entryo["order_filled_timestamp"] // 1000, tz=UTC)
if entry_ts > t["open_date"]: if entry_ts > t["open_date"]:
late_entry += 1 late_entry += 1
@@ -1121,7 +1121,7 @@ def test_backtest_one_detail_futures_funding_fees(
return df return df
def adjust_trade_position(trade, current_time, **kwargs): def adjust_trade_position(trade, current_time, **kwargs):
if current_time > datetime(2021, 11, 18, 2, 0, 0, tzinfo=timezone.utc): if current_time > datetime(2021, 11, 18, 2, 0, 0, tzinfo=UTC):
return None return None
return default_conf_usdt["stake_amount"] return default_conf_usdt["stake_amount"]
@@ -2564,7 +2564,7 @@ def test_backtest_start_multi_strat_caching(
mocker.patch("freqtrade.optimize.backtesting.Backtesting.backtest", backtestmock) mocker.patch("freqtrade.optimize.backtesting.Backtesting.backtest", backtestmock)
mocker.patch("freqtrade.optimize.backtesting.show_backtest_results", MagicMock()) mocker.patch("freqtrade.optimize.backtesting.show_backtest_results", MagicMock())
now = min_backtest_date = datetime.now(tz=timezone.utc) now = min_backtest_date = datetime.now(tz=UTC)
start_time = now - timedelta(**start_delta) + timedelta(hours=1) start_time = now - timedelta(**start_delta) + timedelta(hours=1)
if cache == "none": if cache == "none":
min_backtest_date = now + timedelta(days=1) min_backtest_date = now + timedelta(days=1)

View File

@@ -1,5 +1,5 @@
# pragma pylint: disable=missing-docstring, C0103 # pragma pylint: disable=missing-docstring, C0103
from datetime import datetime, timezone from datetime import UTC, datetime
import pytest import pytest
@@ -29,8 +29,8 @@ def test_parse_timerange_incorrect():
assert TimeRange("date", "date", 1231006505, 1233360000) == timerange assert TimeRange("date", "date", 1231006505, 1233360000) == timerange
assert isinstance(timerange.startdt, datetime) assert isinstance(timerange.startdt, datetime)
assert isinstance(timerange.stopdt, datetime) assert isinstance(timerange.stopdt, datetime)
assert timerange.startdt == datetime.fromtimestamp(1231006505, tz=timezone.utc) assert timerange.startdt == datetime.fromtimestamp(1231006505, tz=UTC)
assert timerange.stopdt == datetime.fromtimestamp(1233360000, tz=timezone.utc) assert timerange.stopdt == datetime.fromtimestamp(1233360000, tz=UTC)
assert timerange.timerange_str == "20090103-20090131" assert timerange.timerange_str == "20090103-20090131"
timerange = TimeRange.parse_timerange("1231006505000-1233360000000") timerange = TimeRange.parse_timerange("1231006505000-1233360000000")
@@ -68,7 +68,7 @@ def test_subtract_start():
def test_adjust_start_if_necessary(): def test_adjust_start_if_necessary():
min_date = datetime(2017, 11, 14, 21, 15, 00, tzinfo=timezone.utc) min_date = datetime(2017, 11, 14, 21, 15, 00, tzinfo=UTC)
x = TimeRange("date", "date", 1510694100, 1510780500) x = TimeRange("date", "date", 1510694100, 1510780500)
# Adjust by 20 candles - min_date == startts # Adjust by 20 candles - min_date == startts