ruff format: Update test strategies

This commit is contained in:
Matthias
2024-05-12 15:41:07 +02:00
parent 099b1fc8c4
commit 8c7d80b78e
23 changed files with 420 additions and 462 deletions
@@ -12,7 +12,6 @@ from freqtrade.strategy.interface import IStrategy
class TestStrategyNoImplements(IStrategy):
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return super().populate_indicators(dataframe, metadata)
@@ -26,9 +25,15 @@ class TestStrategyImplementCustomSell(TestStrategyNoImplementSell):
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return super().populate_exit_trend(dataframe, metadata)
def custom_sell(self, pair: str, trade, current_time: datetime,
current_rate: float, current_profit: float,
**kwargs):
def custom_sell(
self,
pair: str,
trade,
current_time: datetime,
current_rate: float,
current_profit: float,
**kwargs,
):
return False
@@ -36,8 +41,9 @@ class TestStrategyImplementBuyTimeout(TestStrategyNoImplementSell):
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return super().populate_exit_trend(dataframe, metadata)
def check_buy_timeout(self, pair: str, trade, order: Order,
current_time: datetime, **kwargs) -> bool:
def check_buy_timeout(
self, pair: str, trade, order: Order, current_time: datetime, **kwargs
) -> bool:
return False
@@ -45,6 +51,7 @@ class TestStrategyImplementSellTimeout(TestStrategyNoImplementSell):
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return super().populate_exit_trend(dataframe, metadata)
def check_sell_timeout(self, pair: str, trade, order: Order,
current_time: datetime, **kwargs) -> bool:
def check_sell_timeout(
self, pair: str, trade, order: Order, current_time: datetime, **kwargs
) -> bool:
return False
@@ -6,25 +6,16 @@ from freqtrade.strategy import IStrategy
# Dummy strategy - no longer loads but raises an exception.
class TestStrategyLegacyV1(IStrategy):
minimal_roi = {
"40": 0.0,
"30": 0.01,
"20": 0.02,
"0": 0.04
}
minimal_roi = {"40": 0.0, "30": 0.01, "20": 0.02, "0": 0.04}
stoploss = -0.10
timeframe = '5m'
timeframe = "5m"
def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
return dataframe
def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
return dataframe
def populate_sell_trend(self, dataframe: DataFrame) -> DataFrame:
return dataframe
@@ -25,22 +25,20 @@ class freqai_rl_test_strat(IStrategy):
startup_candle_count: int = 300
can_short = False
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
metadata: Dict, **kwargs):
def feature_engineering_expand_all(
self, dataframe: DataFrame, period: int, metadata: Dict, **kwargs
):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
return dataframe
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-pct-change"] = dataframe["close"].pct_change()
dataframe["%-raw_volume"] = dataframe["volume"]
return dataframe
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
@@ -52,19 +50,16 @@ class freqai_rl_test_strat(IStrategy):
return dataframe
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["&-action"] = 0
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe = self.freqai.start(dataframe, metadata, self)
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
enter_long_conditions = [df["do_predict"] == 1, df["&-action"] == 1]
if enter_long_conditions:
@@ -57,9 +57,9 @@ class freqai_test_classifier(IStrategy):
informative_pairs.append((pair, tf))
return informative_pairs
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
metadata: Dict, **kwargs):
def feature_engineering_expand_all(
self, dataframe: DataFrame, period: int, metadata: Dict, **kwargs
):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
@@ -67,7 +67,6 @@ class freqai_test_classifier(IStrategy):
return dataframe
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-pct-change"] = dataframe["close"].pct_change()
dataframe["%-raw_volume"] = dataframe["volume"]
dataframe["%-raw_price"] = dataframe["close"]
@@ -75,7 +74,6 @@ class freqai_test_classifier(IStrategy):
return dataframe
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
@@ -83,13 +81,13 @@ class freqai_test_classifier(IStrategy):
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
self.freqai.class_names = ["down", "up"]
dataframe['&s-up_or_down'] = np.where(dataframe["close"].shift(-100) >
dataframe["close"], 'up', 'down')
dataframe["&s-up_or_down"] = np.where(
dataframe["close"].shift(-100) > dataframe["close"], "up", "down"
)
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
self.freqai_info = self.config["freqai"]
dataframe = self.freqai.start(dataframe, metadata, self)
@@ -97,15 +95,14 @@ class freqai_test_classifier(IStrategy):
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
enter_long_conditions = [df['&s-up_or_down'] == 'up']
enter_long_conditions = [df["&s-up_or_down"] == "up"]
if enter_long_conditions:
df.loc[
reduce(lambda x, y: x & y, enter_long_conditions), ["enter_long", "enter_tag"]
] = (1, "long")
enter_short_conditions = [df['&s-up_or_down'] == 'down']
enter_short_conditions = [df["&s-up_or_down"] == "down"]
if enter_short_conditions:
df.loc[
@@ -115,5 +112,4 @@ class freqai_test_classifier(IStrategy):
return df
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
return df
@@ -44,9 +44,9 @@ class freqai_test_multimodel_classifier_strat(IStrategy):
)
max_roi_time_long = IntParameter(0, 800, default=400, space="sell", optimize=False, load=True)
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
metadata: Dict, **kwargs):
def feature_engineering_expand_all(
self, dataframe: DataFrame, period: int, metadata: Dict, **kwargs
):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
@@ -54,7 +54,6 @@ class freqai_test_multimodel_classifier_strat(IStrategy):
return dataframe
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-pct-change"] = dataframe["close"].pct_change()
dataframe["%-raw_volume"] = dataframe["volume"]
dataframe["%-raw_price"] = dataframe["close"]
@@ -62,24 +61,23 @@ class freqai_test_multimodel_classifier_strat(IStrategy):
return dataframe
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
return dataframe
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["&s-up_or_down"] = np.where(
dataframe["close"].shift(-50) > dataframe["close"], "up", "down"
)
dataframe['&s-up_or_down'] = np.where(dataframe["close"].shift(-50) >
dataframe["close"], 'up', 'down')
dataframe['&s-up_or_down2'] = np.where(dataframe["close"].shift(-50) >
dataframe["close"], 'up2', 'down2')
dataframe["&s-up_or_down2"] = np.where(
dataframe["close"].shift(-50) > dataframe["close"], "up2", "down2"
)
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
self.freqai_info = self.config["freqai"]
dataframe = self.freqai.start(dataframe, metadata, self)
@@ -89,7 +87,6 @@ class freqai_test_multimodel_classifier_strat(IStrategy):
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
enter_long_conditions = [df["do_predict"] == 1, df["&-s_close"] > df["target_roi"]]
if enter_long_conditions:
@@ -43,9 +43,9 @@ class freqai_test_multimodel_strat(IStrategy):
)
max_roi_time_long = IntParameter(0, 800, default=400, space="sell", optimize=False, load=True)
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
metadata: Dict, **kwargs):
def feature_engineering_expand_all(
self, dataframe: DataFrame, period: int, metadata: Dict, **kwargs
):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
@@ -53,7 +53,6 @@ class freqai_test_multimodel_strat(IStrategy):
return dataframe
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-pct-change"] = dataframe["close"].pct_change()
dataframe["%-raw_volume"] = dataframe["volume"]
dataframe["%-raw_price"] = dataframe["close"]
@@ -61,14 +60,12 @@ class freqai_test_multimodel_strat(IStrategy):
return dataframe
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
return dataframe
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["&-s_close"] = (
dataframe["close"]
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
@@ -76,15 +73,14 @@ class freqai_test_multimodel_strat(IStrategy):
.mean()
/ dataframe["close"]
- 1
)
)
dataframe["&-s_range"] = (
dataframe["close"]
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
.max()
-
dataframe["close"]
- dataframe["close"]
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
.min()
@@ -93,7 +89,6 @@ class freqai_test_multimodel_strat(IStrategy):
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
self.freqai_info = self.config["freqai"]
dataframe = self.freqai.start(dataframe, metadata, self)
@@ -103,7 +98,6 @@ class freqai_test_multimodel_strat(IStrategy):
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
enter_long_conditions = [df["do_predict"] == 1, df["&-s_close"] > df["target_roi"]]
if enter_long_conditions:
+4 -9
View File
@@ -43,9 +43,9 @@ class freqai_test_strat(IStrategy):
)
max_roi_time_long = IntParameter(0, 800, default=400, space="sell", optimize=False, load=True)
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
metadata: Dict, **kwargs):
def feature_engineering_expand_all(
self, dataframe: DataFrame, period: int, metadata: Dict, **kwargs
):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
@@ -53,7 +53,6 @@ class freqai_test_strat(IStrategy):
return dataframe
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-pct-change"] = dataframe["close"].pct_change()
dataframe["%-raw_volume"] = dataframe["volume"]
dataframe["%-raw_price"] = dataframe["close"]
@@ -61,14 +60,12 @@ class freqai_test_strat(IStrategy):
return dataframe
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
return dataframe
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
dataframe["&-s_close"] = (
dataframe["close"]
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
@@ -76,12 +73,11 @@ class freqai_test_strat(IStrategy):
.mean()
/ dataframe["close"]
- 1
)
)
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
self.freqai_info = self.config["freqai"]
dataframe = self.freqai.start(dataframe, metadata, self)
@@ -91,7 +87,6 @@ class freqai_test_strat(IStrategy):
return dataframe
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
enter_long_conditions = [df["do_predict"] == 1, df["&-s_close"] > df["target_roi"]]
if enter_long_conditions:
+31 -35
View File
@@ -17,20 +17,18 @@ class HyperoptableStrategy(StrategyTestV3):
"""
buy_params = {
'buy_rsi': 35,
"buy_rsi": 35,
# Intentionally not specified, so "default" is tested
# 'buy_plusdi': 0.4
}
sell_params = {
'sell_rsi': 74,
'sell_minusdi': 0.4
}
sell_params = {"sell_rsi": 74, "sell_minusdi": 0.4}
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)
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)
@@ -43,10 +41,12 @@ class HyperoptableStrategy(StrategyTestV3):
def protections(self):
prot = []
if self.protection_enabled.value:
prot.append({
"method": "CooldownPeriod",
"stop_duration_candles": self.protection_cooldown_lookback.value
})
prot.append(
{
"method": "CooldownPeriod",
"stop_duration_candles": self.protection_cooldown_lookback.value,
}
)
return prot
bot_loop_started = False
@@ -60,7 +60,7 @@ class HyperoptableStrategy(StrategyTestV3):
Parameters can also be defined here ...
"""
self.bot_started = True
self.buy_rsi = IntParameter([0, 50], default=30, space='buy')
self.buy_rsi = IntParameter([0, 50], default=30, space="buy")
def informative_pairs(self):
"""
@@ -84,16 +84,14 @@ class HyperoptableStrategy(StrategyTestV3):
"""
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)
),
'buy'] = 1
(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)),
"buy",
] = 1
return dataframe
@@ -107,15 +105,13 @@ class HyperoptableStrategy(StrategyTestV3):
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)
),
'sell'] = 1
(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)),
"sell",
] = 1
return dataframe
@@ -15,20 +15,22 @@ class HyperoptableStrategyV2(StrategyTestV2):
"""
buy_params = {
'buy_rsi': 35,
"buy_rsi": 35,
# Intentionally not specified, so "default" is tested
# 'buy_plusdi': 0.4
}
sell_params = {
'sell_rsi': 74,
'sell_minusdi': 0.4
# Sell parameters
"sell_rsi": 74,
"sell_minusdi": 0.4,
}
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)
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)
@@ -36,10 +38,12 @@ class HyperoptableStrategyV2(StrategyTestV2):
def protections(self):
prot = []
if self.protection_enabled.value:
prot.append({
"method": "CooldownPeriod",
"stop_duration_candles": self.protection_cooldown_lookback.value
})
prot.append(
{
"method": "CooldownPeriod",
"stop_duration_candles": self.protection_cooldown_lookback.value,
}
)
return prot
bot_loop_started = False
@@ -51,4 +55,4 @@ class HyperoptableStrategyV2(StrategyTestV2):
"""
Parameters can also be defined here ...
"""
self.buy_rsi = IntParameter([0, 50], default=30, space='buy')
self.buy_rsi = IntParameter([0, 50], default=30, space="buy")
@@ -13,72 +13,73 @@ class InformativeDecoratorTest(IStrategy):
or strategy repository https://github.com/freqtrade/freqtrade-strategies
for samples and inspiration.
"""
INTERFACE_VERSION = 2
stoploss = -0.10
timeframe = '5m'
timeframe = "5m"
startup_candle_count: int = 20
def informative_pairs(self):
# Intentionally return 2 tuples, must be converted to 3 in compatibility code
return [
('NEO/USDT', '5m'),
('NEO/USDT', '15m', ''),
('NEO/USDT', '2h', 'futures'),
]
("NEO/USDT", "5m"),
("NEO/USDT", "15m", ""),
("NEO/USDT", "2h", "futures"),
]
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['buy'] = 0
dataframe["buy"] = 0
return dataframe
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['sell'] = 0
dataframe["sell"] = 0
return dataframe
# Decorator stacking test.
@informative('30m')
@informative('1h')
@informative("30m")
@informative("1h")
def populate_indicators_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
# Simple informative test.
@informative('1h', 'NEO/{stake}')
@informative("1h", "NEO/{stake}")
def populate_indicators_neo_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
@informative('1h', '{base}/BTC')
@informative("1h", "{base}/BTC")
def populate_indicators_base_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
# Quote currency different from stake currency test.
@informative('1h', 'ETH/BTC', candle_type='spot')
@informative("1h", "ETH/BTC", candle_type="spot")
def populate_indicators_eth_btc_1h(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
# Formatting test.
@informative('30m', 'NEO/{stake}', '{column}_{BASE}_{QUOTE}_{base}_{quote}_{asset}_{timeframe}')
@informative("30m", "NEO/{stake}", "{column}_{BASE}_{QUOTE}_{base}_{quote}_{asset}_{timeframe}")
def populate_indicators_btc_1h_2(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
# Custom formatter test
@informative('30m', 'ETH/{stake}', fmt=lambda column, **kwargs: column + '_from_callable')
@informative("30m", "ETH/{stake}", fmt=lambda column, **kwargs: column + "_from_callable")
def populate_indicators_eth_30m(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = 14
dataframe["rsi"] = 14
return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# Strategy timeframe indicators for current pair.
dataframe['rsi'] = 14
dataframe["rsi"] = 14
# Informative pairs are available in this method.
dataframe['rsi_less'] = dataframe['rsi'] < dataframe['rsi_1h']
dataframe["rsi_less"] = dataframe["rsi"] < dataframe["rsi_1h"]
# Mixing manual informative pairs with decorators.
informative = self.dp.get_pair_dataframe('NEO/USDT', '5m', '')
informative['rsi'] = 14
dataframe = merge_informative_pair(dataframe, informative, self.timeframe, '5m', ffill=True)
informative = self.dp.get_pair_dataframe("NEO/USDT", "5m", "")
informative["rsi"] = 14
dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "5m", ffill=True)
return dataframe
@@ -10,49 +10,44 @@ class strategy_test_v3_with_lookahead_bias(IStrategy):
INTERFACE_VERSION = 3
# Minimal ROI designed for the strategy
minimal_roi = {
"40": 0.0,
"30": 0.01,
"20": 0.02,
"0": 0.04
}
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'
scenario = CategoricalParameter(['no_bias', 'bias1'], default='bias1', space="buy")
timeframe = "5m"
scenario = CategoricalParameter(["no_bias", "bias1"], default="bias1", space="buy")
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = 20
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# bias is introduced here
if self.scenario.value != 'no_bias':
ichi = ichimoku(dataframe,
conversion_line_period=20,
base_line_periods=60,
laggin_span=120,
displacement=30)
dataframe['chikou_span'] = ichi['chikou_span']
if self.scenario.value != "no_bias":
ichi = ichimoku(
dataframe,
conversion_line_period=20,
base_line_periods=60,
laggin_span=120,
displacement=30,
)
dataframe["chikou_span"] = ichi["chikou_span"]
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
if self.scenario.value == 'no_bias':
dataframe.loc[dataframe['close'].shift(10) < dataframe['close'], 'enter_long'] = 1
if self.scenario.value == "no_bias":
dataframe.loc[dataframe["close"].shift(10) < dataframe["close"], "enter_long"] = 1
else:
dataframe.loc[dataframe['close'].shift(-10) > dataframe['close'], 'enter_long'] = 1
dataframe.loc[dataframe["close"].shift(-10) > dataframe["close"], "enter_long"] = 1
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
if self.scenario.value == 'no_bias':
dataframe.loc[
dataframe['close'].shift(10) < dataframe['close'], 'exit'] = 1
if self.scenario.value == "no_bias":
dataframe.loc[dataframe["close"].shift(10) < dataframe["close"], "exit"] = 1
else:
dataframe.loc[
dataframe['close'].shift(-10) > dataframe['close'], 'exit'] = 1
dataframe.loc[dataframe["close"].shift(-10) > dataframe["close"], "exit"] = 1
return dataframe
+39 -47
View File
@@ -15,28 +15,24 @@ class StrategyTestV2(IStrategy):
or strategy repository https://github.com/freqtrade/freqtrade-strategies
for samples and inspiration.
"""
INTERFACE_VERSION = 2
# Minimal ROI designed for the strategy
minimal_roi = {
"40": 0.0,
"30": 0.01,
"20": 0.02,
"0": 0.04
}
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'
timeframe = "5m"
# Optional order type mapping
order_types = {
'entry': 'limit',
'exit': 'limit',
'stoploss': 'limit',
'stoploss_on_exchange': False
"entry": "limit",
"exit": "limit",
"stoploss": "limit",
"stoploss_on_exchange": False,
}
# Number of candles the strategy requires before producing valid signals
@@ -44,8 +40,8 @@ class StrategyTestV2(IStrategy):
# Optional time in force for orders
order_time_in_force = {
'entry': 'gtc',
'exit': 'gtc',
"entry": "gtc",
"exit": "gtc",
}
# Test legacy use_sell_signal definition
use_sell_signal = False
@@ -69,36 +65,36 @@ class StrategyTestV2(IStrategy):
# ------------------------------------
# ADX
dataframe['adx'] = ta.ADX(dataframe)
dataframe["adx"] = ta.ADX(dataframe)
# MACD
macd = ta.MACD(dataframe)
dataframe['macd'] = macd['macd']
dataframe['macdsignal'] = macd['macdsignal']
dataframe['macdhist'] = macd['macdhist']
dataframe["macd"] = macd["macd"]
dataframe["macdsignal"] = macd["macdsignal"]
dataframe["macdhist"] = macd["macdhist"]
# Minus Directional Indicator / Movement
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
dataframe["minus_di"] = ta.MINUS_DI(dataframe)
# Plus Directional Indicator / Movement
dataframe['plus_di'] = ta.PLUS_DI(dataframe)
dataframe["plus_di"] = ta.PLUS_DI(dataframe)
# RSI
dataframe['rsi'] = ta.RSI(dataframe)
dataframe["rsi"] = ta.RSI(dataframe)
# Stoch fast
stoch_fast = ta.STOCHF(dataframe)
dataframe['fastd'] = stoch_fast['fastd']
dataframe['fastk'] = stoch_fast['fastk']
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']
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)
dataframe["ema10"] = ta.EMA(dataframe, timeperiod=10)
return dataframe
@@ -111,16 +107,14 @@ class StrategyTestV2(IStrategy):
"""
dataframe.loc[
(
(dataframe['rsi'] < 35) &
(dataframe['fastd'] < 35) &
(dataframe['adx'] > 30) &
(dataframe['plus_di'] > 0.5)
) |
(
(dataframe['adx'] > 65) &
(dataframe['plus_di'] > 0.5)
),
'buy'] = 1
(dataframe["rsi"] < 35)
& (dataframe["fastd"] < 35)
& (dataframe["adx"] > 30)
& (dataframe["plus_di"] > 0.5)
)
| ((dataframe["adx"] > 65) & (dataframe["plus_di"] > 0.5)),
"buy",
] = 1
return dataframe
@@ -134,15 +128,13 @@ class StrategyTestV2(IStrategy):
dataframe.loc[
(
(
(qtpylib.crossed_above(dataframe['rsi'], 70)) |
(qtpylib.crossed_above(dataframe['fastd'], 70))
) &
(dataframe['adx'] > 10) &
(dataframe['minus_di'] > 0)
) |
(
(dataframe['adx'] > 70) &
(dataframe['minus_di'] > 0.5)
),
'sell'] = 1
(qtpylib.crossed_above(dataframe["rsi"], 70))
| (qtpylib.crossed_above(dataframe["fastd"], 70))
)
& (dataframe["adx"] > 10)
& (dataframe["minus_di"] > 0)
)
| ((dataframe["adx"] > 70) & (dataframe["minus_di"] > 0.5)),
"sell",
] = 1
return dataframe
+78 -78
View File
@@ -25,15 +25,11 @@ class StrategyTestV3(IStrategy):
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
}
minimal_roi = {"40": 0.0, "30": 0.01, "20": 0.02, "0": 0.04}
# Optimal max_open_trades for the strategy
max_open_trades = -1
@@ -42,14 +38,14 @@ class StrategyTestV3(IStrategy):
stoploss = -0.10
# Optimal timeframe for the strategy
timeframe = '5m'
timeframe = "5m"
# Optional order type mapping
order_types = {
'entry': 'limit',
'exit': 'limit',
'stoploss': 'limit',
'stoploss_on_exchange': False
"entry": "limit",
"exit": "limit",
"stoploss": "limit",
"stoploss_on_exchange": False,
}
# Number of candles the strategy requires before producing valid signals
@@ -57,26 +53,24 @@ class StrategyTestV3(IStrategy):
# Optional time in force for orders
order_time_in_force = {
'entry': 'gtc',
'exit': 'gtc',
"entry": "gtc",
"exit": "gtc",
}
buy_params = {
'buy_rsi': 35,
"buy_rsi": 35,
# Intentionally not specified, so "default" is tested
# 'buy_plusdi': 0.4
}
sell_params = {
'sell_rsi': 74,
'sell_minusdi': 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)
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)
@@ -97,67 +91,61 @@ class StrategyTestV3(IStrategy):
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)
dataframe["adx"] = ta.ADX(dataframe)
# MACD
macd = ta.MACD(dataframe)
dataframe['macd'] = macd['macd']
dataframe['macdsignal'] = macd['macdsignal']
dataframe['macdhist'] = macd['macdhist']
dataframe["macd"] = macd["macd"]
dataframe["macdsignal"] = macd["macdsignal"]
dataframe["macdhist"] = macd["macdhist"]
# Minus Directional Indicator / Movement
dataframe['minus_di'] = ta.MINUS_DI(dataframe)
dataframe["minus_di"] = ta.MINUS_DI(dataframe)
# Plus Directional Indicator / Movement
dataframe['plus_di'] = ta.PLUS_DI(dataframe)
dataframe["plus_di"] = ta.PLUS_DI(dataframe)
# RSI
dataframe['rsi'] = ta.RSI(dataframe)
dataframe["rsi"] = ta.RSI(dataframe)
# Stoch fast
stoch_fast = ta.STOCHF(dataframe)
dataframe['fastd'] = stoch_fast['fastd']
dataframe['fastk'] = stoch_fast['fastk']
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']
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)
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'] = 1
(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",
] = 1
dataframe.loc[
(
qtpylib.crossed_below(dataframe['rsi'], self.sell_rsi.value)
),
('enter_short', 'enter_tag')] = (1, 'short_Tag')
(qtpylib.crossed_below(dataframe["rsi"], self.sell_rsi.value)),
("enter_short", "enter_tag"),
] = (1, "short_Tag")
return dataframe
@@ -165,41 +153,53 @@ class StrategyTestV3(IStrategy):
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'] = 1
(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",
] = 1
dataframe.loc[
(
qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)
),
('exit_short', 'exit_tag')] = (1, 'short_Tag')
(qtpylib.crossed_above(dataframe["rsi"], self.buy_rsi.value)),
("exit_short", "exit_tag"),
] = (1, "short_Tag")
return dataframe
def leverage(self, pair: str, current_time: datetime, current_rate: float,
proposed_leverage: float, max_leverage: float, entry_tag: Optional[str],
side: str, **kwargs) -> float:
def leverage(
self,
pair: str,
current_time: datetime,
current_rate: float,
proposed_leverage: float,
max_leverage: float,
entry_tag: Optional[str],
side: str,
**kwargs,
) -> float:
# Return 3.0 in all cases.
# Bot-logic must make sure it's an allowed leverage and eventually adjust accordingly.
return 3.0
def adjust_trade_position(self, trade: Trade, current_time: datetime,
current_rate: float, current_profit: float,
min_stake: Optional[float], max_stake: float,
current_entry_rate: float, current_exit_rate: float,
current_entry_profit: float, current_exit_profit: float,
**kwargs) -> Optional[float]:
def adjust_trade_position(
self,
trade: Trade,
current_time: datetime,
current_rate: float,
current_profit: float,
min_stake: Optional[float],
max_stake: float,
current_entry_rate: float,
current_exit_rate: float,
current_entry_profit: float,
current_exit_profit: float,
**kwargs,
) -> Optional[float]:
if current_profit < -0.0075:
orders = trade.select_filled_orders(trade.entry_side)
return round(orders[0].stake_amount, 0)
@@ -17,24 +17,28 @@ class StrategyTestV3CustomEntryPrice(StrategyTestV3):
or strategy repository https://github.com/freqtrade/freqtrade-strategies
for samples and inspiration.
"""
new_entry_price: float = 0.001
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
dataframe['volume'] > 0,
'enter_long'] = 1
dataframe.loc[dataframe["volume"] > 0, "enter_long"] = 1
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return dataframe
def custom_entry_price(self, pair: str, trade: Optional[Trade], current_time: datetime,
proposed_rate: float,
entry_tag: Optional[str], side: str, **kwargs) -> float:
def custom_entry_price(
self,
pair: str,
trade: Optional[Trade],
current_time: datetime,
proposed_rate: float,
entry_tag: Optional[str],
side: str,
**kwargs,
) -> float:
return self.new_entry_price
@@ -10,37 +10,33 @@ class strategy_test_v3_recursive_issue(IStrategy):
INTERFACE_VERSION = 3
# Minimal ROI designed for the strategy
minimal_roi = {
"0": 0.04
}
minimal_roi = {"0": 0.04}
# Optimal stoploss designed for the strategy
stoploss = -0.10
# Optimal timeframe for the strategy
timeframe = '5m'
scenario = CategoricalParameter(['no_bias', 'bias1', 'bias2'], default='bias1', space="buy")
timeframe = "5m"
scenario = CategoricalParameter(["no_bias", "bias1", "bias2"], default="bias1", space="buy")
# Number of candles the strategy requires before producing valid signals
startup_candle_count: int = 100
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
# bias is introduced here
if self.scenario.value == 'no_bias':
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
if self.scenario.value == "no_bias":
dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
else:
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=50)
dataframe["rsi"] = ta.RSI(dataframe, timeperiod=50)
if self.scenario.value == 'bias2':
if self.scenario.value == "bias2":
# Has both bias1 and bias2
dataframe['rsi_lookahead'] = ta.RSI(dataframe, timeperiod=50).shift(-1)
dataframe["rsi_lookahead"] = ta.RSI(dataframe, timeperiod=50).shift(-1)
return dataframe
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return dataframe
def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
return dataframe