# source: https://raw.githubusercontent.com/xielk/freqtrade-test/925e067f080172a4581bc71ae9ee64be247606f4/user_data/strategies/SimpleFibonacciStrategy.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__SimpleFibonacciStrategy__20250910_084214(IStrategy):
    """
    简化的斐波那契策略 - 用于测试
    """
    
    # Strategy interface version
    INTERFACE_VERSION = 3

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

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

    # 最小ROI设置
    minimal_roi = {
        "60": 0.02,   # 1小时后2%收益
        "30": 0.03,   # 30分钟后3%收益
        "0": 0.05     # 立即5%收益
    }

    # 止损设置
    stoploss = -0.05  # 5%止损

    # 只处理新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 = 30

    # 订单类型
    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 populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        计算技术指标
        """
        # 计算RSI
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
        
        # 计算斐波那契回归水平 - 使用固定周期
        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)

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        简化的买入信号
        """
        dataframe.loc[
            (
                # 价格接近0.618斐波那契回归位
                (dataframe["close"] <= dataframe["fib_0.618"] * 1.05) &  # 允许5%的误差
                (dataframe["close"] >= dataframe["fib_0.618"] * 0.95) &
                
                # RSI显示超卖状态
                (dataframe["rsi"] <= 40) &
                
                # 确保有足够的数据
                (dataframe["volume"] > 0) &
                (dataframe["price_range"] > 0)
            ),
            "enter_long"
        ] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        简化的卖出信号
        """
        dataframe.loc[
            (
                # 价格接近0.382斐波那契回归位
                (dataframe["close"] >= dataframe["fib_0.382"] * 0.95) &  # 允许5%的误差
                (dataframe["close"] <= dataframe["fib_0.382"] * 1.05) &
                
                # RSI显示超买状态
                (dataframe["rsi"] >= 60) &
                
                # 确保有足够的数据
                (dataframe["volume"] > 0) &
                (dataframe["price_range"] > 0)
            ),
            "exit_long"
        ] = 1

        return dataframe
