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


class Github_WKoniczynski_freqtrade_bot__bollinger_band_strategy__20260408_073618(IStrategy):
    """
    Bollinger Band Strategy
    
    Entry: When price crosses below the lower Bollinger Band (oversold)
    Exit: When price crosses above the middle Bollinger Band (mean reversion)
    """

    INTERFACE_VERSION = 3
    
    # Bollinger Bands parameters
    bb_period = 20
    bb_dev = 2.0
    
    # 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 Bollinger Bands
        dataframe['bb_lower'], dataframe['bb_middle'], dataframe['bb_upper'] = talib.BBANDS(
            dataframe['close'], 
            timeperiod=self.bb_period, 
            nbdevup=self.bb_dev, 
            nbdevdn=self.bb_dev
        )
        
        # Optional: RSI for confirmation
        dataframe['rsi'] = talib.RSI(dataframe['close'], timeperiod=14)
        
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Populate BUY signal for the given dataframe.
        
        Buy when price crosses below lower Bollinger Band AND RSI is oversold.
        """
        dataframe.loc[
            (
                (dataframe['close'] < dataframe['bb_lower']) &
                (dataframe['rsi'] < 30) &  # RSI oversold confirmation
                (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 price crosses above middle Bollinger Band.
        """
        dataframe.loc[
            (
                (dataframe['close'] > dataframe['bb_middle']) &
                (dataframe['volume'] > 0)
            ),
            'exit_long'] = 1

        return dataframe
