# Filename: VwapMacdCrossBelowZeroStrategy.py

from freqtrade.strategy import IStrategy
from pandas import DataFrame
import talib

class VwapStrategy(IStrategy):
    """
    Estrategia:
    - Compra si el precio cruza VWAP al alza y MACD cruza señal al alza, ambos por debajo de cero.
    - Venta cuando MACD cruza señal a la baja.
    """

    timeframe = "5m"

    minimal_roi = {
        "0": 0.049,
        "5": 0.036,
        "14": 0.013,
        "16": 0
    }
    stoploss = -0.02
    trailing_stop = False

    position_adjustment_enable = False

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # VWAP con longitud 14
        vwap_length = 14
        typical_price = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3
        tp_vol = typical_price * dataframe['volume']
        dataframe['vwap'] = tp_vol.rolling(window=vwap_length, min_periods=1).sum() / dataframe['volume'].rolling(window=vwap_length, min_periods=1).sum()

        # MACD
        macd, macdsignal, _ = talib.MACD(
            dataframe['close'],
            fastperiod=12,
            slowperiod=26,
            signalperiod=9
        )
        dataframe['macd'] = macd
        dataframe['macdsignal'] = macdsignal

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['enter_long'] = 0

        for i in range(1, len(dataframe)):
            # Comprobación de datos válidos
            if (
                dataframe['vwap'].iloc[i - 1] is None or
                dataframe['vwap'].iloc[i] is None or
                dataframe['macd'].iloc[i - 1] is None or
                dataframe['macd'].iloc[i] is None or
                dataframe['macdsignal'].iloc[i - 1] is None or
                dataframe['macdsignal'].iloc[i] is None
            ):
                continue

            # Cruce precio sobre VWAP en vela actual
            cross_vwap = (
                dataframe['close'].iloc[i - 1] < dataframe['vwap'].iloc[i - 1]
                and dataframe['close'].iloc[i] > dataframe['vwap'].iloc[i]
            )

            # Cruce MACD al alza en vela actual
            cross_macd = (
                dataframe['macd'].iloc[i - 1] < dataframe['macdsignal'].iloc[i - 1]
                and dataframe['macd'].iloc[i] > dataframe['macdsignal'].iloc[i]
            )

            # Ambas líneas MACD por debajo de 0
            macd_below_zero = (
                dataframe['macd'].iloc[i] < 0
                and dataframe['macdsignal'].iloc[i] < 0
            )

            if cross_vwap and cross_macd and macd_below_zero:
                dataframe.loc[dataframe.index[i], 'enter_long'] = 1

        return dataframe

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

        for i in range(1, len(dataframe)):
            if (
                dataframe['macd'].iloc[i - 1] > dataframe['macdsignal'].iloc[i - 1]
                and dataframe['macd'].iloc[i] < dataframe['macdsignal'].iloc[i]
            ):
                dataframe.loc[dataframe.index[i], 'exit_long'] = 1

        return dataframe
