# source: https://raw.githubusercontent.com/BestiaTantrica/mi-n8n/d10908a9f97669a5127ed3c522485f282c717b60/freqtrade-docker/user_data/strategies/GuruStrategy.py
from freqtrade.strategy import IStrategy
from pandas import DataFrame
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
import requests
import datetime

class Github_BestiaTantrica_mi_n8n__GuruStrategy__20260101_160701(IStrategy):
    """
    Estrategia Guru: Combina indicadores técnicos con sentimiento externo de n8n.
    Incluye un mecanismo de "Heartbeat" para mantener activo Render.
    """
    # Configuraciones de la estrategia
    INTERFACE_VERSION = 3
    minimal_roi = {"0": 0.1}
    stoploss = -0.05
    timeframe = '5m'

    # Variable para almacenar el sentimiento (actualizada vía Heartbeat)
    custom_info = {"sentiment": 0, "last_heartbeat": None}

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Indicadores técnicos básicos
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20)
        dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
        
        # Bollinger Bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']

        # Ejecutar Heartbeat cada 10 minutos
        self.check_heartbeat()

        return dataframe

    def check_heartbeat(self):
        """Envía un ping a Render para mantenerlo despierto y obtener sentimiento."""
        now = datetime.datetime.now()
        if self.custom_info["last_heartbeat"] is None or (now - self.custom_info["last_heartbeat"]).seconds > 600:
            try:
                # URL de tu webhook de n8n en Render
                render_url = "https://tu-url-de-render.com/webhook/heartbeat"
                response = requests.get(render_url, timeout=5)
                if response.status_code == 200:
                    data = response.json()
                    self.custom_info["sentiment"] = data.get("sentiment", 0)
                    self.custom_info["last_heartbeat"] = now
                    print(f"Guru Heartbeat: Render despertado. Sentimiento actual: {self.custom_info['sentiment']}")
            except Exception as e:
                print(f"Error en Heartbeat: {e}")

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['rsi'] < 30) &
                (dataframe['close'] < dataframe['bb_lowerband']) &
                (self.custom_info["sentiment"] > 50) # Solo entra si el sentimiento es positivo
            ),
            'enter_long'] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['rsi'] > 70) |
                (self.custom_info["sentiment"] < -50) # Sale si el sentimiento es muy negativo
            ),
            'exit_long'] = 1
        return dataframe
