from freqtrade.strategy import IStrategy, IntParameter, DecimalParameter
from pandas import DataFrame
import talib as ta

class Prometheus(IStrategy):
    timeframe = '1m'

    # Parámetro optimizable para el RSI de compra
    #rsi_buy = IntParameter(10, 50, default=30, space="buy")
    rsi_deviation_threshold = DecimalParameter(0.5, 2.0, default=1.0, decimals=2, space="buy")
    rsi_window = IntParameter(10, 60, default=30, space="buy")
    #macd_fast_period = IntParameter(5, 20, default=12, space="buy")
    #macd_slow_period = IntParameter(20, 50, default=26, space="buy")
    #macd_signal_period = IntParameter(5, 20, default=9, space="buy")

    
    minimal_roi = {
        "0": 0.012  # 1.2% de ROI
    }

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Calcula el RSI
        dataframe['rsi'] = ta.RSI(dataframe['close'], timeperiod=14)
        #dataframe['stoch_rsi'], _ = ta.STOCHRSI(dataframe['close'], timeperiod=14, fastk_period=3, fastd_period=3, fastd_matype=0)
        
         # Calcula el MACD
        #dataframe['macd'], dataframe['macd_signal'], dataframe['macd_hist'] = ta.MACD(
        #    dataframe['close'],
        #    fastperiod=self.macd_fast_period.value,
        #    slowperiod=self.macd_slow_period.value,
        #    signalperiod=self.macd_signal_period.value
        #)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Señal de compra basada en RSI
        #dataframe.loc[
        #    (dataframe['rsi'] < self.rsi_buy.value),
        #    'buy'] = 1
        
        # Calcula la media del RSI usando una ventana optimizable en cada iteración
        dataframe['rsi_avg'] = dataframe['rsi'].rolling(window=self.rsi_window.value).mean()
        #dataframe['stoch_rsi_avg'] = dataframe['stoch_rsi'].rolling(window=self.rsi_window.value).mean()
        
        # Señal de compra cuando el RSI es un porcentaje específico respecto a su media de los últimos 30 minutos
        dataframe.loc[
            (dataframe['rsi'] < dataframe['rsi_avg'] * self.rsi_deviation_threshold.value),
            'buy'] = 1
        #dataframe.loc[
        #    (dataframe['stoch_rsi'] < dataframe['stoch_rsi_avg'] * self.rsi_deviation_threshold.value),
        #    'buy'] = 1
        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Vender cuando el RSI es mayor a 70 (puedes ajustar esto también si lo necesitas)
        #dataframe.loc[
        #    (dataframe['rsi'] > 70),
        #    'sell'] = 1
        return dataframe
