# source: https://raw.githubusercontent.com/WKoniczynski/freqtrade_bot/9741a5c7ea4195be4bf2bc959d26a09fd18fc06a/user_data/strategies/rsi_strategy.py
import talib
from freqtrade.strategy import IStrategy
from pandas import DataFrame


class Github_WKoniczynski_freqtrade_bot__rsi_strategy__20260408_073618(IStrategy):
    """
    RSI (Relative Strength Index) Strategy
    
    Entry: When RSI < 30 (oversold conditions)
    Exit: When RSI > 70 (overbought conditions)
    
    This is a mean-reversion strategy that assumes oversold assets
    will bounce back up.
    """

    INTERFACE_VERSION = 3
    
    # RSI parameters
    buy_rsi_threshold = 30
    sell_rsi_threshold = 70
    rsi_period = 14
    
    # Stoploss
    stoploss = -0.10
    
    # Trailing stop
    trailing_stop = False
    
    # Optimal timeframe
    timeframe = '5m'
    
    # Can short
    can_short = False

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Add technical indicators to the dataframe.
        """
        # Calculate RSI
        dataframe['rsi'] = talib.RSI(dataframe['close'], timeperiod=self.rsi_period)
        
        # Calculate additional indicators for confirmation
        dataframe['sma_20'] = talib.SMA(dataframe['close'], timeperiod=20)
        dataframe['bb_upper'], dataframe['bb_middle'], dataframe['bb_lower'] = talib.BBANDS(
            dataframe['close'], timeperiod=20, nbdevup=2, nbdevdn=2
        )
        
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Populate BUY signal for the given dataframe.
        
        Buy when RSI is oversold AND price is above 20-period SMA (uptrend confirmation)
        """
        dataframe.loc[
            (
                # RSI oversold condition
                (dataframe['rsi'] < self.buy_rsi_threshold) &
                # Confirmation: Price above SMA (uptrend)
                (dataframe['close'] > dataframe['sma_20']) &
                # Volume filter
                (dataframe['volume'] > 0)
            ),
            'enter_long'] = 1
            
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Populate SELL signal for the given dataframe.
        
        Sell when RSI is overbought
        """
        dataframe.loc[
            (
                # RSI overbought condition
                (dataframe['rsi'] > self.sell_rsi_threshold) &
                (dataframe['volume'] > 0)
            ),
            'exit_long'] = 1

        return dataframe
