# filename: lot_strategy.py

from freqtrade.strategy import IStrategy, DecimalParameter
from freqtrade.persistence import Trade
from pandas import DataFrame


class LotStrategy(IStrategy):
    """
    Estrategia de ejemplo:
    - Compra inicial al cruce de EMA corta sobre EMA larga.
    - Compra adicional si el precio cae un % definido.
    - Venta parcial a ciertos niveles de beneficio optimizables.
    """

    timeframe = '5m'
    minimal_roi = {}
    stoploss = -0.20
    trailing_stop = False

    # Parámetro configurable: porcentaje de caída para comprar lote adicional
    dca_buydown = DecimalParameter(0.01, 0.05, default=0.02, space="buy", optimize=True)

    # Parámetro configurable: beneficio para venta parcial
    take_profit_partial = DecimalParameter(0.02, 0.10, default=0.05, space="sell", optimize=True)

    # Parámetro configurable: beneficio para venta total
    take_profit_full = DecimalParameter(0.06, 0.20, default=0.10, space="sell", optimize=True)

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema_fast'] = dataframe['close'].ewm(span=10, adjust=False).mean()
        dataframe['ema_slow'] = dataframe['close'].ewm(span=50, adjust=False).mean()
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['ema_fast'] > dataframe['ema_slow']) &
                (dataframe['ema_fast'].shift(1) <= dataframe['ema_slow'].shift(1))
            ),
            'enter_long'] = 1
        return dataframe


    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['exit_long'] = 0
        return dataframe

    def custom_exit(self, pair: str, trade: Trade, current_time, current_rate, current_profit, **kwargs):
        """
        Ventas parciales por lotes:
        - Si beneficio >= take_profit_partial, vende el 50%.
        - Si beneficio >= take_profit_full, vende el 100% restante.
        """
        sell_reason = None
        sell_rate = None
        sell_amount = None

        if current_profit >= self.take_profit_full.value:
            sell_reason = 'TakeProfitFull'
            sell_amount = 1.0  # Vende todo
        elif current_profit >= self.take_profit_partial.value:
            sell_reason = 'TakeProfitPartial'
            sell_amount = 0.5  # Vende la mitad

        if sell_reason:
            return (sell_reason, sell_rate, sell_amount)
        return None

    def should_enter(self, trade: Trade, current_price: float, **kwargs) -> bool:
        """
        Compra por lotes (DCA simple):
        - Si el precio cae más que dca_buydown% desde el precio de entrada, vuelve a comprar.
        """
        if trade is None:
            return False
        avg_entry = trade.open_rate
        threshold = avg_entry * (1 - self.dca_buydown.value)
        return current_price <= threshold

    def custom_entry(self, pair: str, current_price: float, entry_tag: str, **kwargs):
        """
        Ejecutar compra adicional si se cumplen condiciones de should_enter.
        """
        if self.should_enter(kwargs.get('trade'), current_price):
            return (entry_tag, current_price, 1.0)  # Compra completa (puedes poner fracciones)
        return None
