# source: https://raw.githubusercontent.com/G3niusYukki/ethstrategy/a589f8ead2929251d4b8f0496a171cb755d305fe/user_data/strategies/ETHStrategy.py
# 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 pandas_ta as pta
from freqtrade.persistence import Trade


class Github_G3niusYukki_ethstrategy__ETHStrategy__20260210_125247(IStrategy):
    """
    ETH Trading Strategy combining RSI and MACD
    
    Strategy Logic:
    - Entry: RSI < 30 (oversold) AND MACD histogram crosses above signal line
    - Exit: RSI > 70 (overbought) OR MACD histogram crosses below signal line
    - Uses 5-minute timeframe for quick reactions to ETH volatility
    - Includes trailing stop loss for profit protection
    """

    INTERFACE_VERSION = 3

    # Optimal timeframe for the strategy
    timeframe = '5m'

    # Can this strategy go short?
    can_short: bool = False

    # Minimal ROI designed for the strategy
    # This attribute will override the 'minimal_roi' from the config
    minimal_roi = {
        "0": 0.10,      # 10% profit target
        "30": 0.05,     # After 30 minutes, 5% profit
        "60": 0.03,     # After 1 hour, 3% profit
        "120": 0.01     # After 2 hours, 1% profit
    }

    # Optimal stoploss designed for the strategy
    stoploss = -0.05  # 5% stop loss

    # Trailing stoploss
    trailing_stop = True
    trailing_stop_positive = 0.01
    trailing_stop_positive_offset = 0.02
    trailing_only_offset_is_reached = True

    # Run "populate_indicators()" only for new candle
    process_only_new_candles = True

    # These values can be overridden in the config
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count: int = 30

    # Strategy parameters
    buy_rsi = IntParameter(20, 40, default=30, space="buy")
    sell_rsi = IntParameter(60, 80, default=70, space="sell")
    
    # MACD parameters
    macd_fast = IntParameter(8, 16, default=12, space="buy")
    macd_slow = IntParameter(20, 30, default=26, space="buy")
    macd_signal = IntParameter(7, 12, default=9, space="buy")

    def informative_pairs(self):
        """
        Define additional, informative pair/interval combinations to be cached from the exchange.
        """
        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.
        """

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # MACD
        macd = ta.MACD(dataframe, 
                      fastperiod=self.macd_fast.value,
                      slowperiod=self.macd_slow.value, 
                      signalperiod=self.macd_signal.value)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        # Bollinger Bands for additional context
        bollinger = ta.BBANDS(dataframe, timeperiod=20, nbdevup=2.0, nbdevdn=2.0)
        dataframe['bb_lowerband'] = bollinger['lowerband']
        dataframe['bb_middleband'] = bollinger['middleband']
        dataframe['bb_upperband'] = bollinger['upperband']
        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']

        # Volume
        dataframe['volume_mean'] = dataframe['volume'].rolling(window=20).mean()

        # ATR for volatility
        dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the entry signal for the given dataframe
        """
        dataframe.loc[
            (
                # RSI oversold
                (dataframe['rsi'] < self.buy_rsi.value) &
                
                # MACD histogram crosses above signal (bullish)
                (dataframe['macdhist'] > 0) &
                (dataframe['macdhist'].shift(1) <= 0) &
                
                # Price near lower Bollinger Band (potential bounce)
                (dataframe['bb_percent'] < 0.3) &
                
                # Volume confirmation
                (dataframe['volume'] > dataframe['volume_mean']) &
                
                # Guard: price is not 0
                (dataframe['close'] > 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
        """
        dataframe.loc[
            (
                (
                    # RSI overbought
                    (dataframe['rsi'] > self.sell_rsi.value) |
                    
                    # MACD histogram crosses below signal (bearish)
                    (
                        (dataframe['macdhist'] < 0) &
                        (dataframe['macdhist'].shift(1) >= 0)
                    )
                ) &
                
                # Volume confirmation
                (dataframe['volume'] > 0)
            ),
            'exit_long'] = 1
        
        return dataframe
