# source: https://raw.githubusercontent.com/xielk/freqtrade-test/925e067f080172a4581bc71ae9ee64be247606f4/user_data/strategies/SimpleHarmonicDivergence.py
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
# --- Do not remove these imports ---
import numpy as np
import pandas as pd
from datetime import datetime, timedelta, timezone
from pandas import DataFrame
from typing import Dict, Optional, Union, Tuple

from freqtrade.strategy import (
    IStrategy,
    Trade,
    Order,
    PairLocks,
    informative,  # @informative decorator
    # Hyperopt Parameters
    BooleanParameter,
    CategoricalParameter,
    DecimalParameter,
    IntParameter,
    RealParameter,
    # timeframe helpers
    timeframe_to_minutes,
    timeframe_to_next_date,
    timeframe_to_prev_date,
    # Strategy helper functions
    merge_informative_pair,
    stoploss_from_absolute,
    stoploss_from_open,
    AnnotationType,
)

# --------------------------------
# Add your lib to import here
import talib.abstract as ta
from technical import qtpylib


class Github_xielk_freqtrade_test__SimpleHarmonicDivergence__20250910_084214(IStrategy):
    """
    简化版谐波背离策略
    """
    
    # Strategy interface version
    INTERFACE_VERSION = 3

    # 策略时间框架
    timeframe = "15m"

    # 是否支持做空
    can_short: bool = False

    # 最小ROI设置
    minimal_roi = {
        "0": 0.02
    }

    # 止损设置
    stoploss = -0.06

    # 只处理新K线
    process_only_new_candles = True

    # 策略参数
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # 策略启动所需的K线数量
    startup_candle_count: int = 50

    # 订单类型
    order_types = {
        "entry": "limit",
        "exit": "limit",
        "stoploss": "market",
        "stoploss_on_exchange": False
    }

    # 订单时间
    order_time_in_force = {
        "entry": "GTC",
        "exit": "GTC"
    }

    def informative_pairs(self):
        return []

    def detect_simple_divergence(self, dataframe: DataFrame, lookback: int = 10) -> DataFrame:
        """
        简化的背离检测
        """
        dataframe["bullish_divergence"] = False
        dataframe["bearish_divergence"] = False
        
        for i in range(lookback, len(dataframe)):
            # 获取窗口数据
            price_window = dataframe["close"].iloc[i-lookback:i+1]
            rsi_window = dataframe["rsi"].iloc[i-lookback:i+1]
            
            # 看涨背离：价格创新低，RSI没有创新低
            if (price_window.iloc[-1] == price_window.min() and 
                rsi_window.iloc[-1] > rsi_window.min()):
                dataframe.loc[dataframe.index[i], "bullish_divergence"] = True
            
            # 看跌背离：价格创新高，RSI没有创新高
            if (price_window.iloc[-1] == price_window.max() and 
                rsi_window.iloc[-1] < rsi_window.max()):
                dataframe.loc[dataframe.index[i], "bearish_divergence"] = True
        
        return dataframe

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        计算技术指标
        """
        # 计算RSI
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
        
        # 计算MACD
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]
        
        # 计算斐波那契
        period = 30
        dataframe["highest"] = dataframe["high"].rolling(window=period).max()
        dataframe["lowest"] = dataframe["low"].rolling(window=period).min()
        dataframe["price_range"] = dataframe["highest"] - dataframe["lowest"]
        
        dataframe["fib_0.618"] = dataframe["highest"] - 0.618 * dataframe["price_range"]
        dataframe["fib_0.382"] = dataframe["highest"] - 0.382 * dataframe["price_range"]
        
        # 计算EMA
        dataframe["ema_20"] = ta.EMA(dataframe, timeperiod=20)
        
        # 检测背离
        dataframe = self.detect_simple_divergence(dataframe, lookback=10)
        
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        基于背离的买入信号
        """
        dataframe.loc[
            (
                # 检测到看涨背离
                (dataframe["bullish_divergence"]) &
                # 价格接近斐波那契支撑位
                ((dataframe["close"] <= dataframe["fib_0.618"] * 1.05) & 
                 (dataframe["close"] >= dataframe["fib_0.618"] * 0.95)) &
                # RSI显示超卖
                (dataframe["rsi"] < 40) &
                # 价格在EMA20之上
                (dataframe["close"] > dataframe["ema_20"]) &
                # 有成交量
                (dataframe["volume"] > 0)
            ),
            "enter_long"
        ] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        基于背离的卖出信号
        """
        dataframe.loc[
            (
                # 检测到看跌背离
                (dataframe["bearish_divergence"]) &
                # 价格接近斐波那契阻力位
                ((dataframe["close"] >= dataframe["fib_0.382"] * 0.95) & 
                 (dataframe["close"] <= dataframe["fib_0.382"] * 1.05)) &
                # RSI显示超买
                (dataframe["rsi"] > 60) &
                # 有成交量
                (dataframe["volume"] > 0)
            ),
            "exit_long"
        ] = 1

        return dataframe
