# source: https://raw.githubusercontent.com/secondlinger/WinnieBari/169c792f21e234c203210dd10e4c6fbbd813bbe2/user_data/strategies/CustomRLStrategy.py
import pandas as pd
import talib.abstract as ta
from pandas import DataFrame

from freqtrade.strategy import IStrategy

class Github_secondlinger_WinnieBari__CustomRLStrategy__20250926_145841(IStrategy):
    """
    An effective Reinforcement Learning strategy for FreqAI.
    """
    timeframe = "5m"
    can_short = True

    # RL agent controls exits, so these are disabled.
    stoploss = -0.99
    minimal_roi = {"0": 100}
    trailing_stop = False

    process_only_new_candles = True
    startup_candle_count = 200

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Base indicators for the strategy.
        """
        # These are kept minimal as most features are generated in feature_engineering_*
        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['rsi'] = ta.RSI(dataframe)
        dataframe['ema_20'] = ta.EMA(dataframe, timeperiod=20)
        dataframe['ema_50'] = ta.EMA(dataframe, timeperiod=50)

        # Start FreqAI processing
        dataframe = self.freqai.start(dataframe, metadata, self)
        return dataframe

    def feature_engineering_standard(self, dataframe: DataFrame, **kwargs) -> DataFrame:
        """
        Generate features for the RL model.
        All feature columns must be prefixed with '%-'.
        """

        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['rsi'] = ta.RSI(dataframe)
        dataframe['ema_20'] = ta.EMA(dataframe, timeperiod=20)
        dataframe['ema_50'] = ta.EMA(dataframe, timeperiod=50)

        # Required raw price data
        dataframe["%-raw_close"] = dataframe["close"]
        dataframe["%-raw_open"] = dataframe["open"]
        dataframe["%-raw_high"] = dataframe["high"]
        dataframe["%-raw_low"] = dataframe["low"]

        # Percentage change features
        for i in range(1, 5):
            dataframe[f'%-return_shift_{i}'] = dataframe['close'].pct_change(i)

        # Volatility
        dataframe['%-atr_14'] = ta.ATR(dataframe, timeperiod=14)

        # Trend
        dataframe['%-adx_14'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['%-rsi_14'] = ta.RSI(dataframe, timeperiod=14)

        # Price relative to EMAs
        dataframe['%-ema_20_dist'] = (dataframe['close'] - dataframe['ema_20']) / dataframe['ema_20']
        dataframe['%-ema_50_dist'] = (dataframe['close'] - dataframe['ema_50']) / dataframe['ema_50']

        # Fill NaNs created by indicators
        dataframe.fillna(0, inplace=True)

        return dataframe

    def set_freqai_targets(self, dataframe: DataFrame, **kwargs) -> DataFrame:
        """
        This method is required by FreqAI.
        For RL, we simply initialize the action column.
        """
        dataframe["&-action"] = 0
        return dataframe

    def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
        """
        Interpret the RL agent's actions for entries.
        """
        # Long Entry: Action 1
        df.loc[
            (df["do_predict"] == 1) & (df["&-action"] == 1),
            ["enter_long", "enter_tag"]
        ] = (1, f"{metadata['pair']}_long")

        # Short Entry: Action 3
        df.loc[
            (df["do_predict"] == 1) & (df["&-action"] == 3),
            ["enter_short", "enter_tag"]
        ] = (1, f"{metadata['pair']}_short")

        return df

    def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
        """
        Interpret the RL agent's actions for exits.
        """
        # Long Exit: Action 2
        df.loc[
            (df["do_predict"] == 1) & (df["&-action"] == 2),
            "exit_long"
        ] = 1

        # Short Exit: Action 4
        df.loc[
            (df["do_predict"] == 1) & (df["&-action"] == 4),
            "exit_short"
        ] = 1

        return df