# source: https://raw.githubusercontent.com/Zer0phucks/trading-lab/90a6eef67476f5a442f148722ac2f56de8ee2fd1/user_data/strategies/RangeBetaV1.py
from __future__ import annotations

from pandas import DataFrame
import talib.abstract as ta

from freqtrade.strategy import DecimalParameter, IStrategy


class Github_Zer0phucks_trading_lab__RangeBetaV1__20260505_075652(IStrategy):
    INTERFACE_VERSION = 3

    timeframe = "5m"
    can_short = False
    process_only_new_candles = True
    startup_candle_count = 120

    minimal_roi = {"0": 0.025, "90": 0.01, "240": 0.0}
    stoploss = -0.055
    trailing_stop = False

    buy_rsi = DecimalParameter(20.0, 38.0, default=31.0, decimals=1, space="buy")
    sell_rsi = DecimalParameter(55.0, 75.0, default=64.0, decimals=1, space="sell")

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        bollinger = ta.BBANDS(dataframe, timeperiod=20, nbdevup=2.0, nbdevdn=2.0)
        dataframe["bb_lower"] = bollinger["lowerband"]
        dataframe["bb_mid"] = bollinger["middleband"]
        dataframe["bb_upper"] = bollinger["upperband"]
        dataframe["bb_width"] = (dataframe["bb_upper"] - dataframe["bb_lower"]) / dataframe["bb_mid"]
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
        dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)
        dataframe["volume_mean_30"] = dataframe["volume"].rolling(30).mean()
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe["adx"] < 20)
                & (dataframe["bb_width"] > 0)
                & (dataframe["close"] < dataframe["bb_lower"])
                & (dataframe["rsi"] < self.buy_rsi.value)
                & (dataframe["volume"] > 0)
            ),
            "enter_long",
        ] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe["close"] > dataframe["bb_mid"])
                | (dataframe["rsi"] > self.sell_rsi.value)
            ),
            "exit_long",
        ] = 1
        return dataframe
