Merge branch 'develop' into feature_keyval_storage
This commit is contained in:
@@ -29,6 +29,7 @@ def mock_order_1(is_short: bool):
|
||||
'average': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -65,6 +66,7 @@ def mock_order_2(is_short: bool):
|
||||
'price': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -79,6 +81,7 @@ def mock_order_2_sell(is_short: bool):
|
||||
'price': 0.128,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -126,6 +129,7 @@ def mock_order_3(is_short: bool):
|
||||
'price': 0.05,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -141,6 +145,7 @@ def mock_order_3_sell(is_short: bool):
|
||||
'average': 0.06,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -186,6 +191,7 @@ def mock_order_4(is_short: bool):
|
||||
'price': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 0.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 123.0,
|
||||
}
|
||||
|
||||
@@ -225,6 +231,7 @@ def mock_order_5(is_short: bool):
|
||||
'price': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -239,6 +246,7 @@ def mock_order_5_stoploss(is_short: bool):
|
||||
'price': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 0.0,
|
||||
'cost': 0.0,
|
||||
'remaining': 123.0,
|
||||
}
|
||||
|
||||
@@ -281,6 +289,7 @@ def mock_order_6(is_short: bool):
|
||||
'price': 0.15,
|
||||
'amount': 2.0,
|
||||
'filled': 2.0,
|
||||
'cost': 0.3,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -295,6 +304,7 @@ def mock_order_6_sell(is_short: bool):
|
||||
'price': 0.15 if is_short else 0.20,
|
||||
'amount': 2.0,
|
||||
'filled': 0.0,
|
||||
'cost': 0.0,
|
||||
'remaining': 2.0,
|
||||
}
|
||||
|
||||
@@ -337,6 +347,7 @@ def short_order():
|
||||
'price': 0.123,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.129,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -351,6 +362,7 @@ def exit_short_order():
|
||||
'price': 0.128,
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'cost': 15.744,
|
||||
'remaining': 0.0,
|
||||
}
|
||||
|
||||
@@ -424,6 +436,7 @@ def leverage_order():
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'remaining': 0.0,
|
||||
'cost': 15.129,
|
||||
'leverage': 5.0
|
||||
}
|
||||
|
||||
@@ -439,6 +452,7 @@ def leverage_order_sell():
|
||||
'amount': 123.0,
|
||||
'filled': 123.0,
|
||||
'remaining': 0.0,
|
||||
'cost': 15.744,
|
||||
'leverage': 5.0
|
||||
}
|
||||
|
||||
|
||||
191
tests/data/test_entryexitanalysis.py
Executable file
191
tests/data/test_entryexitanalysis.py
Executable file
@@ -0,0 +1,191 @@
|
||||
import logging
|
||||
from unittest.mock import MagicMock, PropertyMock
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from freqtrade.commands.analyze_commands import start_analysis_entries_exits
|
||||
from freqtrade.commands.optimize_commands import start_backtesting
|
||||
from freqtrade.enums import ExitType
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
from tests.conftest import get_args, patch_exchange, patched_configuration_load_config_file
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def entryexitanalysis_cleanup() -> None:
|
||||
yield None
|
||||
|
||||
Backtesting.cleanup()
|
||||
|
||||
|
||||
def test_backtest_analysis_nomock(default_conf, mocker, caplog, testdatadir, tmpdir, capsys):
|
||||
caplog.set_level(logging.INFO)
|
||||
|
||||
default_conf.update({
|
||||
"use_exit_signal": True,
|
||||
"exit_profit_only": False,
|
||||
"exit_profit_offset": 0.0,
|
||||
"ignore_roi_if_entry_signal": False,
|
||||
})
|
||||
patch_exchange(mocker)
|
||||
result1 = pd.DataFrame({'pair': ['ETH/BTC', 'LTC/BTC', 'ETH/BTC', 'LTC/BTC'],
|
||||
'profit_ratio': [0.025, 0.05, -0.1, -0.05],
|
||||
'profit_abs': [0.5, 2.0, -4.0, -2.0],
|
||||
'open_date': pd.to_datetime(['2018-01-29 18:40:00',
|
||||
'2018-01-30 03:30:00',
|
||||
'2018-01-30 08:10:00',
|
||||
'2018-01-31 13:30:00', ], utc=True
|
||||
),
|
||||
'close_date': pd.to_datetime(['2018-01-29 20:45:00',
|
||||
'2018-01-30 05:35:00',
|
||||
'2018-01-30 09:10:00',
|
||||
'2018-01-31 15:00:00', ], utc=True),
|
||||
'trade_duration': [235, 40, 60, 90],
|
||||
'is_open': [False, False, False, False],
|
||||
'stake_amount': [0.01, 0.01, 0.01, 0.01],
|
||||
'open_rate': [0.104445, 0.10302485, 0.10302485, 0.10302485],
|
||||
'close_rate': [0.104969, 0.103541, 0.102041, 0.102541],
|
||||
"is_short": [False, False, False, False],
|
||||
'enter_tag': ["enter_tag_long_a",
|
||||
"enter_tag_long_b",
|
||||
"enter_tag_long_a",
|
||||
"enter_tag_long_b"],
|
||||
'exit_reason': [ExitType.ROI,
|
||||
ExitType.EXIT_SIGNAL,
|
||||
ExitType.STOP_LOSS,
|
||||
ExitType.TRAILING_STOP_LOSS]
|
||||
})
|
||||
|
||||
backtestmock = MagicMock(side_effect=[
|
||||
{
|
||||
'results': result1,
|
||||
'config': default_conf,
|
||||
'locks': [],
|
||||
'rejected_signals': 20,
|
||||
'timedout_entry_orders': 0,
|
||||
'timedout_exit_orders': 0,
|
||||
'canceled_trade_entries': 0,
|
||||
'canceled_entry_orders': 0,
|
||||
'replaced_entry_orders': 0,
|
||||
'final_balance': 1000,
|
||||
}
|
||||
])
|
||||
mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist',
|
||||
PropertyMock(return_value=['ETH/BTC', 'LTC/BTC', 'DASH/BTC']))
|
||||
mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', backtestmock)
|
||||
|
||||
patched_configuration_load_config_file(mocker, default_conf)
|
||||
|
||||
args = [
|
||||
'backtesting',
|
||||
'--config', 'config.json',
|
||||
'--datadir', str(testdatadir),
|
||||
'--user-data-dir', str(tmpdir),
|
||||
'--timeframe', '5m',
|
||||
'--timerange', '1515560100-1517287800',
|
||||
'--export', 'signals',
|
||||
'--cache', 'none',
|
||||
]
|
||||
args = get_args(args)
|
||||
start_backtesting(args)
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert 'BACKTESTING REPORT' in captured.out
|
||||
assert 'EXIT REASON STATS' in captured.out
|
||||
assert 'LEFT OPEN TRADES REPORT' in captured.out
|
||||
|
||||
base_args = [
|
||||
'backtesting-analysis',
|
||||
'--config', 'config.json',
|
||||
'--datadir', str(testdatadir),
|
||||
'--user-data-dir', str(tmpdir),
|
||||
]
|
||||
|
||||
# test group 0 and indicator list
|
||||
args = get_args(base_args +
|
||||
['--analysis-groups', "0",
|
||||
'--indicator-list', "close", "rsi", "profit_abs"]
|
||||
)
|
||||
start_analysis_entries_exits(args)
|
||||
captured = capsys.readouterr()
|
||||
assert 'LTC/BTC' in captured.out
|
||||
assert 'ETH/BTC' in captured.out
|
||||
assert 'enter_tag_long_a' in captured.out
|
||||
assert 'enter_tag_long_b' in captured.out
|
||||
assert 'exit_signal' in captured.out
|
||||
assert 'roi' in captured.out
|
||||
assert 'stop_loss' in captured.out
|
||||
assert 'trailing_stop_loss' in captured.out
|
||||
assert '0.5' in captured.out
|
||||
assert '-4' in captured.out
|
||||
assert '-2' in captured.out
|
||||
assert '-3.5' in captured.out
|
||||
assert '50' in captured.out
|
||||
assert '0' in captured.out
|
||||
assert '0.01616' in captured.out
|
||||
assert '34.049' in captured.out
|
||||
assert '0.104104' in captured.out
|
||||
assert '47.0996' in captured.out
|
||||
|
||||
# test group 1
|
||||
args = get_args(base_args + ['--analysis-groups', "1"])
|
||||
start_analysis_entries_exits(args)
|
||||
captured = capsys.readouterr()
|
||||
assert 'enter_tag_long_a' in captured.out
|
||||
assert 'enter_tag_long_b' in captured.out
|
||||
assert 'total_profit_pct' in captured.out
|
||||
assert '-3.5' in captured.out
|
||||
assert '-1.75' in captured.out
|
||||
assert '-7.5' in captured.out
|
||||
assert '-3.75' in captured.out
|
||||
assert '0' in captured.out
|
||||
|
||||
# test group 2
|
||||
args = get_args(base_args + ['--analysis-groups', "2"])
|
||||
start_analysis_entries_exits(args)
|
||||
captured = capsys.readouterr()
|
||||
assert 'enter_tag_long_a' in captured.out
|
||||
assert 'enter_tag_long_b' in captured.out
|
||||
assert 'exit_signal' in captured.out
|
||||
assert 'roi' in captured.out
|
||||
assert 'stop_loss' in captured.out
|
||||
assert 'trailing_stop_loss' in captured.out
|
||||
assert 'total_profit_pct' in captured.out
|
||||
assert '-10' in captured.out
|
||||
assert '-5' in captured.out
|
||||
assert '2.5' in captured.out
|
||||
|
||||
# test group 3
|
||||
args = get_args(base_args + ['--analysis-groups', "3"])
|
||||
start_analysis_entries_exits(args)
|
||||
captured = capsys.readouterr()
|
||||
assert 'LTC/BTC' in captured.out
|
||||
assert 'ETH/BTC' in captured.out
|
||||
assert 'enter_tag_long_a' in captured.out
|
||||
assert 'enter_tag_long_b' in captured.out
|
||||
assert 'total_profit_pct' in captured.out
|
||||
assert '-7.5' in captured.out
|
||||
assert '-3.75' in captured.out
|
||||
assert '-1.75' in captured.out
|
||||
assert '0' in captured.out
|
||||
assert '2' in captured.out
|
||||
|
||||
# test group 4
|
||||
args = get_args(base_args + ['--analysis-groups', "4"])
|
||||
start_analysis_entries_exits(args)
|
||||
captured = capsys.readouterr()
|
||||
assert 'LTC/BTC' in captured.out
|
||||
assert 'ETH/BTC' in captured.out
|
||||
assert 'enter_tag_long_a' in captured.out
|
||||
assert 'enter_tag_long_b' in captured.out
|
||||
assert 'exit_signal' in captured.out
|
||||
assert 'roi' in captured.out
|
||||
assert 'stop_loss' in captured.out
|
||||
assert 'trailing_stop_loss' in captured.out
|
||||
assert 'total_profit_pct' in captured.out
|
||||
assert '-10' in captured.out
|
||||
assert '-5' in captured.out
|
||||
assert '-4' in captured.out
|
||||
assert '0.5' in captured.out
|
||||
assert '1' in captured.out
|
||||
assert '2.5' in captured.out
|
||||
@@ -33,6 +33,12 @@ def test_validate_order_types_gateio(default_conf, mocker):
|
||||
match=r'Exchange .* does not support market orders.'):
|
||||
ExchangeResolver.load_exchange('gateio', default_conf, True)
|
||||
|
||||
# market-orders supported on futures markets.
|
||||
default_conf['trading_mode'] = 'futures'
|
||||
default_conf['margin_mode'] = 'isolated'
|
||||
ex = ExchangeResolver.load_exchange('gateio', default_conf, True)
|
||||
assert ex
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_persistence")
|
||||
def test_fetch_stoploss_order_gateio(default_conf, mocker):
|
||||
|
||||
@@ -7,6 +7,7 @@ import pytest
|
||||
from freqtrade.data.history import get_timerange
|
||||
from freqtrade.enums import ExitType
|
||||
from freqtrade.optimize.backtesting import Backtesting
|
||||
from freqtrade.persistence.trade_model import LocalTrade
|
||||
from tests.conftest import patch_exchange
|
||||
from tests.optimize import (BTContainer, BTrade, _build_backtest_dataframe,
|
||||
_get_frame_time_from_offset, tests_timeframe)
|
||||
@@ -964,5 +965,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data: BTContainer)
|
||||
assert res.open_date == _get_frame_time_from_offset(trade.open_tick)
|
||||
assert res.close_date == _get_frame_time_from_offset(trade.close_tick)
|
||||
assert res.is_short == trade.is_short
|
||||
assert len(LocalTrade.trades) == len(data.trades)
|
||||
assert len(LocalTrade.trades_open) == 0
|
||||
backtesting.cleanup()
|
||||
del backtesting
|
||||
|
||||
@@ -171,7 +171,7 @@ def test_generate_backtest_stats(default_conf, testdatadir, tmpdir):
|
||||
_backup_file(filename_last, copy_file=True)
|
||||
assert not filename.is_file()
|
||||
|
||||
store_backtest_stats(filename, stats)
|
||||
store_backtest_stats(filename, stats, '2022_01_01_15_05_13')
|
||||
|
||||
# get real Filename (it's btresult-<date>.json)
|
||||
last_fn = get_latest_backtest_filename(filename_last.parent)
|
||||
@@ -194,7 +194,7 @@ def test_store_backtest_stats(testdatadir, mocker):
|
||||
|
||||
dump_mock = mocker.patch('freqtrade.optimize.optimize_reports.file_dump_json')
|
||||
|
||||
store_backtest_stats(testdatadir, {'metadata': {}})
|
||||
store_backtest_stats(testdatadir, {'metadata': {}}, '2022_01_01_15_05_13')
|
||||
|
||||
assert dump_mock.call_count == 3
|
||||
assert isinstance(dump_mock.call_args_list[0][0][0], Path)
|
||||
@@ -202,7 +202,7 @@ def test_store_backtest_stats(testdatadir, mocker):
|
||||
|
||||
dump_mock.reset_mock()
|
||||
filename = testdatadir / 'testresult.json'
|
||||
store_backtest_stats(filename, {'metadata': {}})
|
||||
store_backtest_stats(filename, {'metadata': {}}, '2022_01_01_15_05_13')
|
||||
assert dump_mock.call_count == 3
|
||||
assert isinstance(dump_mock.call_args_list[0][0][0], Path)
|
||||
# result will be testdatadir / testresult-<timestamp>.json
|
||||
@@ -216,7 +216,7 @@ def test_store_backtest_candles(testdatadir, mocker):
|
||||
candle_dict = {'DefStrat': {'UNITTEST/BTC': pd.DataFrame()}}
|
||||
|
||||
# mock directory exporting
|
||||
store_backtest_signal_candles(testdatadir, candle_dict)
|
||||
store_backtest_signal_candles(testdatadir, candle_dict, '2022_01_01_15_05_13')
|
||||
|
||||
assert dump_mock.call_count == 1
|
||||
assert isinstance(dump_mock.call_args_list[0][0][0], Path)
|
||||
@@ -225,7 +225,7 @@ def test_store_backtest_candles(testdatadir, mocker):
|
||||
dump_mock.reset_mock()
|
||||
# mock file exporting
|
||||
filename = Path(testdatadir / 'testresult')
|
||||
store_backtest_signal_candles(filename, candle_dict)
|
||||
store_backtest_signal_candles(filename, candle_dict, '2022_01_01_15_05_13')
|
||||
assert dump_mock.call_count == 1
|
||||
assert isinstance(dump_mock.call_args_list[0][0][0], Path)
|
||||
# result will be testdatadir / testresult-<timestamp>_signals.pkl
|
||||
@@ -238,7 +238,7 @@ def test_write_read_backtest_candles(tmpdir):
|
||||
candle_dict = {'DefStrat': {'UNITTEST/BTC': pd.DataFrame()}}
|
||||
|
||||
# test directory exporting
|
||||
stored_file = store_backtest_signal_candles(Path(tmpdir), candle_dict)
|
||||
stored_file = store_backtest_signal_candles(Path(tmpdir), candle_dict, '2022_01_01_15_05_13')
|
||||
scp = open(stored_file, "rb")
|
||||
pickled_signal_candles = joblib.load(scp)
|
||||
scp.close()
|
||||
@@ -252,7 +252,7 @@ def test_write_read_backtest_candles(tmpdir):
|
||||
|
||||
# test file exporting
|
||||
filename = Path(tmpdir / 'testresult')
|
||||
stored_file = store_backtest_signal_candles(filename, candle_dict)
|
||||
stored_file = store_backtest_signal_candles(filename, candle_dict, '2022_01_01_15_05_13')
|
||||
scp = open(stored_file, "rb")
|
||||
pickled_signal_candles = joblib.load(scp)
|
||||
scp.close()
|
||||
|
||||
@@ -724,7 +724,9 @@ def test_api_edge_disabled(botclient, mocker, ticker, fee, markets):
|
||||
'profit_closed_fiat': -83.19455985, 'profit_closed_ratio_mean': -0.0075,
|
||||
'profit_closed_percent_mean': -0.75, 'profit_closed_ratio_sum': -0.015,
|
||||
'profit_closed_percent_sum': -1.5, 'profit_closed_ratio': -6.739057628404269e-06,
|
||||
'profit_closed_percent': -0.0, 'winning_trades': 0, 'losing_trades': 2}
|
||||
'profit_closed_percent': -0.0, 'winning_trades': 0, 'losing_trades': 2,
|
||||
'profit_factor': 0.0, 'trading_volume': 91.074,
|
||||
}
|
||||
),
|
||||
(
|
||||
False,
|
||||
@@ -737,7 +739,9 @@ def test_api_edge_disabled(botclient, mocker, ticker, fee, markets):
|
||||
'profit_closed_fiat': 9.124559849999999, 'profit_closed_ratio_mean': 0.0075,
|
||||
'profit_closed_percent_mean': 0.75, 'profit_closed_ratio_sum': 0.015,
|
||||
'profit_closed_percent_sum': 1.5, 'profit_closed_ratio': 7.391275897987988e-07,
|
||||
'profit_closed_percent': 0.0, 'winning_trades': 2, 'losing_trades': 0}
|
||||
'profit_closed_percent': 0.0, 'winning_trades': 2, 'losing_trades': 0,
|
||||
'profit_factor': None, 'trading_volume': 91.074,
|
||||
}
|
||||
),
|
||||
(
|
||||
None,
|
||||
@@ -750,7 +754,9 @@ def test_api_edge_disabled(botclient, mocker, ticker, fee, markets):
|
||||
'profit_closed_fiat': -67.02260985, 'profit_closed_ratio_mean': 0.0025,
|
||||
'profit_closed_percent_mean': 0.25, 'profit_closed_ratio_sum': 0.005,
|
||||
'profit_closed_percent_sum': 0.5, 'profit_closed_ratio': -5.429078808526421e-06,
|
||||
'profit_closed_percent': -0.0, 'winning_trades': 1, 'losing_trades': 1}
|
||||
'profit_closed_percent': -0.0, 'winning_trades': 1, 'losing_trades': 1,
|
||||
'profit_factor': 0.02775724835771106, 'trading_volume': 91.074,
|
||||
}
|
||||
)
|
||||
])
|
||||
def test_api_profit(botclient, mocker, ticker, fee, markets, is_short, expected):
|
||||
@@ -803,6 +809,10 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, is_short, expected)
|
||||
'closed_trade_count': 2,
|
||||
'winning_trades': expected['winning_trades'],
|
||||
'losing_trades': expected['losing_trades'],
|
||||
'profit_factor': expected['profit_factor'],
|
||||
'max_drawdown': ANY,
|
||||
'max_drawdown_abs': ANY,
|
||||
'trading_volume': expected['trading_volume'],
|
||||
}
|
||||
|
||||
|
||||
@@ -852,8 +862,8 @@ def test_api_performance(botclient, fee):
|
||||
close_rate=0.265441,
|
||||
|
||||
)
|
||||
trade.close_profit = trade.calc_profit_ratio()
|
||||
trade.close_profit_abs = trade.calc_profit()
|
||||
trade.close_profit = trade.calc_profit_ratio(trade.close_rate)
|
||||
trade.close_profit_abs = trade.calc_profit(trade.close_rate)
|
||||
Trade.query.session.add(trade)
|
||||
|
||||
trade = Trade(
|
||||
@@ -868,8 +878,8 @@ def test_api_performance(botclient, fee):
|
||||
fee_open=fee.return_value,
|
||||
close_rate=0.391
|
||||
)
|
||||
trade.close_profit = trade.calc_profit_ratio()
|
||||
trade.close_profit_abs = trade.calc_profit()
|
||||
trade.close_profit = trade.calc_profit_ratio(trade.close_rate)
|
||||
trade.close_profit_abs = trade.calc_profit(trade.close_rate)
|
||||
|
||||
Trade.query.session.add(trade)
|
||||
Trade.commit()
|
||||
@@ -1384,12 +1394,14 @@ def test_api_strategies(botclient):
|
||||
rc = client_get(client, f"{BASE_URI}/strategies")
|
||||
|
||||
assert_response(rc)
|
||||
|
||||
assert rc.json() == {'strategies': [
|
||||
'HyperoptableStrategy',
|
||||
'InformativeDecoratorTest',
|
||||
'StrategyTestV2',
|
||||
'StrategyTestV3',
|
||||
'StrategyTestV3Futures',
|
||||
'StrategyTestV3Analysis',
|
||||
'StrategyTestV3Futures'
|
||||
]}
|
||||
|
||||
|
||||
|
||||
@@ -704,11 +704,13 @@ def test_profit_handle(default_conf_usdt, update, ticker_usdt, ticker_sell_up, f
|
||||
assert '∙ `6.253 USD`' in msg_mock.call_args_list[-1][0][0]
|
||||
|
||||
assert '*Best Performing:* `ETH/USDT: 9.45%`' in msg_mock.call_args_list[-1][0][0]
|
||||
assert '*Max Drawdown:*' in msg_mock.call_args_list[-1][0][0]
|
||||
assert '*Profit factor:*' in msg_mock.call_args_list[-1][0][0]
|
||||
assert '*Trading volume:* `60 USDT`' in msg_mock.call_args_list[-1][0][0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('is_short', [True, False])
|
||||
def test_telegram_stats(default_conf, update, ticker, ticker_sell_up, fee,
|
||||
limit_buy_order, limit_sell_order, mocker, is_short) -> None:
|
||||
def test_telegram_stats(default_conf, update, ticker, fee, mocker, is_short) -> None:
|
||||
mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0)
|
||||
mocker.patch.multiple(
|
||||
'freqtrade.exchange.Exchange',
|
||||
@@ -1680,7 +1682,7 @@ def test_send_msg_buy_notification(default_conf, mocker, caplog, message_type,
|
||||
leverage_text = f'*Leverage:* `{leverage}`\n' if leverage and leverage != 1.0 else ''
|
||||
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
f'\N{LARGE BLUE CIRCLE} *Binance:* {enter} ETH/BTC (#1)\n'
|
||||
f'\N{LARGE BLUE CIRCLE} *Binance (dry):* {enter} ETH/BTC (#1)\n'
|
||||
f'*Enter Tag:* `{enter_signal}`\n'
|
||||
'*Amount:* `1333.33333333`\n'
|
||||
f'{leverage_text}'
|
||||
@@ -1720,7 +1722,7 @@ def test_send_msg_buy_cancel_notification(default_conf, mocker, message_type, en
|
||||
'pair': 'ETH/BTC',
|
||||
'reason': CANCEL_REASON['TIMEOUT']
|
||||
})
|
||||
assert (msg_mock.call_args[0][0] == '\N{WARNING SIGN} *Binance:* '
|
||||
assert (msg_mock.call_args[0][0] == '\N{WARNING SIGN} *Binance (dry):* '
|
||||
'Cancelling enter Order for ETH/BTC (#1). '
|
||||
'Reason: cancelled due to timeout.')
|
||||
|
||||
@@ -1782,7 +1784,7 @@ def test_send_msg_entry_fill_notification(default_conf, mocker, message_type, en
|
||||
})
|
||||
leverage_text = f'*Leverage:* `{leverage}`\n' if leverage != 1.0 else ''
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
f'\N{CHECK MARK} *Binance:* {entered}ed ETH/BTC (#1)\n'
|
||||
f'\N{CHECK MARK} *Binance (dry):* {entered}ed ETH/BTC (#1)\n'
|
||||
f'*Enter Tag:* `{enter_signal}`\n'
|
||||
'*Amount:* `1333.33333333`\n'
|
||||
f"{leverage_text}"
|
||||
@@ -1820,7 +1822,7 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'close_date': arrow.utcnow(),
|
||||
})
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
'\N{WARNING SIGN} *Binance:* Exiting KEY/ETH (#1)\n'
|
||||
'\N{WARNING SIGN} *Binance (dry):* Exiting KEY/ETH (#1)\n'
|
||||
'*Unrealized Profit:* `-57.41% (loss: -0.05746268 ETH / -24.812 USD)`\n'
|
||||
'*Enter Tag:* `buy_signal1`\n'
|
||||
'*Exit Reason:* `stop_loss`\n'
|
||||
@@ -1854,7 +1856,7 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None:
|
||||
'close_date': arrow.utcnow(),
|
||||
})
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
'\N{WARNING SIGN} *Binance:* Exiting KEY/ETH (#1)\n'
|
||||
'\N{WARNING SIGN} *Binance (dry):* Exiting KEY/ETH (#1)\n'
|
||||
'*Unrealized Profit:* `-57.41%`\n'
|
||||
'*Enter Tag:* `buy_signal1`\n'
|
||||
'*Exit Reason:* `stop_loss`\n'
|
||||
@@ -1883,10 +1885,12 @@ def test_send_msg_sell_cancel_notification(default_conf, mocker) -> None:
|
||||
'reason': 'Cancelled on exchange'
|
||||
})
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
'\N{WARNING SIGN} *Binance:* Cancelling exit Order for KEY/ETH (#1).'
|
||||
'\N{WARNING SIGN} *Binance (dry):* Cancelling exit Order for KEY/ETH (#1).'
|
||||
' Reason: Cancelled on exchange.')
|
||||
|
||||
msg_mock.reset_mock()
|
||||
# Test with live mode (no dry appendix)
|
||||
telegram._config['dry_run'] = False
|
||||
telegram.send_msg({
|
||||
'type': RPCMessageType.EXIT_CANCEL,
|
||||
'trade_id': 1,
|
||||
@@ -1935,7 +1939,7 @@ def test_send_msg_sell_fill_notification(default_conf, mocker, direction,
|
||||
|
||||
leverage_text = f'*Leverage:* `{leverage}`\n' if leverage and leverage != 1.0 else ''
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
'\N{WARNING SIGN} *Binance:* Exited KEY/ETH (#1)\n'
|
||||
'\N{WARNING SIGN} *Binance (dry):* Exited KEY/ETH (#1)\n'
|
||||
'*Profit:* `-57.41%`\n'
|
||||
f'*Enter Tag:* `{enter_signal}`\n'
|
||||
'*Exit Reason:* `stop_loss`\n'
|
||||
@@ -1991,6 +1995,7 @@ def test_send_msg_unknown_type(default_conf, mocker) -> None:
|
||||
def test_send_msg_buy_notification_no_fiat(
|
||||
default_conf, mocker, message_type, enter, enter_signal, leverage) -> None:
|
||||
del default_conf['fiat_display_currency']
|
||||
default_conf['dry_run'] = False
|
||||
telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
|
||||
|
||||
telegram.send_msg({
|
||||
@@ -2060,7 +2065,7 @@ def test_send_msg_sell_notification_no_fiat(
|
||||
|
||||
leverage_text = f'*Leverage:* `{leverage}`\n' if leverage and leverage != 1.0 else ''
|
||||
assert msg_mock.call_args[0][0] == (
|
||||
'\N{WARNING SIGN} *Binance:* Exiting KEY/ETH (#1)\n'
|
||||
'\N{WARNING SIGN} *Binance (dry):* Exiting KEY/ETH (#1)\n'
|
||||
'*Unrealized Profit:* `-57.41%`\n'
|
||||
f'*Enter Tag:* `{enter_signal}`\n'
|
||||
'*Exit Reason:* `stop_loss`\n'
|
||||
|
||||
175
tests/strategy/strats/strategy_test_v3_analysis.py
Normal file
175
tests/strategy/strats/strategy_test_v3_analysis.py
Normal file
@@ -0,0 +1,175 @@
|
||||
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
|
||||
|
||||
import talib.abstract as ta
|
||||
from pandas import DataFrame
|
||||
|
||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
from freqtrade.strategy import (BooleanParameter, DecimalParameter, IntParameter, IStrategy,
|
||||
RealParameter)
|
||||
|
||||
|
||||
class StrategyTestV3Analysis(IStrategy):
|
||||
"""
|
||||
Strategy used by tests freqtrade bot.
|
||||
Please do not modify this strategy, it's intended for internal use only.
|
||||
Please look at the SampleStrategy in the user_data/strategy directory
|
||||
or strategy repository https://github.com/freqtrade/freqtrade-strategies
|
||||
for samples and inspiration.
|
||||
"""
|
||||
INTERFACE_VERSION = 3
|
||||
|
||||
# Minimal ROI designed for the strategy
|
||||
minimal_roi = {
|
||||
"40": 0.0,
|
||||
"30": 0.01,
|
||||
"20": 0.02,
|
||||
"0": 0.04
|
||||
}
|
||||
|
||||
# Optimal stoploss designed for the strategy
|
||||
stoploss = -0.10
|
||||
|
||||
# Optimal timeframe for the strategy
|
||||
timeframe = '5m'
|
||||
|
||||
# Optional order type mapping
|
||||
order_types = {
|
||||
'entry': 'limit',
|
||||
'exit': 'limit',
|
||||
'stoploss': 'limit',
|
||||
'stoploss_on_exchange': False
|
||||
}
|
||||
|
||||
# Number of candles the strategy requires before producing valid signals
|
||||
startup_candle_count: int = 20
|
||||
|
||||
# Optional time in force for orders
|
||||
order_time_in_force = {
|
||||
'entry': 'gtc',
|
||||
'exit': 'gtc',
|
||||
}
|
||||
|
||||
buy_params = {
|
||||
'buy_rsi': 35,
|
||||
# Intentionally not specified, so "default" is tested
|
||||
# 'buy_plusdi': 0.4
|
||||
}
|
||||
|
||||
sell_params = {
|
||||
'sell_rsi': 74,
|
||||
'sell_minusdi': 0.4
|
||||
}
|
||||
|
||||
buy_rsi = IntParameter([0, 50], default=30, space='buy')
|
||||
buy_plusdi = RealParameter(low=0, high=1, default=0.5, space='buy')
|
||||
sell_rsi = IntParameter(low=50, high=100, default=70, space='sell')
|
||||
sell_minusdi = DecimalParameter(low=0, high=1, default=0.5001, decimals=3, space='sell',
|
||||
load=False)
|
||||
protection_enabled = BooleanParameter(default=True)
|
||||
protection_cooldown_lookback = IntParameter([0, 50], default=30)
|
||||
|
||||
# TODO: Can this work with protection tests? (replace HyperoptableStrategy implicitly ... )
|
||||
# @property
|
||||
# def protections(self):
|
||||
# prot = []
|
||||
# if self.protection_enabled.value:
|
||||
# prot.append({
|
||||
# "method": "CooldownPeriod",
|
||||
# "stop_duration_candles": self.protection_cooldown_lookback.value
|
||||
# })
|
||||
# return prot
|
||||
|
||||
bot_started = False
|
||||
|
||||
def bot_start(self):
|
||||
self.bot_started = True
|
||||
|
||||
def informative_pairs(self):
|
||||
|
||||
return []
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
# Momentum Indicator
|
||||
# ------------------------------------
|
||||
|
||||
# ADX
|
||||
dataframe['adx'] = ta.ADX(dataframe)
|
||||
|
||||
# MACD
|
||||
macd = ta.MACD(dataframe)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['macdhist'] = macd['macdhist']
|
||||
|
||||
# Minus Directional Indicator / Movement
|
||||
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
||||
|
||||
# Plus Directional Indicator / Movement
|
||||
dataframe['plus_di'] = ta.PLUS_DI(dataframe)
|
||||
|
||||
# RSI
|
||||
dataframe['rsi'] = ta.RSI(dataframe)
|
||||
|
||||
# Stoch fast
|
||||
stoch_fast = ta.STOCHF(dataframe)
|
||||
dataframe['fastd'] = stoch_fast['fastd']
|
||||
dataframe['fastk'] = stoch_fast['fastk']
|
||||
|
||||
# Bollinger bands
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_middleband'] = bollinger['mid']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
|
||||
# EMA - Exponential Moving Average
|
||||
dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
|
||||
dataframe.loc[
|
||||
(
|
||||
(dataframe['rsi'] < self.buy_rsi.value) &
|
||||
(dataframe['fastd'] < 35) &
|
||||
(dataframe['adx'] > 30) &
|
||||
(dataframe['plus_di'] > self.buy_plusdi.value)
|
||||
) |
|
||||
(
|
||||
(dataframe['adx'] > 65) &
|
||||
(dataframe['plus_di'] > self.buy_plusdi.value)
|
||||
),
|
||||
['enter_long', 'enter_tag']] = 1, 'enter_tag_long'
|
||||
|
||||
dataframe.loc[
|
||||
(
|
||||
qtpylib.crossed_below(dataframe['rsi'], self.sell_rsi.value)
|
||||
),
|
||||
['enter_short', 'enter_tag']] = 1, 'enter_tag_short'
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
dataframe.loc[
|
||||
(
|
||||
(
|
||||
(qtpylib.crossed_above(dataframe['rsi'], self.sell_rsi.value)) |
|
||||
(qtpylib.crossed_above(dataframe['fastd'], 70))
|
||||
) &
|
||||
(dataframe['adx'] > 10) &
|
||||
(dataframe['minus_di'] > 0)
|
||||
) |
|
||||
(
|
||||
(dataframe['adx'] > 70) &
|
||||
(dataframe['minus_di'] > self.sell_minusdi.value)
|
||||
),
|
||||
['exit_long', 'exit_tag']] = 1, 'exit_tag_long'
|
||||
|
||||
dataframe.loc[
|
||||
(
|
||||
qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)
|
||||
),
|
||||
['exit_long', 'exit_tag']] = 1, 'exit_tag_short'
|
||||
|
||||
return dataframe
|
||||
@@ -34,7 +34,7 @@ def test_search_all_strategies_no_failed():
|
||||
directory = Path(__file__).parent / "strats"
|
||||
strategies = StrategyResolver.search_all_objects(directory, enum_failed=False)
|
||||
assert isinstance(strategies, list)
|
||||
assert len(strategies) == 5
|
||||
assert len(strategies) == 6
|
||||
assert isinstance(strategies[0], dict)
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ def test_search_all_strategies_with_failed():
|
||||
directory = Path(__file__).parent / "strats"
|
||||
strategies = StrategyResolver.search_all_objects(directory, enum_failed=True)
|
||||
assert isinstance(strategies, list)
|
||||
assert len(strategies) == 6
|
||||
assert len(strategies) == 7
|
||||
# with enum_failed=True search_all_objects() shall find 2 good strategies
|
||||
# and 1 which fails to load
|
||||
assert len([x for x in strategies if x['class'] is not None]) == 5
|
||||
assert len([x for x in strategies if x['class'] is not None]) == 6
|
||||
assert len([x for x in strategies if x['class'] is None]) == 1
|
||||
|
||||
|
||||
|
||||
@@ -2151,7 +2151,7 @@ def test_handle_trade(
|
||||
|
||||
assert trade.close_rate == 2.0 if is_short else 2.2
|
||||
assert trade.close_profit == close_profit
|
||||
assert trade.calc_profit() == 5.685
|
||||
assert trade.calc_profit(trade.close_rate) == 5.685
|
||||
assert trade.close_date is not None
|
||||
assert trade.exit_reason == 'sell_signal1'
|
||||
|
||||
|
||||
@@ -606,9 +606,9 @@ def test_calc_open_close_trade_price(
|
||||
trade.close_rate = 2.2
|
||||
trade.recalc_open_trade_value()
|
||||
assert isclose(trade._calc_open_trade_value(), open_value)
|
||||
assert isclose(trade.calc_close_trade_value(), close_value)
|
||||
assert isclose(trade.calc_profit(), round(profit, 8))
|
||||
assert pytest.approx(trade.calc_profit_ratio()) == profit_ratio
|
||||
assert isclose(trade.calc_close_trade_value(trade.close_rate), close_value)
|
||||
assert isclose(trade.calc_profit(trade.close_rate), round(profit, 8))
|
||||
assert pytest.approx(trade.calc_profit_ratio(trade.close_rate)) == profit_ratio
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_persistence")
|
||||
@@ -660,7 +660,7 @@ def test_calc_close_trade_price_exception(limit_buy_order_usdt, fee):
|
||||
trade.open_order_id = 'something'
|
||||
oobj = Order.parse_from_ccxt_object(limit_buy_order_usdt, 'ADA/USDT', 'buy')
|
||||
trade.update_trade(oobj)
|
||||
assert trade.calc_close_trade_value() == 0.0
|
||||
assert trade.calc_close_trade_value(trade.close_rate) == 0.0
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_persistence")
|
||||
@@ -813,7 +813,7 @@ def test_calc_close_trade_price(
|
||||
funding_fees=funding_fees
|
||||
)
|
||||
trade.open_order_id = 'close_trade'
|
||||
assert round(trade.calc_close_trade_value(rate=close_rate, fee=fee_rate), 8) == result
|
||||
assert round(trade.calc_close_trade_value(rate=close_rate), 8) == result
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -884,6 +884,17 @@ def test_calc_close_trade_price(
|
||||
('binance', False, 3, 2.2, 0.0025, 4.684999, 0.23366583, futures, -1),
|
||||
('binance', True, 1, 2.2, 0.0025, -7.315, -0.12222222, futures, -1),
|
||||
('binance', True, 3, 2.2, 0.0025, -7.315, -0.36666666, futures, -1),
|
||||
|
||||
# FUTURES, funding_fee=0
|
||||
('binance', False, 1, 2.1, 0.0025, 2.6925, 0.04476309, futures, 0),
|
||||
('binance', False, 3, 2.1, 0.0025, 2.6925, 0.13428928, futures, 0),
|
||||
('binance', True, 1, 2.1, 0.0025, -3.3074999, -0.05526316, futures, 0),
|
||||
('binance', True, 3, 2.1, 0.0025, -3.3074999, -0.16578947, futures, 0),
|
||||
|
||||
('binance', False, 1, 1.9, 0.0025, -3.2925, -0.05473815, futures, 0),
|
||||
('binance', False, 3, 1.9, 0.0025, -3.2925, -0.16421446, futures, 0),
|
||||
('binance', True, 1, 1.9, 0.0025, 2.7075, 0.0452381, futures, 0),
|
||||
('binance', True, 3, 1.9, 0.0025, 2.7075, 0.13571429, futures, 0),
|
||||
])
|
||||
@pytest.mark.usefixtures("init_persistence")
|
||||
def test_calc_profit(
|
||||
@@ -2258,6 +2269,7 @@ def test_Trade_object_idem():
|
||||
'get_exit_reason_performance',
|
||||
'get_enter_tag_performance',
|
||||
'get_mix_tag_performance',
|
||||
'get_trading_volume',
|
||||
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user