# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
import numpy as np
import pandas as pd
from pandas import DataFrame
from freqtrade.strategy import (
    IStrategy,
    IntParameter,
    DecimalParameter,
    CategoricalParameter,
)
import talib.abstract as ta
from technical import qtpylib


class TrendPullbackStrategy(IStrategy):
    """
    Buy pullbacks in uptrends, avoid catching falling knives.

    Core fixes vs SimpleStrategy:
    - Tight stoploss (-5 to -8%) — cuts losers FAST
    - EMA trend filter — only buys when price is above EMA200
    - ATR-based trailing — adapts to volatility
    - RSI oversold entry — buys the dip, not the rip

    Why this works better:
    - BTC was profitable in SimpleStrategy (trend-friendly)
    - Alts got wrecked by -22% stops in downtrends
    - Filtering for uptrend + tight stops = asymmetric risk/reward
    """
    INTERFACE_VERSION = 3
    timeframe = "5m"
    can_short: bool = False

    # No ROI table — use stoploss + trailing for exits
    minimal_roi = {}

    # Tight stop — cut losers before they destroy wins
    stoploss = -0.06

    # Trailing stop kicks in after +5% profit, then trails at 3%
    trailing_stop = True
    trailing_only_offset_is_reached = True
    trailing_stop_positive = 0.03
    trailing_stop_positive_offset = 0.05

    process_only_new_candles = True
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    position_adjustment_enable = True

    startup_candle_count: int = 300

    # --- Hyperopt parameters ---
    # Trend filter: must be above this EMA to enter
    buy_ema_trend = IntParameter(100, 300, default=200, space="buy", optimize=True)

    # RSI oversold threshold — lower = more selective
    buy_rsi_max = IntParameter(25, 50, default=35, space="buy", optimize=True)

    # RSI exit — higher = lets winners run longer
    sell_rsi_min = IntParameter(65, 85, default=75, space="sell", optimize=True)

    # Volume filter — skip low volume entries
    buy_volume_factor = DecimalParameter(1.0, 2.5, default=1.2, space="buy", optimize=True)

    # Bollinger Band squeeze filter
    buy_bb_percent_min = DecimalParameter(0.0, 0.3, default=0.0, space="buy", optimize=True)
    buy_bb_percent_max = DecimalParameter(0.3, 0.8, default=0.5, space="buy", optimize=True)

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # --- Trend detection ---
        dataframe["ema20"] = ta.EMA(dataframe, timeperiod=20)
        dataframe["ema50"] = ta.EMA(dataframe, timeperiod=50)
        dataframe["ema100"] = ta.EMA(dataframe, timeperiod=100)
        dataframe["ema200"] = ta.EMA(dataframe, timeperiod=200)

        # --- Momentum ---
        dataframe["rsi"] = ta.RSI(dataframe)
        dataframe["stoch_fast"] = ta.STOCHF(dataframe)["fastk"]

        # --- Volatility ---
        dataframe["atr"] = ta.ATR(dataframe, timeperiod=14)
        bollinger = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=2
        )
        dataframe["bb_lowerband"] = bollinger["lower"]
        dataframe["bb_middleband"] = bollinger["mid"]
        dataframe["bb_upperband"] = bollinger["upper"]
        dataframe["bb_percent"] = (
            (dataframe["close"] - dataframe["bb_lowerband"])
            / (dataframe["bb_upperband"] - dataframe["bb_lowerband"])
        )

        # --- Volume ---
        dataframe["volume_mean_20"] = dataframe["volume"].rolling(20).mean()

        # --- MACD (for confirmation) ---
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]
        dataframe["macdhist"] = macd["macdhist"]

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                # 1. TREND FILTER — price must be above EMA200 (in uptrend)
                (dataframe["close"] > dataframe["ema200"])
                # 2. RSI PULLBACK — RSI dipped below threshold (oversold in uptrend)
                & (dataframe["rsi"] < self.buy_rsi_max.value)
                # 3. RSI RECOVERY — RSI starting to turn up (not still falling)
                & (dataframe["rsi"] > dataframe["rsi"].shift(1))
                # 4. VOLUME — above average (not a ghost trade)
                & (dataframe["volume"] > dataframe["volume_mean_20"] * self.buy_volume_factor.value)
                # 5. BB POSITION — not at the top of the band (buy the dip)
                & (dataframe["bb_percent"] > self.buy_bb_percent_min.value)
                & (dataframe["bb_percent"] < self.buy_bb_percent_max.value)
            ),
            "enter_long",
        ] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                # Exit on RSI overbought OR trend breaks
                (dataframe["rsi"] > self.sell_rsi_min.value)
                | (dataframe["close"] < dataframe["ema20"])
            ),
            "exit_long",
        ] = 1
        return dataframe

    def adjust_trade_position(self, trade, current_profit, **kwargs):
        """
        Partial exits — lock in gains on volatile pairs.
        Tier 1: 25% at +4% profit
        Tier 2: 25% at +8% profit
        Remaining 50% rides the trailing stop
        """
        if trade.is_short:
            return None

        if current_profit >= 0.04 and trade.nr_of_successful_exits == 0:
            return (-0.25, "TP1: 25% at +4%")

        if current_profit >= 0.08 and trade.nr_of_successful_exits == 1:
            return (-0.25, "TP2: 25% at +8%")

        return None
