# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement # flake8: noqa: F401 # isort: skip_file # --- Do not remove these libs --- import numpy as np import pandas as pd from pandas import DataFrame from datetime import datetime from typing import Optional, Union from freqtrade.strategy import (BooleanParameter, CategoricalParameter, DecimalParameter, IntParameter, IStrategy, merge_informative_pair) # -------------------------------- # Add your lib to import here import talib.abstract as ta import freqtrade.vendor.qtpylib.indicators as qtpylib class RsiMaStrategy(IStrategy): """ Simple RSI + Moving Average Strategy This strategy combines RSI (Relative Strength Index) and Moving Average indicators to generate entry and exit signals. Entry conditions: - RSI < rsi_buy_threshold (oversold) - Price > SMA (uptrend) - Volume > average volume Exit conditions: - RSI > rsi_sell_threshold (overbought) - Price < SMA (downtrend) - Stop loss at -5% - Take profit at +10% """ # Strategy interface version - allow new iterations of the strategy interface. # Check the documentation or the Sample strategy to get the latest version. INTERFACE_VERSION = 3 # Can this strategy go short? can_short: bool = False # Minimal ROI designed for the strategy. # This attribute will be overridden if the config file contains "minimal_roi". minimal_roi = { "60": 0.01, "30": 0.02, "0": 0.04 } # Optimal stoploss designed for the strategy. # This attribute will be overridden if the config file contains "stoploss". stoploss = -0.05 # Trailing stoploss trailing_stop = False # trailing_stop_positive = 0.01 # trailing_stop_positive_offset = 0.0 # Disabled / not configured # Optimal timeframe for the strategy. timeframe = '5m' # Run "populate_indicators" only for new candle. process_only_new_candles = False # These values can be overridden in the config. use_exit_signal = True exit_profit_only = False ignore_roi_if_entry_signal = False # Hyperoptable parameters rsi_buy_threshold = IntParameter(20, 40, default=30, space="buy") rsi_sell_threshold = IntParameter(60, 80, default=70, space="sell") sma_period = IntParameter(10, 50, default=20, space="buy") volume_factor = DecimalParameter(1.0, 2.0, default=1.2, space="buy") # Number of candles the strategy requires before producing valid signals startup_candle_count: int = 30 # Optional order type mapping. order_types = { 'entry': 'limit', 'exit': 'limit', 'stoploss': 'market', 'stoploss_on_exchange': False } # Optional order time in force. order_time_in_force = { 'entry': 'GTC', 'exit': 'GTC' } plot_config = { 'main_plot': { 'sma': {'color': 'blue'}, }, 'subplots': { "RSI": { 'rsi': {'color': 'red'}, } } } def informative_pairs(self): """ Define additional, informative pair/interval combinations to be cached from the exchange. These pairs will automatically be available in the populate_indicators() method. """ return [] def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Adds several different TA indicators to the given DataFrame Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies """ # RSI dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) # Simple Moving Average dataframe['sma'] = ta.SMA(dataframe, timeperiod=self.sma_period.value) # Volume moving average dataframe['volume_sma'] = ta.SMA(dataframe['volume'], timeperiod=20) # MACD macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] # 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_percent"] = ( (dataframe["close"] - dataframe["bb_lowerband"]) / (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) ) dataframe["bb_width"] = ( (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"] ) return dataframe def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Based on TA indicators, populates the entry signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with entry columns populated """ dataframe.loc[ ( # RSI is oversold (dataframe['rsi'] < self.rsi_buy_threshold.value) & # Price is above SMA (uptrend) (dataframe['close'] > dataframe['sma']) & # Volume is above average (dataframe['volume'] > (dataframe['volume_sma'] * self.volume_factor.value)) & # MACD is positive (dataframe['macd'] > dataframe['macdsignal']) & # Price is not at the upper Bollinger Band (avoid buying at peaks) (dataframe['close'] < dataframe['bb_upperband']) & # Volume check (dataframe['volume'] > 0) ), 'enter_long'] = 1 return dataframe def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Based on TA indicators, populates the exit signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with exit columns populated """ dataframe.loc[ ( # RSI is overbought (dataframe['rsi'] > self.rsi_sell_threshold.value) | # Price is below SMA (downtrend) (dataframe['close'] < dataframe['sma']) | # MACD turns negative (dataframe['macd'] < dataframe['macdsignal']) | # Price hits upper Bollinger Band (dataframe['close'] >= dataframe['bb_upperband']) ), 'exit_long'] = 1 return dataframe def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: """ Custom stoploss logic, returning the new distance relative to current_rate (as ratio). e.g. returning -0.05 would create a stoploss 5% below current_rate. The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-customization/ When not implemented by a strategy, returns the initial stoploss value Only called when use_custom_stoploss is set to True. :param pair: Pair that's currently analyzed :param trade: trade object. :param current_time: datetime object, containing the current datetime :param current_rate: Rate, calculated based on pricing settings in exit_pricing. :param current_profit: Current profit (as ratio), calculated based on current_rate. :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return float: New stoploss value, relative to the current_rate """ return self.stoploss