2022-05-03 08:14:17 +00:00
|
|
|
import logging
|
2022-05-04 15:42:34 +00:00
|
|
|
from functools import reduce
|
2023-02-04 19:04:16 +00:00
|
|
|
from typing import Dict
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
import talib.abstract as ta
|
|
|
|
from pandas import DataFrame
|
|
|
|
from technical import qtpylib
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
from freqtrade.strategy import CategoricalParameter, IStrategy
|
2022-05-04 15:42:34 +00:00
|
|
|
|
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
class FreqaiExampleStrategy(IStrategy):
|
|
|
|
"""
|
2022-05-04 15:42:34 +00:00
|
|
|
Example strategy showing how the user connects their own
|
2022-05-03 08:14:17 +00:00
|
|
|
IFreqaiModel to the strategy. Namely, the user uses:
|
2022-07-23 13:58:31 +00:00
|
|
|
self.freqai.start(dataframe, metadata)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
to make predictions on their data. feature_engineering_*() automatically
|
|
|
|
generate the variety of features indicated by the user in the
|
2022-05-03 08:14:17 +00:00
|
|
|
canonical freqtrade configuration file under config['freqai'].
|
|
|
|
"""
|
|
|
|
|
2022-06-06 22:24:32 +00:00
|
|
|
minimal_roi = {"0": 0.1, "240": -1}
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
plot_config = {
|
2022-05-04 15:42:34 +00:00
|
|
|
"main_plot": {},
|
|
|
|
"subplots": {
|
2023-01-03 20:52:16 +00:00
|
|
|
"&-s_close": {"prediction": {"color": "blue"}},
|
2022-05-04 15:42:34 +00:00
|
|
|
"do_predict": {
|
|
|
|
"do_predict": {"color": "brown"},
|
2022-05-03 08:14:17 +00:00
|
|
|
},
|
2022-05-04 15:42:34 +00:00
|
|
|
},
|
2022-05-03 08:14:17 +00:00
|
|
|
}
|
|
|
|
|
2022-06-02 13:24:08 +00:00
|
|
|
process_only_new_candles = True
|
2022-05-03 08:14:17 +00:00
|
|
|
stoploss = -0.05
|
2022-06-02 13:24:08 +00:00
|
|
|
use_exit_signal = True
|
2022-08-22 16:19:07 +00:00
|
|
|
# this is the maximum period fed to talib (timeframe independent)
|
2022-09-03 12:00:01 +00:00
|
|
|
startup_candle_count: int = 40
|
2023-01-03 15:11:46 +00:00
|
|
|
can_short = True
|
2022-05-29 12:45:46 +00:00
|
|
|
|
2022-09-08 20:22:50 +00:00
|
|
|
std_dev_multiplier_buy = CategoricalParameter(
|
|
|
|
[0.75, 1, 1.25, 1.5, 1.75], default=1.25, space="buy", optimize=True)
|
|
|
|
std_dev_multiplier_sell = CategoricalParameter(
|
2022-09-18 15:00:55 +00:00
|
|
|
[0.75, 1, 1.25, 1.5, 1.75], space="sell", default=1.25, optimize=True)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
def feature_engineering_expand_all(self, dataframe: DataFrame, period: int,
|
|
|
|
metadata: Dict, **kwargs):
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
*Only functional with FreqAI enabled strategies*
|
|
|
|
This function will automatically expand the defined features on the config defined
|
|
|
|
`indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and
|
|
|
|
`include_corr_pairs`. In other words, a single feature defined in this function
|
|
|
|
will automatically expand to a total of
|
|
|
|
`indicator_periods_candles` * `include_timeframes` * `include_shifted_candles` *
|
|
|
|
`include_corr_pairs` numbers of features added to the model.
|
|
|
|
|
|
|
|
All features must be prepended with `%` to be recognized by FreqAI internals.
|
|
|
|
|
2023-02-04 15:53:17 +00:00
|
|
|
Access metadata such as the current pair/timeframe with:
|
2023-02-04 12:47:11 +00:00
|
|
|
|
2023-02-04 15:53:17 +00:00
|
|
|
`metadata["pair"]` `metadata["tf"]`
|
2023-02-04 12:47:11 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
More details on how these config defined parameters accelerate feature engineering
|
|
|
|
in the documentation at:
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-parameter-table/#feature-parameters
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-feature-engineering/#defining-the-features
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
:param dataframe: strategy dataframe which will receive the features
|
2022-12-27 14:37:01 +00:00
|
|
|
:param period: period of the indicator - usage example:
|
2023-02-04 19:04:16 +00:00
|
|
|
:param metadata: metadata of current pair
|
2022-12-27 14:37:01 +00:00
|
|
|
dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period)
|
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
|
2022-12-27 14:37:01 +00:00
|
|
|
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
|
|
|
|
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
|
|
|
|
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
|
|
|
|
dataframe["%-sma-period"] = ta.SMA(dataframe, timeperiod=period)
|
|
|
|
dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period)
|
|
|
|
|
|
|
|
bollinger = qtpylib.bollinger_bands(
|
|
|
|
qtpylib.typical_price(dataframe), window=period, stds=2.2
|
|
|
|
)
|
|
|
|
dataframe["bb_lowerband-period"] = bollinger["lower"]
|
|
|
|
dataframe["bb_middleband-period"] = bollinger["mid"]
|
|
|
|
dataframe["bb_upperband-period"] = bollinger["upper"]
|
|
|
|
|
|
|
|
dataframe["%-bb_width-period"] = (
|
|
|
|
dataframe["bb_upperband-period"]
|
|
|
|
- dataframe["bb_lowerband-period"]
|
|
|
|
) / dataframe["bb_middleband-period"]
|
|
|
|
dataframe["%-close-bb_lower-period"] = (
|
|
|
|
dataframe["close"] / dataframe["bb_lowerband-period"]
|
|
|
|
)
|
|
|
|
|
|
|
|
dataframe["%-roc-period"] = ta.ROC(dataframe, timeperiod=period)
|
|
|
|
|
|
|
|
dataframe["%-relative_volume-period"] = (
|
|
|
|
dataframe["volume"] / dataframe["volume"].rolling(period).mean()
|
|
|
|
)
|
|
|
|
|
|
|
|
return dataframe
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
def feature_engineering_expand_basic(self, dataframe: DataFrame, metadata: Dict, **kwargs):
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
*Only functional with FreqAI enabled strategies*
|
|
|
|
This function will automatically expand the defined features on the config defined
|
|
|
|
`include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`.
|
|
|
|
In other words, a single feature defined in this function
|
|
|
|
will automatically expand to a total of
|
|
|
|
`include_timeframes` * `include_shifted_candles` * `include_corr_pairs`
|
|
|
|
numbers of features added to the model.
|
|
|
|
|
|
|
|
Features defined here will *not* be automatically duplicated on user defined
|
|
|
|
`indicator_periods_candles`
|
|
|
|
|
|
|
|
All features must be prepended with `%` to be recognized by FreqAI internals.
|
|
|
|
|
2023-02-04 12:47:11 +00:00
|
|
|
Access metadata such as the current pair/timeframe with:
|
|
|
|
|
|
|
|
`metadata["pair"]` `metadata["tf"]`
|
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
More details on how these config defined parameters accelerate feature engineering
|
|
|
|
in the documentation at:
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-parameter-table/#feature-parameters
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-feature-engineering/#defining-the-features
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
:param dataframe: strategy dataframe which will receive the features
|
|
|
|
:param metadata: metadata of current pair
|
2022-12-27 14:37:01 +00:00
|
|
|
dataframe["%-pct-change"] = dataframe["close"].pct_change()
|
2022-12-28 12:25:40 +00:00
|
|
|
dataframe["%-ema-200"] = ta.EMA(dataframe, timeperiod=200)
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
|
|
|
dataframe["%-pct-change"] = dataframe["close"].pct_change()
|
|
|
|
dataframe["%-raw_volume"] = dataframe["volume"]
|
|
|
|
dataframe["%-raw_price"] = dataframe["close"]
|
|
|
|
return dataframe
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
def feature_engineering_standard(self, dataframe: DataFrame, metadata: Dict, **kwargs):
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
*Only functional with FreqAI enabled strategies*
|
|
|
|
This optional function will be called once with the dataframe of the base timeframe.
|
|
|
|
This is the final function to be called, which means that the dataframe entering this
|
|
|
|
function will contain all the features and columns created by all other
|
|
|
|
freqai_feature_engineering_* functions.
|
|
|
|
|
|
|
|
This function is a good place to do custom exotic feature extractions (e.g. tsfresh).
|
|
|
|
This function is a good place for any feature that should not be auto-expanded upon
|
|
|
|
(e.g. day of the week).
|
|
|
|
|
|
|
|
All features must be prepended with `%` to be recognized by FreqAI internals.
|
|
|
|
|
2023-02-04 12:47:11 +00:00
|
|
|
Access metadata such as the current pair with:
|
|
|
|
|
|
|
|
`metadata["pair"]`
|
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
More details about feature engineering available:
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-feature-engineering
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
:param dataframe: strategy dataframe which will receive the features
|
|
|
|
:param metadata: metadata of current pair
|
2022-12-27 14:37:01 +00:00
|
|
|
usage example: dataframe["%-day_of_week"] = (dataframe["date"].dt.dayofweek + 1) / 7
|
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
dataframe["%-day_of_week"] = dataframe["date"].dt.dayofweek
|
|
|
|
dataframe["%-hour_of_day"] = dataframe["date"].dt.hour
|
2022-12-27 14:37:01 +00:00
|
|
|
return dataframe
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
def set_freqai_targets(self, dataframe: DataFrame, metadata: Dict, **kwargs):
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
2022-12-28 12:25:40 +00:00
|
|
|
*Only functional with FreqAI enabled strategies*
|
2022-12-27 14:37:01 +00:00
|
|
|
Required function to set the targets for the model.
|
2022-12-28 12:25:40 +00:00
|
|
|
All targets must be prepended with `&` to be recognized by the FreqAI internals.
|
|
|
|
|
2023-02-04 12:47:11 +00:00
|
|
|
Access metadata such as the current pair with:
|
|
|
|
|
|
|
|
`metadata["pair"]`
|
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
More details about feature engineering available:
|
|
|
|
|
|
|
|
https://www.freqtrade.io/en/latest/freqai-feature-engineering
|
|
|
|
|
2023-02-04 19:04:16 +00:00
|
|
|
:param dataframe: strategy dataframe which will receive the targets
|
|
|
|
:param metadata: metadata of current pair
|
2022-12-27 14:37:01 +00:00
|
|
|
usage example: dataframe["&-target"] = dataframe["close"].shift(-1) / dataframe["close"]
|
|
|
|
"""
|
|
|
|
dataframe["&-s_close"] = (
|
|
|
|
dataframe["close"]
|
|
|
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
.mean()
|
|
|
|
/ dataframe["close"]
|
|
|
|
- 1
|
|
|
|
)
|
2022-08-14 15:19:50 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
# Classifiers are typically set up with strings as targets:
|
|
|
|
# df['&s-up_or_down'] = np.where( df["close"].shift(-100) >
|
|
|
|
# df["close"], 'up', 'down')
|
|
|
|
|
|
|
|
# If user wishes to use multiple targets, they can add more by
|
|
|
|
# appending more columns with '&'. User should keep in mind that multi targets
|
|
|
|
# requires a multioutput prediction model such as
|
2023-01-04 13:40:20 +00:00
|
|
|
# freqai/prediction_models/CatboostRegressorMultiTarget.py,
|
|
|
|
# freqtrade trade --freqaimodel CatboostRegressorMultiTarget
|
2022-12-28 12:25:40 +00:00
|
|
|
|
|
|
|
# df["&-s_range"] = (
|
|
|
|
# df["close"]
|
|
|
|
# .shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
# .rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
# .max()
|
|
|
|
# -
|
|
|
|
# df["close"]
|
|
|
|
# .shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
# .rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
|
|
# .min()
|
|
|
|
# )
|
2022-08-14 15:19:50 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
return dataframe
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
# All indicators must be populated by feature_engineering_*() functions
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-12-28 12:25:40 +00:00
|
|
|
# the model will return all labels created by user in `feature_engineering_*`
|
2022-07-21 10:24:22 +00:00
|
|
|
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
|
|
|
# the target mean/std values for each of the labels created by user in
|
2022-12-28 12:25:40 +00:00
|
|
|
# `set_freqai_targets()` for each training period.
|
2022-07-21 10:24:22 +00:00
|
|
|
|
2022-07-23 13:58:31 +00:00
|
|
|
dataframe = self.freqai.start(dataframe, metadata, self)
|
2022-12-28 12:25:40 +00:00
|
|
|
|
2022-09-08 20:22:50 +00:00
|
|
|
for val in self.std_dev_multiplier_buy.range:
|
2022-09-18 06:45:24 +00:00
|
|
|
dataframe[f'target_roi_{val}'] = (
|
|
|
|
dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * val
|
|
|
|
)
|
2022-09-08 20:22:50 +00:00
|
|
|
for val in self.std_dev_multiplier_sell.range:
|
2022-09-18 06:45:24 +00:00
|
|
|
dataframe[f'sell_roi_{val}'] = (
|
|
|
|
dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * val
|
|
|
|
)
|
2022-05-03 08:14:17 +00:00
|
|
|
return dataframe
|
|
|
|
|
2022-05-29 12:45:46 +00:00
|
|
|
def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-09-18 06:45:24 +00:00
|
|
|
enter_long_conditions = [
|
|
|
|
df["do_predict"] == 1,
|
|
|
|
df["&-s_close"] > df[f"target_roi_{self.std_dev_multiplier_buy.value}"],
|
|
|
|
]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-29 12:45:46 +00:00
|
|
|
if enter_long_conditions:
|
2022-06-02 12:37:40 +00:00
|
|
|
df.loc[
|
|
|
|
reduce(lambda x, y: x & y, enter_long_conditions), ["enter_long", "enter_tag"]
|
|
|
|
] = (1, "long")
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-09-18 06:45:24 +00:00
|
|
|
enter_short_conditions = [
|
|
|
|
df["do_predict"] == 1,
|
|
|
|
df["&-s_close"] < df[f"sell_roi_{self.std_dev_multiplier_sell.value}"],
|
|
|
|
]
|
2022-05-29 12:45:46 +00:00
|
|
|
|
|
|
|
if enter_short_conditions:
|
2022-06-02 12:37:40 +00:00
|
|
|
df.loc[
|
|
|
|
reduce(lambda x, y: x & y, enter_short_conditions), ["enter_short", "enter_tag"]
|
|
|
|
] = (1, "short")
|
2022-05-29 12:45:46 +00:00
|
|
|
|
|
|
|
return df
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-29 12:45:46 +00:00
|
|
|
def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
|
2022-09-18 06:45:24 +00:00
|
|
|
exit_long_conditions = [
|
|
|
|
df["do_predict"] == 1,
|
|
|
|
df["&-s_close"] < df[f"sell_roi_{self.std_dev_multiplier_sell.value}"] * 0.25,
|
|
|
|
]
|
2022-05-29 12:45:46 +00:00
|
|
|
if exit_long_conditions:
|
|
|
|
df.loc[reduce(lambda x, y: x & y, exit_long_conditions), "exit_long"] = 1
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-09-18 06:45:24 +00:00
|
|
|
exit_short_conditions = [
|
|
|
|
df["do_predict"] == 1,
|
|
|
|
df["&-s_close"] > df[f"target_roi_{self.std_dev_multiplier_buy.value}"] * 0.25,
|
|
|
|
]
|
2022-05-29 12:45:46 +00:00
|
|
|
if exit_short_conditions:
|
|
|
|
df.loc[reduce(lambda x, y: x & y, exit_short_conditions), "exit_short"] = 1
|
|
|
|
|
|
|
|
return df
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
def get_ticker_indicator(self):
|
2022-05-04 15:42:34 +00:00
|
|
|
return int(self.config["timeframe"][:-1])
|
2022-05-29 12:45:46 +00:00
|
|
|
|
2022-06-02 12:37:40 +00:00
|
|
|
def confirm_trade_entry(
|
|
|
|
self,
|
|
|
|
pair: str,
|
|
|
|
order_type: str,
|
|
|
|
amount: float,
|
|
|
|
rate: float,
|
|
|
|
time_in_force: str,
|
|
|
|
current_time,
|
|
|
|
entry_tag,
|
|
|
|
side: str,
|
2022-07-03 08:59:38 +00:00
|
|
|
**kwargs,
|
2022-06-02 12:37:40 +00:00
|
|
|
) -> bool:
|
2022-05-31 12:35:04 +00:00
|
|
|
|
|
|
|
df, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
|
|
|
last_candle = df.iloc[-1].squeeze()
|
|
|
|
|
2022-06-02 12:37:40 +00:00
|
|
|
if side == "long":
|
|
|
|
if rate > (last_candle["close"] * (1 + 0.0025)):
|
2022-05-31 12:35:04 +00:00
|
|
|
return False
|
|
|
|
else:
|
2022-06-02 12:37:40 +00:00
|
|
|
if rate < (last_candle["close"] * (1 - 0.0025)):
|
2022-05-31 12:35:04 +00:00
|
|
|
return False
|
2022-05-29 14:36:46 +00:00
|
|
|
|
|
|
|
return True
|