Merge branch 'develop' into github_actions_tests

This commit is contained in:
Matthias
2019-11-14 06:45:14 +01:00
76 changed files with 941 additions and 539 deletions

View File

@@ -252,6 +252,7 @@ def default_conf(testdatadir):
"db_url": "sqlite://",
"user_data_dir": Path("user_data"),
"verbosity": 3,
"strategy": "DefaultStrategy"
}
return configuration

View File

@@ -56,7 +56,7 @@ def test_extract_trades_of_period(testdatadir):
# 2018-11-14 06:07:00
timerange = TimeRange('date', None, 1510639620, 0)
data = load_pair_history(pair=pair, ticker_interval='1m',
data = load_pair_history(pair=pair, timeframe='1m',
datadir=testdatadir, timerange=timerange)
trades = DataFrame(
@@ -122,7 +122,7 @@ def test_combine_tickers_with_mean(testdatadir):
pairs = ["ETH/BTC", "ADA/BTC"]
tickers = load_data(datadir=testdatadir,
pairs=pairs,
ticker_interval='5m'
timeframe='5m'
)
df = combine_tickers_with_mean(tickers)
assert isinstance(df, DataFrame)
@@ -136,7 +136,7 @@ def test_create_cum_profit(testdatadir):
bt_data = load_backtest_data(filename)
timerange = TimeRange.parse_timerange("20180110-20180112")
df = load_pair_history(pair="TRX/BTC", ticker_interval='5m',
df = load_pair_history(pair="TRX/BTC", timeframe='5m',
datadir=testdatadir, timerange=timerange)
cum_profits = create_cum_profit(df.set_index('date'),
@@ -154,7 +154,7 @@ def test_create_cum_profit1(testdatadir):
bt_data.loc[:, 'close_time'] = bt_data.loc[:, 'close_time'] + DateOffset(seconds=20)
timerange = TimeRange.parse_timerange("20180110-20180112")
df = load_pair_history(pair="TRX/BTC", ticker_interval='5m',
df = load_pair_history(pair="TRX/BTC", timeframe='5m',
datadir=testdatadir, timerange=timerange)
cum_profits = create_cum_profit(df.set_index('date'),

View File

@@ -23,7 +23,7 @@ def test_parse_ticker_dataframe(ticker_history_list, caplog):
def test_ohlcv_fill_up_missing_data(testdatadir, caplog):
data = load_pair_history(datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
pair='UNITTEST/BTC',
fill_up_missing=False)
caplog.set_level(logging.DEBUG)
@@ -42,7 +42,7 @@ def test_ohlcv_fill_up_missing_data(testdatadir, caplog):
def test_ohlcv_fill_up_missing_data2(caplog):
ticker_interval = '5m'
timeframe = '5m'
ticks = [[
1511686200000, # 8:50:00
8.794e-05, # open
@@ -78,10 +78,10 @@ def test_ohlcv_fill_up_missing_data2(caplog):
]
# Generate test-data without filling missing
data = parse_ticker_dataframe(ticks, ticker_interval, pair="UNITTEST/BTC", fill_missing=False)
data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC", fill_missing=False)
assert len(data) == 3
caplog.set_level(logging.DEBUG)
data2 = ohlcv_fill_up_missing_data(data, ticker_interval, "UNITTEST/BTC")
data2 = ohlcv_fill_up_missing_data(data, timeframe, "UNITTEST/BTC")
assert len(data2) == 4
# 3rd candle has been filled
row = data2.loc[2, :]
@@ -99,7 +99,7 @@ def test_ohlcv_fill_up_missing_data2(caplog):
def test_ohlcv_drop_incomplete(caplog):
ticker_interval = '1d'
timeframe = '1d'
ticks = [[
1559750400000, # 2019-06-04
8.794e-05, # open
@@ -134,13 +134,13 @@ def test_ohlcv_drop_incomplete(caplog):
]
]
caplog.set_level(logging.DEBUG)
data = parse_ticker_dataframe(ticks, ticker_interval, pair="UNITTEST/BTC",
data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC",
fill_missing=False, drop_incomplete=False)
assert len(data) == 4
assert not log_has("Dropping last candle", caplog)
# Drop last candle
data = parse_ticker_dataframe(ticks, ticker_interval, pair="UNITTEST/BTC",
data = parse_ticker_dataframe(ticks, timeframe, pair="UNITTEST/BTC",
fill_missing=False, drop_incomplete=True)
assert len(data) == 3

View File

@@ -9,32 +9,32 @@ from tests.conftest import get_patched_exchange
def test_ohlcv(mocker, default_conf, ticker_history):
default_conf["runmode"] = RunMode.DRY_RUN
ticker_interval = default_conf["ticker_interval"]
timeframe = default_conf["ticker_interval"]
exchange = get_patched_exchange(mocker, default_conf)
exchange._klines[("XRP/BTC", ticker_interval)] = ticker_history
exchange._klines[("UNITTEST/BTC", ticker_interval)] = ticker_history
exchange._klines[("XRP/BTC", timeframe)] = ticker_history
exchange._klines[("UNITTEST/BTC", timeframe)] = ticker_history
dp = DataProvider(default_conf, exchange)
assert dp.runmode == RunMode.DRY_RUN
assert ticker_history.equals(dp.ohlcv("UNITTEST/BTC", ticker_interval))
assert isinstance(dp.ohlcv("UNITTEST/BTC", ticker_interval), DataFrame)
assert dp.ohlcv("UNITTEST/BTC", ticker_interval) is not ticker_history
assert dp.ohlcv("UNITTEST/BTC", ticker_interval, copy=False) is ticker_history
assert not dp.ohlcv("UNITTEST/BTC", ticker_interval).empty
assert dp.ohlcv("NONESENSE/AAA", ticker_interval).empty
assert ticker_history.equals(dp.ohlcv("UNITTEST/BTC", timeframe))
assert isinstance(dp.ohlcv("UNITTEST/BTC", timeframe), DataFrame)
assert dp.ohlcv("UNITTEST/BTC", timeframe) is not ticker_history
assert dp.ohlcv("UNITTEST/BTC", timeframe, copy=False) is ticker_history
assert not dp.ohlcv("UNITTEST/BTC", timeframe).empty
assert dp.ohlcv("NONESENSE/AAA", timeframe).empty
# Test with and without parameter
assert dp.ohlcv("UNITTEST/BTC", ticker_interval).equals(dp.ohlcv("UNITTEST/BTC"))
assert dp.ohlcv("UNITTEST/BTC", timeframe).equals(dp.ohlcv("UNITTEST/BTC"))
default_conf["runmode"] = RunMode.LIVE
dp = DataProvider(default_conf, exchange)
assert dp.runmode == RunMode.LIVE
assert isinstance(dp.ohlcv("UNITTEST/BTC", ticker_interval), DataFrame)
assert isinstance(dp.ohlcv("UNITTEST/BTC", timeframe), DataFrame)
default_conf["runmode"] = RunMode.BACKTEST
dp = DataProvider(default_conf, exchange)
assert dp.runmode == RunMode.BACKTEST
assert dp.ohlcv("UNITTEST/BTC", ticker_interval).empty
assert dp.ohlcv("UNITTEST/BTC", timeframe).empty
def test_historic_ohlcv(mocker, default_conf, ticker_history):
@@ -45,7 +45,7 @@ def test_historic_ohlcv(mocker, default_conf, ticker_history):
data = dp.historic_ohlcv("UNITTEST/BTC", "5m")
assert isinstance(data, DataFrame)
assert historymock.call_count == 1
assert historymock.call_args_list[0][1]["ticker_interval"] == "5m"
assert historymock.call_args_list[0][1]["timeframe"] == "5m"
def test_get_pair_dataframe(mocker, default_conf, ticker_history):

View File

@@ -64,20 +64,20 @@ def _clean_test_file(file: Path) -> None:
def test_load_data_30min_ticker(mocker, caplog, default_conf, testdatadir) -> None:
ld = history.load_pair_history(pair='UNITTEST/BTC', ticker_interval='30m', datadir=testdatadir)
ld = history.load_pair_history(pair='UNITTEST/BTC', timeframe='30m', datadir=testdatadir)
assert isinstance(ld, DataFrame)
assert not log_has(
'Download history data for pair: "UNITTEST/BTC", interval: 30m '
'Download history data for pair: "UNITTEST/BTC", timeframe: 30m '
'and store in None.', caplog
)
def test_load_data_7min_ticker(mocker, caplog, default_conf, testdatadir) -> None:
ld = history.load_pair_history(pair='UNITTEST/BTC', ticker_interval='7m', datadir=testdatadir)
ld = history.load_pair_history(pair='UNITTEST/BTC', timeframe='7m', datadir=testdatadir)
assert not isinstance(ld, DataFrame)
assert ld is None
assert log_has(
'No history data for pair: "UNITTEST/BTC", interval: 7m. '
'No history data for pair: "UNITTEST/BTC", timeframe: 7m. '
'Use `freqtrade download-data` to download the data', caplog
)
@@ -86,7 +86,7 @@ def test_load_data_1min_ticker(ticker_history, mocker, caplog, testdatadir) -> N
mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ticker_history)
file = testdatadir / 'UNITTEST_BTC-1m.json'
_backup_file(file, copy_file=True)
history.load_data(datadir=testdatadir, ticker_interval='1m', pairs=['UNITTEST/BTC'])
history.load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC'])
assert file.is_file()
assert not log_has(
'Download history data for pair: "UNITTEST/BTC", interval: 1m '
@@ -99,7 +99,7 @@ def test_load_data_startup_candles(mocker, caplog, default_conf, testdatadir) ->
ltfmock = mocker.patch('freqtrade.data.history.load_tickerdata_file',
MagicMock(return_value=None))
timerange = TimeRange('date', None, 1510639620, 0)
history.load_pair_history(pair='UNITTEST/BTC', ticker_interval='1m',
history.load_pair_history(pair='UNITTEST/BTC', timeframe='1m',
datadir=testdatadir, timerange=timerange,
startup_candles=20,
)
@@ -122,28 +122,28 @@ def test_load_data_with_new_pair_1min(ticker_history_list, mocker, caplog,
_backup_file(file)
# do not download a new pair if refresh_pairs isn't set
history.load_pair_history(datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
pair='MEME/BTC')
assert not file.is_file()
assert log_has(
'No history data for pair: "MEME/BTC", interval: 1m. '
'No history data for pair: "MEME/BTC", timeframe: 1m. '
'Use `freqtrade download-data` to download the data', caplog
)
# download a new pair if refresh_pairs is set
history.load_pair_history(datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
refresh_pairs=True,
exchange=exchange,
pair='MEME/BTC')
assert file.is_file()
assert log_has_re(
'Download history data for pair: "MEME/BTC", interval: 1m '
'Download history data for pair: "MEME/BTC", timeframe: 1m '
'and store in .*', caplog
)
with pytest.raises(OperationalException, match=r'Exchange needs to be initialized when.*'):
history.load_pair_history(datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
refresh_pairs=True,
exchange=None,
pair='MEME/BTC')
@@ -269,10 +269,10 @@ def test_download_pair_history(ticker_history_list, mocker, default_conf, testda
assert download_pair_history(datadir=testdatadir, exchange=exchange,
pair='MEME/BTC',
ticker_interval='1m')
timeframe='1m')
assert download_pair_history(datadir=testdatadir, exchange=exchange,
pair='CFI/BTC',
ticker_interval='1m')
timeframe='1m')
assert not exchange._pairs_last_refresh_time
assert file1_1.is_file()
assert file2_1.is_file()
@@ -286,10 +286,10 @@ def test_download_pair_history(ticker_history_list, mocker, default_conf, testda
assert download_pair_history(datadir=testdatadir, exchange=exchange,
pair='MEME/BTC',
ticker_interval='5m')
timeframe='5m')
assert download_pair_history(datadir=testdatadir, exchange=exchange,
pair='CFI/BTC',
ticker_interval='5m')
timeframe='5m')
assert not exchange._pairs_last_refresh_time
assert file1_5.is_file()
assert file2_5.is_file()
@@ -307,8 +307,8 @@ def test_download_pair_history2(mocker, default_conf, testdatadir) -> None:
json_dump_mock = mocker.patch('freqtrade.misc.file_dump_json', return_value=None)
mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=tick)
exchange = get_patched_exchange(mocker, default_conf)
download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", ticker_interval='1m')
download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", ticker_interval='3m')
download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", timeframe='1m')
download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", timeframe='3m')
assert json_dump_mock.call_count == 2
@@ -326,12 +326,12 @@ def test_download_backtesting_data_exception(ticker_history, mocker, caplog,
assert not download_pair_history(datadir=testdatadir, exchange=exchange,
pair='MEME/BTC',
ticker_interval='1m')
timeframe='1m')
# clean files freshly downloaded
_clean_test_file(file1_1)
_clean_test_file(file1_5)
assert log_has(
'Failed to download history data for pair: "MEME/BTC", interval: 1m. '
'Failed to download history data for pair: "MEME/BTC", timeframe: 1m. '
'Error: File Error', caplog
)
@@ -369,7 +369,7 @@ def test_load_partial_missing(testdatadir, caplog) -> None:
caplog.clear()
start = arrow.get('2018-01-10T00:00:00')
end = arrow.get('2018-02-20T00:00:00')
tickerdata = history.load_data(datadir=testdatadir, ticker_interval='5m',
tickerdata = history.load_data(datadir=testdatadir, timeframe='5m',
pairs=['UNITTEST/BTC'],
timerange=TimeRange('date', 'date',
start.timestamp, end.timestamp))
@@ -390,7 +390,7 @@ def test_init(default_conf, mocker) -> None:
exchange=exchange,
pairs=[],
refresh_pairs=True,
ticker_interval=default_conf['ticker_interval']
timeframe=default_conf['ticker_interval']
)
@@ -449,7 +449,7 @@ def test_trim_tickerlist(testdatadir) -> None:
def test_trim_dataframe(testdatadir) -> None:
data = history.load_data(
datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
pairs=['UNITTEST/BTC']
)['UNITTEST/BTC']
min_date = int(data.iloc[0]['date'].timestamp())
@@ -517,7 +517,7 @@ def test_get_timeframe(default_conf, mocker, testdatadir) -> None:
data = strategy.tickerdata_to_dataframe(
history.load_data(
datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
pairs=['UNITTEST/BTC']
)
)
@@ -533,7 +533,7 @@ def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir)
data = strategy.tickerdata_to_dataframe(
history.load_data(
datadir=testdatadir,
ticker_interval='1m',
timeframe='1m',
pairs=['UNITTEST/BTC'],
fill_up_missing=False
)
@@ -556,7 +556,7 @@ def test_validate_backtest_data(default_conf, mocker, caplog, testdatadir) -> No
data = strategy.tickerdata_to_dataframe(
history.load_data(
datadir=testdatadir,
ticker_interval='5m',
timeframe='5m',
pairs=['UNITTEST/BTC'],
timerange=timerange
)
@@ -669,10 +669,10 @@ def test_convert_trades_to_ohlcv(mocker, default_conf, testdatadir, caplog):
file5 = testdatadir / 'XRP_ETH-5m.json'
# Compare downloaded dataset with converted dataset
dfbak_1m = history.load_pair_history(datadir=testdatadir,
ticker_interval="1m",
timeframe="1m",
pair=pair)
dfbak_5m = history.load_pair_history(datadir=testdatadir,
ticker_interval="5m",
timeframe="5m",
pair=pair)
_backup_file(file1, copy_file=True)
@@ -686,10 +686,10 @@ def test_convert_trades_to_ohlcv(mocker, default_conf, testdatadir, caplog):
assert log_has("Deleting existing data for pair XRP/ETH, interval 1m.", caplog)
# Load new data
df_1m = history.load_pair_history(datadir=testdatadir,
ticker_interval="1m",
timeframe="1m",
pair=pair)
df_5m = history.load_pair_history(datadir=testdatadir,
ticker_interval="5m",
timeframe="5m",
pair=pair)
assert df_1m.equals(dfbak_1m)

View File

@@ -255,7 +255,7 @@ def test_edge_heartbeat_calculate(mocker, edge_conf):
assert edge.calculate() is False
def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=False,
def mocked_load_data(datadir, pairs=[], timeframe='0m', refresh_pairs=False,
timerange=None, exchange=None, *args, **kwargs):
hz = 0.1
base = 0.001

View File

@@ -1047,8 +1047,8 @@ def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name):
]
pair = 'ETH/BTC'
async def mock_candle_hist(pair, ticker_interval, since_ms):
return pair, ticker_interval, tick
async def mock_candle_hist(pair, timeframe, since_ms):
return pair, timeframe, tick
exchange._async_get_candle_history = Mock(wraps=mock_candle_hist)
# one_call calculation * 1.8 should do 2 calls
@@ -1107,7 +1107,7 @@ def test_refresh_latest_ohlcv(mocker, default_conf, caplog) -> None:
exchange.refresh_latest_ohlcv([('IOTA/ETH', '5m'), ('XRP/ETH', '5m')])
assert exchange._api_async.fetch_ohlcv.call_count == 2
assert log_has(f"Using cached ohlcv data for pair {pairs[0][0]}, interval {pairs[0][1]} ...",
assert log_has(f"Using cached ohlcv data for pair {pairs[0][0]}, timeframe {pairs[0][1]} ...",
caplog)
@@ -1143,7 +1143,7 @@ async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_
# exchange = Exchange(default_conf)
await async_ccxt_exception(mocker, default_conf, MagicMock(),
"_async_get_candle_history", "fetch_ohlcv",
pair='ABCD/BTC', ticker_interval=default_conf['ticker_interval'])
pair='ABCD/BTC', timeframe=default_conf['ticker_interval'])
api_mock = MagicMock()
with pytest.raises(OperationalException, match=r'Could not fetch ticker data*'):

View File

@@ -7,7 +7,7 @@ from freqtrade.exchange import timeframe_to_minutes
from freqtrade.strategy.interface import SellType
ticker_start_time = arrow.get(2018, 10, 3)
tests_ticker_interval = '1h'
tests_timeframe = '1h'
class BTrade(NamedTuple):
@@ -36,7 +36,7 @@ class BTContainer(NamedTuple):
def _get_frame_time_from_offset(offset):
return ticker_start_time.shift(minutes=(offset * timeframe_to_minutes(tests_ticker_interval))
return ticker_start_time.shift(minutes=(offset * timeframe_to_minutes(tests_timeframe))
).datetime

View File

@@ -9,7 +9,7 @@ from freqtrade.optimize.backtesting import Backtesting
from freqtrade.strategy.interface import SellType
from tests.conftest import patch_exchange
from tests.optimize import (BTContainer, BTrade, _build_backtest_dataframe,
_get_frame_time_from_offset, tests_ticker_interval)
_get_frame_time_from_offset, tests_timeframe)
# Test 0: Sell with signal sell in candle 3
# Test with Stop-loss at 1%
@@ -293,7 +293,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data) -> None:
"""
default_conf["stoploss"] = data.stop_loss
default_conf["minimal_roi"] = data.roi
default_conf["ticker_interval"] = tests_ticker_interval
default_conf["ticker_interval"] = tests_timeframe
default_conf["trailing_stop"] = data.trailing_stop
default_conf["trailing_only_offset_is_reached"] = data.trailing_only_offset_is_reached
# Only add this to configuration If it's necessary

View File

@@ -50,7 +50,7 @@ def trim_dictlist(dict_list, num):
def load_data_test(what, testdatadir):
timerange = TimeRange.parse_timerange('1510694220-1510700340')
pair = history.load_tickerdata_file(testdatadir, ticker_interval='1m',
pair = history.load_tickerdata_file(testdatadir, timeframe='1m',
pair='UNITTEST/BTC', timerange=timerange)
datalen = len(pair)
@@ -116,7 +116,7 @@ def simple_backtest(config, contour, num_results, mocker, testdatadir) -> None:
assert len(results) == num_results
def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=False,
def mocked_load_data(datadir, pairs=[], timeframe='0m', refresh_pairs=False,
timerange=None, exchange=None, live=False, *args, **kwargs):
tickerdata = history.load_tickerdata_file(datadir, 'UNITTEST/BTC', '1m', timerange=timerange)
pairdata = {'UNITTEST/BTC': parse_ticker_dataframe(tickerdata, '1m', pair="UNITTEST/BTC",
@@ -126,14 +126,14 @@ def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=Fals
# use for mock ccxt.fetch_ohlvc'
def _load_pair_as_ticks(pair, tickfreq):
ticks = history.load_tickerdata_file(None, ticker_interval=tickfreq, pair=pair)
ticks = history.load_tickerdata_file(None, timeframe=tickfreq, pair=pair)
ticks = ticks[-201:]
return ticks
# FIX: fixturize this?
def _make_backtest_conf(mocker, datadir, conf=None, pair='UNITTEST/BTC', record=None):
data = history.load_data(datadir=datadir, ticker_interval='1m', pairs=[pair])
data = history.load_data(datadir=datadir, timeframe='1m', pairs=[pair])
data = trim_dictlist(data, -201)
patch_exchange(mocker)
backtesting = Backtesting(conf)
@@ -184,9 +184,9 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
patched_configuration_load_config_file(mocker, default_conf)
args = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'backtesting'
]
config = setup_configuration(get_args(args), RunMode.BACKTEST)
@@ -217,10 +217,10 @@ def test_setup_bt_configuration_with_arguments(mocker, default_conf, caplog) ->
)
args = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'--datadir', '/foo/bar',
'backtesting',
'--ticker-interval', '1m',
'--enable-position-stacking',
'--disable-max-market-positions',
@@ -269,9 +269,9 @@ def test_setup_configuration_unlimited_stake_amount(mocker, default_conf, caplog
patched_configuration_load_config_file(mocker, default_conf)
args = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'backtesting'
]
with pytest.raises(DependencyException, match=r'.*stake amount.*'):
@@ -286,9 +286,9 @@ def test_start(mocker, fee, default_conf, caplog) -> None:
patched_configuration_load_config_file(mocker, default_conf)
args = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'backtesting'
]
args = get_args(args)
start_backtesting(args)
@@ -307,7 +307,7 @@ def test_backtesting_init(mocker, default_conf, order_types) -> None:
get_fee = mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5))
backtesting = Backtesting(default_conf)
assert backtesting.config == default_conf
assert backtesting.ticker_interval == '5m'
assert backtesting.timeframe == '5m'
assert callable(backtesting.strategy.tickerdata_to_dataframe)
assert callable(backtesting.strategy.advise_buy)
assert callable(backtesting.strategy.advise_sell)
@@ -522,7 +522,7 @@ def test_backtest(default_conf, fee, mocker, testdatadir) -> None:
backtesting = Backtesting(default_conf)
pair = 'UNITTEST/BTC'
timerange = TimeRange('date', None, 1517227800, 0)
data = history.load_data(datadir=testdatadir, ticker_interval='5m', pairs=['UNITTEST/BTC'],
data = history.load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'],
timerange=timerange)
data_processed = backtesting.strategy.tickerdata_to_dataframe(data)
min_date, max_date = get_timeframe(data_processed)
@@ -576,9 +576,9 @@ def test_backtest_1min_ticker_interval(default_conf, fee, mocker, testdatadir) -
patch_exchange(mocker)
backtesting = Backtesting(default_conf)
# Run a backtesting for an exiting 1min ticker_interval
# Run a backtesting for an exiting 1min timeframe
timerange = TimeRange.parse_timerange('1510688220-1510700340')
data = history.load_data(datadir=testdatadir, ticker_interval='1m', pairs=['UNITTEST/BTC'],
data = history.load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC'],
timerange=timerange)
processed = backtesting.strategy.tickerdata_to_dataframe(data)
min_date, max_date = get_timeframe(processed)
@@ -688,7 +688,7 @@ def test_backtest_multi_pair(default_conf, fee, mocker, tres, pair, testdatadir)
patch_exchange(mocker)
pairs = ['ADA/BTC', 'DASH/BTC', 'ETH/BTC', 'LTC/BTC', 'NXT/BTC']
data = history.load_data(datadir=testdatadir, ticker_interval='5m', pairs=pairs)
data = history.load_data(datadir=testdatadir, timeframe='5m', pairs=pairs)
# Only use 500 lines to increase performance
data = trim_dictlist(data, -500)
@@ -817,10 +817,10 @@ def test_backtest_start_timerange(default_conf, mocker, caplog, testdatadir):
patched_configuration_load_config_file(mocker, default_conf)
args = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'--datadir', str(testdatadir),
'backtesting',
'--ticker-interval', '1m',
'--timerange', '1510694220-1510700340',
'--enable-position-stacking',
@@ -866,9 +866,9 @@ def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir):
patched_configuration_load_config_file(mocker, default_conf)
args = [
'backtesting',
'--config', 'config.json',
'--datadir', str(testdatadir),
'backtesting',
'--ticker-interval', '1m',
'--timerange', '1510694220-1510700340',
'--enable-position-stacking',

View File

@@ -15,9 +15,9 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
patched_configuration_load_config_file(mocker, default_conf)
args = [
'edge',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'edge'
]
config = setup_configuration(get_args(args), RunMode.EDGE)
@@ -45,10 +45,10 @@ def test_setup_edge_configuration_with_arguments(mocker, edge_conf, caplog) -> N
)
args = [
'edge',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'--datadir', '/foo/bar',
'edge',
'--ticker-interval', '1m',
'--timerange', ':100',
'--stoplosses=-0.01,-0.10,-0.001'
@@ -79,9 +79,9 @@ def test_start(mocker, fee, edge_conf, caplog) -> None:
patched_configuration_load_config_file(mocker, edge_conf)
args = [
'edge',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'edge'
]
args = get_args(args)
start_edge(args)

View File

@@ -26,7 +26,10 @@ from tests.conftest import (get_args, log_has, log_has_re, patch_exchange,
@pytest.fixture(scope='function')
def hyperopt(default_conf, mocker):
default_conf.update({'spaces': ['all']})
default_conf.update({
'spaces': ['all'],
'hyperopt': 'DefaultHyperOpt',
})
patch_exchange(mocker)
return Hyperopt(default_conf)
@@ -69,8 +72,9 @@ def test_setup_hyperopt_configuration_without_arguments(mocker, default_conf, ca
patched_configuration_load_config_file(mocker, default_conf)
args = [
'hyperopt',
'--config', 'config.json',
'hyperopt'
'--hyperopt', 'DefaultHyperOpt',
]
config = setup_configuration(get_args(args), RunMode.HYPEROPT)
@@ -100,9 +104,10 @@ def test_setup_hyperopt_configuration_with_arguments(mocker, default_conf, caplo
)
args = [
'--config', 'config.json',
'--datadir', '/foo/bar',
'hyperopt',
'--config', 'config.json',
'--hyperopt', 'DefaultHyperOpt',
'--datadir', '/foo/bar',
'--ticker-interval', '1m',
'--timerange', ':100',
'--enable-position-stacking',
@@ -157,7 +162,8 @@ def test_hyperoptresolver(mocker, default_conf, caplog) -> None:
'freqtrade.resolvers.hyperopt_resolver.HyperOptResolver._load_hyperopt',
MagicMock(return_value=hyperopt(default_conf))
)
x = HyperOptResolver(default_conf, ).hyperopt
default_conf.update({'hyperopt': 'DefaultHyperOpt'})
x = HyperOptResolver(default_conf).hyperopt
assert not hasattr(x, 'populate_indicators')
assert not hasattr(x, 'populate_buy_trend')
assert not hasattr(x, 'populate_sell_trend')
@@ -174,7 +180,15 @@ def test_hyperoptresolver_wrongname(mocker, default_conf, caplog) -> None:
default_conf.update({'hyperopt': "NonExistingHyperoptClass"})
with pytest.raises(OperationalException, match=r'Impossible to load Hyperopt.*'):
HyperOptResolver(default_conf, ).hyperopt
HyperOptResolver(default_conf).hyperopt
def test_hyperoptresolver_noname(default_conf):
default_conf['hyperopt'] = ''
with pytest.raises(OperationalException,
match="No Hyperopt set. Please use `--hyperopt` to specify "
"the Hyperopt class to use."):
HyperOptResolver(default_conf)
def test_hyperoptlossresolver(mocker, default_conf, caplog) -> None:
@@ -184,7 +198,7 @@ def test_hyperoptlossresolver(mocker, default_conf, caplog) -> None:
'freqtrade.resolvers.hyperopt_resolver.HyperOptLossResolver._load_hyperoptloss',
MagicMock(return_value=hl)
)
x = HyperOptLossResolver(default_conf, ).hyperoptloss
x = HyperOptLossResolver(default_conf).hyperoptloss
assert hasattr(x, "hyperopt_loss_function")
@@ -192,7 +206,7 @@ def test_hyperoptlossresolver_wrongname(mocker, default_conf, caplog) -> None:
default_conf.update({'hyperopt_loss': "NonExistingLossClass"})
with pytest.raises(OperationalException, match=r'Impossible to load HyperoptLoss.*'):
HyperOptLossResolver(default_conf, ).hyperopt
HyperOptLossResolver(default_conf).hyperopt
def test_start_not_installed(mocker, default_conf, caplog, import_fails) -> None:
@@ -203,8 +217,9 @@ def test_start_not_installed(mocker, default_conf, caplog, import_fails) -> None
patch_exchange(mocker)
args = [
'--config', 'config.json',
'hyperopt',
'--config', 'config.json',
'--hyperopt', 'DefaultHyperOpt',
'--epochs', '5'
]
args = get_args(args)
@@ -220,8 +235,9 @@ def test_start(mocker, default_conf, caplog) -> None:
patch_exchange(mocker)
args = [
'--config', 'config.json',
'hyperopt',
'--config', 'config.json',
'--hyperopt', 'DefaultHyperOpt',
'--epochs', '5'
]
args = get_args(args)
@@ -242,8 +258,9 @@ def test_start_no_data(mocker, default_conf, caplog) -> None:
patch_exchange(mocker)
args = [
'--config', 'config.json',
'hyperopt',
'--config', 'config.json',
'--hyperopt', 'DefaultHyperOpt',
'--epochs', '5'
]
args = get_args(args)
@@ -258,8 +275,9 @@ def test_start_filelock(mocker, default_conf, caplog) -> None:
patch_exchange(mocker)
args = [
'--config', 'config.json',
'hyperopt',
'--config', 'config.json',
'--hyperopt', 'DefaultHyperOpt',
'--epochs', '5'
]
args = get_args(args)
@@ -412,6 +430,7 @@ def test_start_calls_optimizer(mocker, default_conf, caplog, capsys) -> None:
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'all',
@@ -515,10 +534,12 @@ def test_buy_strategy_generator(hyperopt, testdatadir) -> None:
def test_generate_optimizer(mocker, default_conf) -> None:
default_conf.update({'config': 'config.json.example'})
default_conf.update({'timerange': None})
default_conf.update({'spaces': 'all'})
default_conf.update({'hyperopt_min_trades': 1})
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'timerange': None,
'spaces': 'all',
'hyperopt_min_trades': 1,
})
trades = [
('TRX/BTC', 0.023117, 0.000233, 100)
@@ -582,6 +603,7 @@ def test_generate_optimizer(mocker, default_conf) -> None:
def test_clean_hyperopt(mocker, default_conf, caplog):
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'all',
@@ -598,6 +620,7 @@ def test_clean_hyperopt(mocker, default_conf, caplog):
def test_continue_hyperopt(mocker, default_conf, caplog):
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'all',
@@ -628,6 +651,7 @@ def test_print_json_spaces_all(mocker, default_conf, caplog, capsys) -> None:
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'all',
@@ -666,6 +690,7 @@ def test_print_json_spaces_roi_stoploss(mocker, default_conf, caplog, capsys) ->
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'roi stoploss',
@@ -705,6 +730,7 @@ def test_simplified_interface_roi_stoploss(mocker, default_conf, caplog, capsys)
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'roi stoploss',
@@ -747,6 +773,7 @@ def test_simplified_interface_all_failed(mocker, default_conf, caplog, capsys) -
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'all',
@@ -781,6 +808,7 @@ def test_simplified_interface_buy(mocker, default_conf, caplog, capsys) -> None:
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'buy',
@@ -827,6 +855,7 @@ def test_simplified_interface_sell(mocker, default_conf, caplog, capsys) -> None
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': 'sell',
@@ -875,6 +904,7 @@ def test_simplified_interface_failed(mocker, default_conf, caplog, capsys, metho
patch_exchange(mocker)
default_conf.update({'config': 'config.json.example',
'hyperopt': 'DefaultHyperOpt',
'epochs': 1,
'timerange': None,
'spaces': space,

View File

@@ -96,6 +96,11 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None:
def test_rpc_status_table(default_conf, ticker, fee, mocker) -> None:
mocker.patch.multiple(
'freqtrade.rpc.fiat_convert.Market',
ticker=MagicMock(return_value={'price_usd': 15000.0}),
)
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock())
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
@@ -109,22 +114,34 @@ def test_rpc_status_table(default_conf, ticker, fee, mocker) -> None:
freqtradebot.state = State.RUNNING
with pytest.raises(RPCException, match=r'.*no active order*'):
rpc._rpc_status_table()
rpc._rpc_status_table(default_conf['stake_currency'], 'USD')
freqtradebot.create_trades()
result = rpc._rpc_status_table()
assert 'instantly' in result['Since'].all()
assert 'ETH/BTC' in result['Pair'].all()
assert '-0.59%' in result['Profit'].all()
result, headers = rpc._rpc_status_table(default_conf['stake_currency'], 'USD')
assert "Since" in headers
assert "Pair" in headers
assert 'instantly' == result[0][2]
assert 'ETH/BTC' == result[0][1]
assert '-0.59%' == result[0][3]
# Test with fiatconvert
rpc._fiat_converter = CryptoToFiatConverter()
result, headers = rpc._rpc_status_table(default_conf['stake_currency'], 'USD')
assert "Since" in headers
assert "Pair" in headers
assert 'instantly' == result[0][2]
assert 'ETH/BTC' == result[0][1]
assert '-0.59% (-0.09)' == result[0][3]
mocker.patch('freqtrade.exchange.Exchange.get_ticker',
MagicMock(side_effect=DependencyException(f"Pair 'ETH/BTC' not available")))
# invalidate ticker cache
rpc._freqtrade.exchange._cached_ticker = {}
result = rpc._rpc_status_table()
assert 'instantly' in result['Since'].all()
assert 'ETH/BTC' in result['Pair'].all()
assert 'nan%' in result['Profit'].all()
result, headers = rpc._rpc_status_table(default_conf['stake_currency'], 'USD')
assert 'instantly' == result[0][2]
assert 'ETH/BTC' == result[0][1]
assert 'nan%' == result[0][3]
def test_rpc_daily_profit(default_conf, update, ticker, fee,

View File

@@ -64,6 +64,10 @@ def test_api_not_found(botclient):
def test_api_unauthorized(botclient):
ftbot, client = botclient
rc = client.get(f"{BASE_URI}/ping")
assert_response(rc)
assert rc.json == {'status': 'pong'}
# Don't send user/pass information
rc = client.get(f"{BASE_URI}/version")
assert_response(rc, 401)

View File

@@ -1,5 +1,5 @@
# pragma pylint: disable=missing-docstring, C0103
import time
import logging
from unittest.mock import MagicMock
@@ -176,6 +176,8 @@ def test_init_apiserver_enabled(mocker, default_conf, caplog) -> None:
"listen_port": "8080"}
rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf))
# Sleep to allow the thread to start
time.sleep(0.5)
assert log_has('Enabling rpc.api_server', caplog)
assert len(rpc_manager.registered_modules) == 1
assert 'apiserver' in [mod.name for mod in rpc_manager.registered_modules]

View File

@@ -54,21 +54,30 @@ def test_load_strategy_base64(result, caplog, default_conf):
def test_load_strategy_invalid_directory(result, caplog, default_conf):
default_conf['strategy'] = 'SampleStrategy'
resolver = StrategyResolver(default_conf)
extra_dir = Path.cwd() / 'some/path'
resolver._load_strategy('SampleStrategy', config=default_conf, extra_dir=extra_dir)
assert log_has_re(r'Path .*' + r'some.*path.*' + r'.* does not exist', caplog)
assert 'adx' in resolver.strategy.advise_indicators(result, {'pair': 'ETH/BTC'})
assert 'rsi' in resolver.strategy.advise_indicators(result, {'pair': 'ETH/BTC'})
def test_load_not_found_strategy(default_conf):
strategy = StrategyResolver(default_conf)
default_conf['strategy'] = 'NotFoundStrategy'
with pytest.raises(OperationalException,
match=r"Impossible to load Strategy 'NotFoundStrategy'. "
r"This class does not exist or contains Python code errors."):
strategy._load_strategy(strategy_name='NotFoundStrategy', config=default_conf)
StrategyResolver(default_conf)
def test_load_strategy_noname(default_conf):
default_conf['strategy'] = ''
with pytest.raises(OperationalException,
match="No strategy set. Please use `--strategy` to specify "
"the strategy class to use."):
StrategyResolver(default_conf)
def test_strategy(result, default_conf):

View File

@@ -11,7 +11,7 @@ from freqtrade.configuration.cli_options import check_int_positive
# Parse common command-line-arguments. Used for all tools
def test_parse_args_none() -> None:
arguments = Arguments([])
arguments = Arguments(['trade'])
assert isinstance(arguments, Arguments)
x = arguments.get_parsed_arg()
assert isinstance(x, dict)
@@ -19,7 +19,7 @@ def test_parse_args_none() -> None:
def test_parse_args_defaults() -> None:
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
assert args["config"] == ['config.json']
assert args["strategy_path"] is None
assert args["datadir"] is None
@@ -27,27 +27,27 @@ def test_parse_args_defaults() -> None:
def test_parse_args_config() -> None:
args = Arguments(['-c', '/dev/null']).get_parsed_arg()
args = Arguments(['trade', '-c', '/dev/null']).get_parsed_arg()
assert args["config"] == ['/dev/null']
args = Arguments(['--config', '/dev/null']).get_parsed_arg()
args = Arguments(['trade', '--config', '/dev/null']).get_parsed_arg()
assert args["config"] == ['/dev/null']
args = Arguments(['--config', '/dev/null',
args = Arguments(['trade', '--config', '/dev/null',
'--config', '/dev/zero'],).get_parsed_arg()
assert args["config"] == ['/dev/null', '/dev/zero']
def test_parse_args_db_url() -> None:
args = Arguments(['--db-url', 'sqlite:///test.sqlite']).get_parsed_arg()
args = Arguments(['trade', '--db-url', 'sqlite:///test.sqlite']).get_parsed_arg()
assert args["db_url"] == 'sqlite:///test.sqlite'
def test_parse_args_verbose() -> None:
args = Arguments(['-v']).get_parsed_arg()
args = Arguments(['trade', '-v']).get_parsed_arg()
assert args["verbosity"] == 1
args = Arguments(['--verbose']).get_parsed_arg()
args = Arguments(['trade', '--verbose']).get_parsed_arg()
assert args["verbosity"] == 1
@@ -69,7 +69,7 @@ def test_parse_args_invalid() -> None:
def test_parse_args_strategy() -> None:
args = Arguments(['--strategy', 'SomeStrategy']).get_parsed_arg()
args = Arguments(['trade', '--strategy', 'SomeStrategy']).get_parsed_arg()
assert args["strategy"] == 'SomeStrategy'
@@ -79,7 +79,7 @@ def test_parse_args_strategy_invalid() -> None:
def test_parse_args_strategy_path() -> None:
args = Arguments(['--strategy-path', '/some/path']).get_parsed_arg()
args = Arguments(['trade', '--strategy-path', '/some/path']).get_parsed_arg()
assert args["strategy_path"] == '/some/path'
@@ -98,8 +98,8 @@ def test_parse_args_backtesting_invalid() -> None:
def test_parse_args_backtesting_custom() -> None:
args = [
'-c', 'test_conf.json',
'backtesting',
'-c', 'test_conf.json',
'--ticker-interval', '1m',
'--strategy-list',
'DefaultStrategy',
@@ -108,7 +108,7 @@ def test_parse_args_backtesting_custom() -> None:
call_args = Arguments(args).get_parsed_arg()
assert call_args["config"] == ['test_conf.json']
assert call_args["verbosity"] == 0
assert call_args["subparser"] == 'backtesting'
assert call_args["command"] == 'backtesting'
assert call_args["func"] is not None
assert call_args["ticker_interval"] == '1m'
assert type(call_args["strategy_list"]) is list
@@ -117,8 +117,8 @@ def test_parse_args_backtesting_custom() -> None:
def test_parse_args_hyperopt_custom() -> None:
args = [
'-c', 'test_conf.json',
'hyperopt',
'-c', 'test_conf.json',
'--epochs', '20',
'--spaces', 'buy'
]
@@ -126,7 +126,7 @@ def test_parse_args_hyperopt_custom() -> None:
assert call_args["config"] == ['test_conf.json']
assert call_args["epochs"] == 20
assert call_args["verbosity"] == 0
assert call_args["subparser"] == 'hyperopt'
assert call_args["command"] == 'hyperopt'
assert call_args["spaces"] == ['buy']
assert call_args["func"] is not None
assert callable(call_args["func"])
@@ -134,8 +134,8 @@ def test_parse_args_hyperopt_custom() -> None:
def test_download_data_options() -> None:
args = [
'--datadir', 'datadir/directory',
'download-data',
'--datadir', 'datadir/directory',
'--pairs-file', 'file_with_pairs',
'--days', '30',
'--exchange', 'binance'
@@ -150,8 +150,8 @@ def test_download_data_options() -> None:
def test_plot_dataframe_options() -> None:
args = [
'-c', 'config.json.example',
'plot-dataframe',
'-c', 'config.json.example',
'--indicators1', 'sma10', 'sma100',
'--indicators2', 'macd', 'fastd', 'fastk',
'--plot-limit', '30',
@@ -186,7 +186,7 @@ def test_config_notallowed(mocker) -> None:
]
pargs = Arguments(args).get_parsed_arg()
assert pargs["config"] is None
assert "config" not in pargs
# When file exists:
mocker.patch.object(Path, "is_file", MagicMock(return_value=True))
@@ -195,7 +195,7 @@ def test_config_notallowed(mocker) -> None:
]
pargs = Arguments(args).get_parsed_arg()
# config is not added even if it exists, since create-userdir is in the notallowed list
assert pargs["config"] is None
assert "config" not in pargs
def test_config_notrequired(mocker) -> None:

View File

@@ -68,7 +68,7 @@ def test_load_config_file(default_conf, mocker, caplog) -> None:
def test__args_to_config(caplog):
arg_list = ['--strategy-path', 'TestTest']
arg_list = ['trade', '--strategy-path', 'TestTest']
args = Arguments(arg_list).get_parsed_arg()
configuration = Configuration(args)
config = {}
@@ -96,7 +96,7 @@ def test_load_config_max_open_trades_zero(default_conf, mocker, caplog) -> None:
default_conf['max_open_trades'] = 0
patched_configuration_load_config_file(mocker, default_conf)
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
@@ -121,7 +121,7 @@ def test_load_config_combine_dicts(default_conf, mocker, caplog) -> None:
configsmock
)
arg_list = ['-c', 'test_conf.json', '--config', 'test2_conf.json', ]
arg_list = ['trade', '-c', 'test_conf.json', '--config', 'test2_conf.json', ]
args = Arguments(arg_list).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
@@ -187,7 +187,7 @@ def test_load_config_max_open_trades_minus_one(default_conf, mocker, caplog) ->
default_conf['max_open_trades'] = -1
patched_configuration_load_config_file(mocker, default_conf)
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
@@ -211,11 +211,10 @@ def test_load_config_file_exception(mocker) -> None:
def test_load_config(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, default_conf)
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
assert validated_conf.get('strategy') == 'DefaultStrategy'
assert validated_conf.get('strategy_path') is None
assert 'edge' not in validated_conf
@@ -224,6 +223,7 @@ def test_load_config_with_params(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--strategy-path', '/some/path',
'--db-url', 'sqlite:///someurl',
@@ -243,6 +243,7 @@ def test_load_config_with_params(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--strategy-path', '/some/path'
]
@@ -259,6 +260,7 @@ def test_load_config_with_params(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--strategy-path', '/some/path'
]
@@ -275,6 +277,7 @@ def test_load_config_with_params(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--strategy-path', '/some/path'
]
@@ -293,6 +296,7 @@ def test_load_config_with_params(default_conf, mocker) -> None:
patched_configuration_load_config_file(mocker, conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--strategy-path', '/some/path'
]
@@ -303,6 +307,23 @@ def test_load_config_with_params(default_conf, mocker) -> None:
assert validated_conf.get('db_url') == DEFAULT_DB_DRYRUN_URL
@pytest.mark.parametrize("config_value,expected,arglist", [
(True, True, ['trade', '--dry-run']), # Leave config untouched
(False, True, ['trade', '--dry-run']), # Override config untouched
(False, False, ['trade']), # Leave config untouched
(True, True, ['trade']), # Leave config untouched
])
def test_load_dry_run(default_conf, mocker, config_value, expected, arglist) -> None:
default_conf['dry_run'] = config_value
patched_configuration_load_config_file(mocker, default_conf)
configuration = Configuration(Arguments(arglist).get_parsed_arg())
validated_conf = configuration.load_config()
assert validated_conf.get('dry_run') is expected
def test_load_custom_strategy(default_conf, mocker) -> None:
default_conf.update({
'strategy': 'CustomStrategy',
@@ -310,7 +331,7 @@ def test_load_custom_strategy(default_conf, mocker) -> None:
})
patched_configuration_load_config_file(mocker, default_conf)
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
@@ -322,6 +343,7 @@ def test_show_info(default_conf, mocker, caplog) -> None:
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'trade',
'--strategy', 'TestStrategy',
'--db-url', 'sqlite:///tmp/testdb',
]
@@ -338,9 +360,9 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'backtesting'
]
args = Arguments(arglist).get_parsed_arg()
@@ -376,11 +398,11 @@ def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> Non
lambda x, *args, **kwargs: Path(x)
)
arglist = [
'backtesting',
'--config', 'config.json',
'--strategy', 'DefaultStrategy',
'--datadir', '/foo/bar',
'--userdir', "/tmp/freqtrade",
'backtesting',
'--ticker-interval', '1m',
'--enable-position-stacking',
'--disable-max-market-positions',
@@ -427,8 +449,8 @@ def test_setup_configuration_with_stratlist(mocker, default_conf, caplog) -> Non
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'--config', 'config.json',
'backtesting',
'--config', 'config.json',
'--ticker-interval', '1m',
'--export', '/bar/foo',
'--strategy-list',
@@ -568,7 +590,7 @@ def test_cli_verbose_with_params(default_conf, mocker, caplog) -> None:
# Prevent setting loggers
mocker.patch('freqtrade.loggers._set_loggers', MagicMock)
arglist = ['-vvv']
arglist = ['trade', '-vvv']
args = Arguments(arglist).get_parsed_arg()
configuration = Configuration(args)
@@ -620,7 +642,7 @@ def test_set_logfile(default_conf, mocker):
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'--logfile', 'test_file.log',
'trade', '--logfile', 'test_file.log',
]
args = Arguments(arglist).get_parsed_arg()
configuration = Configuration(args)
@@ -636,7 +658,7 @@ def test_load_config_warn_forcebuy(default_conf, mocker, caplog) -> None:
default_conf['forcebuy_enable'] = True
patched_configuration_load_config_file(mocker, default_conf)
args = Arguments([]).get_parsed_arg()
args = Arguments(['trade']).get_parsed_arg()
configuration = Configuration(args)
validated_conf = configuration.load_config()
@@ -847,8 +869,8 @@ def test_pairlist_resolving():
def test_pairlist_resolving_with_config(mocker, default_conf):
patched_configuration_load_config_file(mocker, default_conf)
arglist = [
'--config', 'config.json',
'download-data',
'--config', 'config.json',
]
args = Arguments(arglist).get_parsed_arg()
@@ -861,8 +883,8 @@ def test_pairlist_resolving_with_config(mocker, default_conf):
# Override pairs
arglist = [
'--config', 'config.json',
'download-data',
'--config', 'config.json',
'--pairs', 'ETH/BTC', 'XRP/BTC',
]
@@ -883,8 +905,8 @@ def test_pairlist_resolving_with_config_pl(mocker, default_conf):
mocker.patch.object(Path, "open", MagicMock(return_value=MagicMock()))
arglist = [
'--config', 'config.json',
'download-data',
'--config', 'config.json',
'--pairs-file', 'pairs.json',
]
@@ -905,8 +927,8 @@ def test_pairlist_resolving_with_config_pl_not_exists(mocker, default_conf):
mocker.patch.object(Path, "exists", MagicMock(return_value=False))
arglist = [
'--config', 'config.json',
'download-data',
'--config', 'config.json',
'--pairs-file', 'pairs.json',
]

View File

@@ -11,10 +11,16 @@ from freqtrade.freqtradebot import FreqtradeBot
from freqtrade.main import main
from freqtrade.state import State
from freqtrade.worker import Worker
from tests.conftest import (log_has, patch_exchange,
from tests.conftest import (log_has, log_has_re, patch_exchange,
patched_configuration_load_config_file)
def test_parse_args_None(caplog) -> None:
with pytest.raises(SystemExit):
main([])
assert log_has_re(r"Usage of Freqtrade requires a subcommand.*", caplog)
def test_parse_args_backtesting(mocker) -> None:
"""
Test that main() can start backtesting and also ensure we can pass some specific arguments
@@ -29,7 +35,7 @@ def test_parse_args_backtesting(mocker) -> None:
call_args = backtesting_mock.call_args[0][0]
assert call_args["config"] == ['config.json']
assert call_args["verbosity"] == 0
assert call_args["subparser"] == 'backtesting'
assert call_args["command"] == 'backtesting'
assert call_args["func"] is not None
assert callable(call_args["func"])
assert call_args["ticker_interval"] is None
@@ -45,7 +51,7 @@ def test_main_start_hyperopt(mocker) -> None:
call_args = hyperopt_mock.call_args[0][0]
assert call_args["config"] == ['config.json']
assert call_args["verbosity"] == 0
assert call_args["subparser"] == 'hyperopt'
assert call_args["command"] == 'hyperopt'
assert call_args["func"] is not None
assert callable(call_args["func"])
@@ -58,7 +64,7 @@ def test_main_fatal_exception(mocker, default_conf, caplog) -> None:
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
args = ['-c', 'config.json.example']
args = ['trade', '-c', 'config.json.example']
# Test Main + the KeyboardInterrupt exception
with pytest.raises(SystemExit):
@@ -75,7 +81,7 @@ def test_main_keyboard_interrupt(mocker, default_conf, caplog) -> None:
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
args = ['-c', 'config.json.example']
args = ['trade', '-c', 'config.json.example']
# Test Main + the KeyboardInterrupt exception
with pytest.raises(SystemExit):
@@ -95,7 +101,7 @@ def test_main_operational_exception(mocker, default_conf, caplog) -> None:
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
args = ['-c', 'config.json.example']
args = ['trade', '-c', 'config.json.example']
# Test Main + the KeyboardInterrupt exception
with pytest.raises(SystemExit):
@@ -114,15 +120,15 @@ def test_main_reload_conf(mocker, default_conf, caplog) -> None:
OperationalException("Oh snap!")])
mocker.patch('freqtrade.worker.Worker._worker', worker_mock)
patched_configuration_load_config_file(mocker, default_conf)
reconfigure_mock = mocker.patch('freqtrade.main.Worker._reconfigure', MagicMock())
reconfigure_mock = mocker.patch('freqtrade.worker.Worker._reconfigure', MagicMock())
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
args = Arguments(['-c', 'config.json.example']).get_parsed_arg()
args = Arguments(['trade', '-c', 'config.json.example']).get_parsed_arg()
worker = Worker(args=args, config=default_conf)
with pytest.raises(SystemExit):
main(['-c', 'config.json.example'])
main(['trade', '-c', 'config.json.example'])
assert log_has('Using config: config.json.example ...', caplog)
assert worker_mock.call_count == 4
@@ -141,7 +147,7 @@ def test_reconfigure(mocker, default_conf) -> None:
mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())
mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock())
args = Arguments(['-c', 'config.json.example']).get_parsed_arg()
args = Arguments(['trade', '-c', 'config.json.example']).get_parsed_arg()
worker = Worker(args=args, config=default_conf)
freqtrade = worker.freqtrade

View File

@@ -64,7 +64,7 @@ def test_add_indicators(default_conf, testdatadir, caplog):
pair = "UNITTEST/BTC"
timerange = TimeRange(None, 'line', 0, -1000)
data = history.load_pair_history(pair=pair, ticker_interval='1m',
data = history.load_pair_history(pair=pair, timeframe='1m',
datadir=testdatadir, timerange=timerange)
indicators1 = ["ema10"]
indicators2 = ["macd"]
@@ -129,7 +129,7 @@ def test_generate_candlestick_graph_no_signals_no_trades(default_conf, mocker, t
pair = "UNITTEST/BTC"
timerange = TimeRange(None, 'line', 0, -1000)
data = history.load_pair_history(pair=pair, ticker_interval='1m',
data = history.load_pair_history(pair=pair, timeframe='1m',
datadir=testdatadir, timerange=timerange)
data['buy'] = 0
data['sell'] = 0
@@ -164,7 +164,7 @@ def test_generate_candlestick_graph_no_trades(default_conf, mocker, testdatadir)
MagicMock(side_effect=fig_generating_mock))
pair = 'UNITTEST/BTC'
timerange = TimeRange(None, 'line', 0, -1000)
data = history.load_pair_history(pair=pair, ticker_interval='1m',
data = history.load_pair_history(pair=pair, timeframe='1m',
datadir=testdatadir, timerange=timerange)
# Generate buy/sell signals and indicators
@@ -228,7 +228,7 @@ def test_add_profit(testdatadir):
bt_data = load_backtest_data(filename)
timerange = TimeRange.parse_timerange("20180110-20180112")
df = history.load_pair_history(pair="TRX/BTC", ticker_interval='5m',
df = history.load_pair_history(pair="TRX/BTC", timeframe='5m',
datadir=testdatadir, timerange=timerange)
fig = generate_empty_figure()
@@ -251,7 +251,7 @@ def test_generate_profit_graph(testdatadir):
tickers = history.load_data(datadir=testdatadir,
pairs=pairs,
ticker_interval='5m',
timeframe='5m',
timerange=timerange
)
trades = trades[trades['pair'].isin(pairs)]
@@ -281,8 +281,8 @@ def test_generate_profit_graph(testdatadir):
def test_start_plot_dataframe(mocker):
aup = mocker.patch("freqtrade.plot.plotting.load_and_plot_trades", MagicMock())
args = [
"--config", "config.json.example",
"plot-dataframe",
"--config", "config.json.example",
"--pairs", "ETH/BTC"
]
start_plot_dataframe(get_args(args))
@@ -323,8 +323,8 @@ def test_load_and_plot_trades(default_conf, mocker, caplog, testdatadir):
def test_start_plot_profit(mocker):
aup = mocker.patch("freqtrade.plot.plotting.plot_profit", MagicMock())
args = [
"--config", "config.json.example",
"plot-profit",
"--config", "config.json.example",
"--pairs", "ETH/BTC"
]
start_plot_profit(get_args(args))

View File

@@ -14,7 +14,7 @@ from tests.conftest import get_args, log_has, patch_exchange
def test_setup_utils_configuration():
args = [
'--config', 'config.json.example',
'list-exchanges', '--config', 'config.json.example',
]
config = setup_utils_configuration(get_args(args), RunMode.OTHER)
@@ -95,8 +95,8 @@ def test_list_timeframes(mocker, capsys):
# Test with --config config.json.example
args = [
'--config', 'config.json.example',
"list-timeframes",
'--config', 'config.json.example',
]
start_list_timeframes(get_args(args))
captured = capsys.readouterr()
@@ -139,8 +139,8 @@ def test_list_timeframes(mocker, capsys):
# Test with --one-column
args = [
'--config', 'config.json.example',
"list-timeframes",
'--config', 'config.json.example',
"--one-column",
]
start_list_timeframes(get_args(args))
@@ -182,8 +182,8 @@ def test_list_markets(mocker, markets, capsys):
# Test with --config config.json.example
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--print-list",
]
start_list_markets(get_args(args), False)
@@ -208,8 +208,8 @@ def test_list_markets(mocker, markets, capsys):
patch_exchange(mocker, api_mock=api_mock, id="bittrex")
# Test with --all: all markets
args = [
'--config', 'config.json.example',
"list-markets", "--all",
'--config', 'config.json.example',
"--print-list",
]
start_list_markets(get_args(args), False)
@@ -221,8 +221,8 @@ def test_list_markets(mocker, markets, capsys):
# Test list-pairs subcommand: active pairs
args = [
'--config', 'config.json.example',
"list-pairs",
'--config', 'config.json.example',
"--print-list",
]
start_list_markets(get_args(args), True)
@@ -233,8 +233,8 @@ def test_list_markets(mocker, markets, capsys):
# Test list-pairs subcommand with --all: all pairs
args = [
'--config', 'config.json.example',
"list-pairs", "--all",
'--config', 'config.json.example',
"--print-list",
]
start_list_markets(get_args(args), True)
@@ -246,8 +246,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, base=ETH, LTC
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "ETH", "LTC",
"--print-list",
]
@@ -259,8 +259,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, base=LTC
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "LTC",
"--print-list",
]
@@ -272,8 +272,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, quote=USDT, USD
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--quote", "USDT", "USD",
"--print-list",
]
@@ -285,8 +285,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, quote=USDT
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--quote", "USDT",
"--print-list",
]
@@ -298,8 +298,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, base=LTC, quote=USDT
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "LTC", "--quote", "USDT",
"--print-list",
]
@@ -311,8 +311,8 @@ def test_list_markets(mocker, markets, capsys):
# active pairs, base=LTC, quote=USDT
args = [
'--config', 'config.json.example',
"list-pairs",
'--config', 'config.json.example',
"--base", "LTC", "--quote", "USD",
"--print-list",
]
@@ -324,8 +324,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, base=LTC, quote=USDT, NONEXISTENT
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "LTC", "--quote", "USDT", "NONEXISTENT",
"--print-list",
]
@@ -337,8 +337,8 @@ def test_list_markets(mocker, markets, capsys):
# active markets, base=LTC, quote=NONEXISTENT
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "LTC", "--quote", "NONEXISTENT",
"--print-list",
]
@@ -350,8 +350,8 @@ def test_list_markets(mocker, markets, capsys):
# Test tabular output
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
]
start_list_markets(get_args(args), False)
captured = capsys.readouterr()
@@ -360,8 +360,8 @@ def test_list_markets(mocker, markets, capsys):
# Test tabular output, no markets found
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--base", "LTC", "--quote", "NONEXISTENT",
]
start_list_markets(get_args(args), False)
@@ -372,8 +372,8 @@ def test_list_markets(mocker, markets, capsys):
# Test --print-json
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--print-json"
]
start_list_markets(get_args(args), False)
@@ -384,8 +384,8 @@ def test_list_markets(mocker, markets, capsys):
# Test --print-csv
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--print-csv"
]
start_list_markets(get_args(args), False)
@@ -396,8 +396,8 @@ def test_list_markets(mocker, markets, capsys):
# Test --one-column
args = [
'--config', 'config.json.example',
"list-markets",
'--config', 'config.json.example',
"--one-column"
]
start_list_markets(get_args(args), False)