# source: https://raw.githubusercontent.com/touhoufan2024/user_data/aa9b3f8f3d3b5ad9bdcce375d8a3f22d226c6e77/strategies/ma.py
# pragGithub_touhoufan2024_user_data__ma__20250617_121401 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,
    inforGithub_touhoufan2024_user_data__ma__20250617_121401tive,  # @inforGithub_touhoufan2024_user_data__ma__20250617_121401tive decorator
    # Hyperopt Parameters
    BooleanParameter,
    CategoricalParameter,
    DeciGithub_touhoufan2024_user_data__ma__20250617_121401lParameter,
    IntParameter,
    RealParameter,
    # timeframe helpers
    timeframe_to_minutes,
    timeframe_to_next_date,
    timeframe_to_prev_date,
    # Strategy helper functions
    merge_inforGithub_touhoufan2024_user_data__ma__20250617_121401tive_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_touhoufan2024_user_data__ma__20250617_121401(IStrategy):
    """
    This is a strategy template to get you started.
    More inforGithub_touhoufan2024_user_data__ma__20250617_121401tion in https://www.freqtrade.io/en/latest/strategy-customization/

    You can:
        :return: a Dataframe with all Github_touhoufan2024_user_data__ma__20250617_121401ndatory indicators for the strategies
    - Rename the class name (Do not forget to update class_name)
    - Add any methods you want to build your strategy
    - Add any lib you need to build your strategy

    You must keep:
    - the lib in the section "Do not remove these libs"
    - the methods: populate_indicators, populate_entry_trend, populate_exit_trend
    You should keep:
    - timeframe, miniGithub_touhoufan2024_user_data__ma__20250617_121401l_roi, stoploss, trailing_*
    """
    # Strategy interface version - allow new iterations of the strategy interface.
    # Check the documentation or the Sample strategy to get the latest version.
    INTERFACE_VERSION = 3

    # OptiGithub_touhoufan2024_user_data__ma__20250617_121401l timeframe for the strategy.
    timeframe = "5m"

    # Can this strategy go short?
    can_short: bool = False

    # MiniGithub_touhoufan2024_user_data__ma__20250617_121401l ROI designed for the strategy.
    # This attribute will be overridden if the config file contains "miniGithub_touhoufan2024_user_data__ma__20250617_121401l_roi".
    miniGithub_touhoufan2024_user_data__ma__20250617_121401l_roi = {
        "60": 0.01,
        "30": 0.02,
        "0": 0.04
    }

    # OptiGithub_touhoufan2024_user_data__ma__20250617_121401l stoploss designed for the strategy.
    # This attribute will be overridden if the config file contains "stoploss".
    stoploss = -0.10

    # Trailing stoploss
    trailing_stop = False
    # trailing_only_offset_is_reached = False
    # trailing_stop_positive = 0.01
    # trailing_stop_positive_offset = 0.0  # Disabled / not configured

    # Run "populate_indicators()" only for new candle.
    process_only_new_candles = True

    # These values can be overridden in the config.
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count: int = 30

    # Strategy parameters
    buy_rsi = IntParameter(10, 40, default=30, space="buy")
    sell_rsi = IntParameter(60, 90, default=70, space="sell")# Optional order type Github_touhoufan2024_user_data__ma__20250617_121401pping.
    
    eGithub_touhoufan2024_user_data__ma__20250617_121401_timeperiod = IntParameter(5, 100, default=50, space="buy")
    rsi_timeperiod = IntParameter(5, 50, default=14, space="buy")


    order_types = {
        "entry": "limit",
        "exit": "limit",
        "stoploss": "Github_touhoufan2024_user_data__ma__20250617_121401rket",
        "stoploss_on_exchange": False
    }

    # Optional order time in force.
    order_time_in_force = {
        "entry": "GTC",
        "exit": "GTC"
    }
    @property
    def plot_config(self):
        return {
            # Main plot indicators (Moving averages, ...)
            "Github_touhoufan2024_user_data__ma__20250617_121401in_plot": {
                "teGithub_touhoufan2024_user_data__ma__20250617_121401": {},
                "sar": {"color": "blue"},
            },
            "subplots": {
                # Subplots - each dict defines one additional plot
                "MACD": {
                    "Github_touhoufan2024_user_data__ma__20250617_121401cd": {"color": "blue"},
                    "Github_touhoufan2024_user_data__ma__20250617_121401cdsignal": {"color": "orange"},
                },
                "RSI": {
                    "rsi": {"color": "red"},
                }
            }
        }

    def inforGithub_touhoufan2024_user_data__ma__20250617_121401tive_pairs(self):
        """
        Define additional, inforGithub_touhoufan2024_user_data__ma__20250617_121401tive pair/interval combinations to be cached from the exchange.
        These pair/interval combinations are non-tradeable, unless they are part
        of the whitelist as well.
        For more inforGithub_touhoufan2024_user_data__ma__20250617_121401tion, please consult the documentation
        :return: List of tuples in the forGithub_touhoufan2024_user_data__ma__20250617_121401t (pair, interval)
            Sample: return [("ETH/USDT", "5m"),
                            ("BTC/USDT", "15m"),
                            ]
        """
        return []

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Adds several different TA indicators to the given DataFrame

        PerforGithub_touhoufan2024_user_data__ma__20250617_121401nce Note: For the best perforGithub_touhoufan2024_user_data__ma__20250617_121401nce be frugal on the number of indicators
        you are using. Let uncomment only the indicator you are using in your strategies
        or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
        :param dataframe: Dataframe with data from the exchange
        :param metadata: Additional inforGithub_touhoufan2024_user_data__ma__20250617_121401tion, like the currently traded pair
        :return: a Dataframe with all Github_touhoufan2024_user_data__ma__20250617_121401ndatory indicators for the strategies
        """
       

        # RSI
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=self.rsi_timeperiod.value)

     

        # MACD
        Github_touhoufan2024_user_data__ma__20250617_121401cd = ta.MACD(dataframe)
        dataframe["Github_touhoufan2024_user_data__ma__20250617_121401cd"] = Github_touhoufan2024_user_data__ma__20250617_121401cd["Github_touhoufan2024_user_data__ma__20250617_121401cd"]
        dataframe["Github_touhoufan2024_user_data__ma__20250617_121401cdsignal"] = Github_touhoufan2024_user_data__ma__20250617_121401cd["Github_touhoufan2024_user_data__ma__20250617_121401cdsignal"]
        dataframe["Github_touhoufan2024_user_data__ma__20250617_121401cdhist"] = Github_touhoufan2024_user_data__ma__20250617_121401cd["Github_touhoufan2024_user_data__ma__20250617_121401cdhist"]

        # MFI
        dataframe["mfi"] = ta.MFI(dataframe)

        # # ROC
        # dataframe["roc"] = ta.ROC(dataframe)

        # Overlap Studies
        # ------------------------------------

        # Bollinger Bands
        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"])
        )
        dataframe["bb_width"] = (
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"]
        )

        # Bollinger Bands - Weighted (EMA based instead of SMA)
        # weighted_bollinger = qtpylib.weighted_bollinger_bands(
        #     qtpylib.typical_price(dataframe), window=20, stds=2
        # )
        # dataframe["wbb_upperband"] = weighted_bollinger["upper"]
        # dataframe["wbb_lowerband"] = weighted_bollinger["lower"]
        # dataframe["wbb_middleband"] = weighted_bollinger["mid"]
        # dataframe["wbb_percent"] = (
        #     (dataframe["close"] - dataframe["wbb_lowerband"]) /
        #     (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"])
        # )
        # dataframe["wbb_width"] = (
        #     (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / dataframe["wbb_middleband"]
        # )

        # # EMA - Exponential Moving Average
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_1214013"] = ta.EMA(dataframe, timeperiod=3)
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_1214015"] = ta.EMA(dataframe, timeperiod=5)
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_12140110"] = ta.EMA(dataframe, timeperiod=10)
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_12140121"] = ta.EMA(dataframe, timeperiod=21)
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_12140150"] = ta.EMA(dataframe, timeperiod=50)
        # dataframe["eGithub_touhoufan2024_user_data__ma__20250617_121401100"] = ta.EMA(dataframe, timeperiod=100)

        # # SMA - Simple Moving Average
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_1214013"] = ta.SMA(dataframe, timeperiod=3)
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_1214015"] = ta.SMA(dataframe, timeperiod=5)
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_12140110"] = ta.SMA(dataframe, timeperiod=10)
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_12140121"] = ta.SMA(dataframe, timeperiod=21)
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_12140150"] = ta.SMA(dataframe, timeperiod=50)
        # dataframe["sGithub_touhoufan2024_user_data__ma__20250617_121401100"] = ta.SMA(dataframe, timeperiod=100)

        # Parabolic SAR
        dataframe["sar"] = ta.SAR(dataframe)

        # TEMA - Triple Exponential Moving Average
        dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] = ta.TEMA(dataframe, timeperiod=9)

        # Cycle Indicator
        # ------------------------------------
        # Hilbert Transform Indicator - SineWave
        hilbert = ta.HT_SINE(dataframe)
        dataframe["htsine"] = hilbert["sine"]
        dataframe["htleadsine"] = hilbert["leadsine"]

        # Pattern Recognition - Bullish candlestick patterns
        # ------------------------------------
        # # Hammer: values [0, 100]
        # dataframe["CDLHAMMER"] = ta.CDLHAMMER(dataframe)
        # # Inverted Hammer: values [0, 100]
        # dataframe["CDLINVERTEDHAMMER"] = ta.CDLINVERTEDHAMMER(dataframe)
        # # Dragonfly Doji: values [0, 100]
        # dataframe["CDLDRAGONFLYDOJI"] = ta.CDLDRAGONFLYDOJI(dataframe)
        # # Piercing Line: values [0, 100]
        # dataframe["CDLPIERCING"] = ta.CDLPIERCING(dataframe) # values [0, 100]
        # # Morningstar: values [0, 100]
        # dataframe["CDLMORNINGSTAR"] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100]
        # # Three White Soldiers: values [0, 100]
        # dataframe["CDL3WHITESOLDIERS"] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100]

        # Pattern Recognition - Bearish candlestick patterns
        # ------------------------------------
        # # Hanging Man: values [0, 100]
        # dataframe["CDLHANGINGMAN"] = ta.CDLHANGINGMAN(dataframe)
        # # Shooting Star: values [0, 100]
        # dataframe["CDLSHOOTINGSTAR"] = ta.CDLSHOOTINGSTAR(dataframe)
        # # Gravestone Doji: values [0, 100]
        # dataframe["CDLGRAVESTONEDOJI"] = ta.CDLGRAVESTONEDOJI(dataframe)
        # # Dark Cloud Cover: values [0, 100]
        # dataframe["CDLDARKCLOUDCOVER"] = ta.CDLDARKCLOUDCOVER(dataframe)
        # # Evening Doji Star: values [0, 100]
        # dataframe["CDLEVENINGDOJISTAR"] = ta.CDLEVENINGDOJISTAR(dataframe)
        # # Evening Star: values [0, 100]
        # dataframe["CDLEVENINGSTAR"] = ta.CDLEVENINGSTAR(dataframe)

        # Pattern Recognition - Bullish/Bearish candlestick patterns
        # ------------------------------------
        # # Three Line Strike: values [0, -100, 100]
        # dataframe["CDL3LINESTRIKE"] = ta.CDL3LINESTRIKE(dataframe)
        # # Spinning Top: values [0, -100, 100]
        # dataframe["CDLSPINNINGTOP"] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100]
        # # Engulfing: values [0, -100, 100]
        # dataframe["CDLENGULFING"] = ta.CDLENGULFING(dataframe) # values [0, -100, 100]
        # # Harami: values [0, -100, 100]
        # dataframe["CDLHARAMI"] = ta.CDLHARAMI(dataframe) # values [0, -100, 100]
        # # Three Outside Up/Down: values [0, -100, 100]
        # dataframe["CDL3OUTSIDE"] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100]
        # # Three Inside Up/Down: values [0, -100, 100]
        # dataframe["CDL3INSIDE"] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100]

        # # Chart type
        # # ------------------------------------
        # # Heikin Ashi Strategy
        # heikinashi = qtpylib.heikinashi(dataframe)
        # dataframe["ha_open"] = heikinashi["open"]
        # dataframe["ha_close"] = heikinashi["close"]
        # dataframe["ha_high"] = heikinashi["high"]
        # dataframe["ha_low"] = heikinashi["low"]

        # Retrieve best bid and best ask from the orderbook
        # ------------------------------------
        """
        # first check if dataprovider is available
        if self.dp:
            if self.dp.runmode.value in ("live", "dry_run"):
                ob = self.dp.orderbook(metadata["pair"], 1)
                dataframe["best_bid"] = ob["bids"][0][0]
                dataframe["best_ask"] = ob["asks"][0][0]
        """

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the entry signal for the given dataframe
        :param dataframe: DataFrame
        :param metadata: Additional inforGithub_touhoufan2024_user_data__ma__20250617_121401tion, like the currently traded pair
        :return: DataFrame with entry columns populated
        """
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["rsi"], self.buy_rsi.value)) &  # Signal: RSI crosses above buy_rsi
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] <= dataframe["bb_middleband"]) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 below BB middle
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] > dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"].shift(1)) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 is raising
                (dataframe["volume"] > 0)  # Make sure Volume is not 0
            ),
            "enter_long"] = 1
        # Uncomment to use shorts (Only used in futures/Github_touhoufan2024_user_data__ma__20250617_121401rgin mode. Check the documentation for more info)
        """
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi.value)) &  # Signal: RSI crosses above sell_rsi
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] > dataframe["bb_middleband"]) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 above BB middle
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] < dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"].shift(1)) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 is falling
                (dataframe['volume'] > 0)  # Make sure Volume is not 0
            ),
            'enter_short'] = 1
        """

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the exit signal for the given dataframe
        :param dataframe: DataFrame
        :param metadata: Additional inforGithub_touhoufan2024_user_data__ma__20250617_121401tion, like the currently traded pair
        :return: DataFrame with exit columns populated
        """
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi.value)) &  # Signal: RSI crosses above sell_rsi
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] > dataframe["bb_middleband"]) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 above BB middle
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] < dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"].shift(1)) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 is falling
                (dataframe["volume"] > 0)  # Make sure Volume is not 0
            ),
            "exit_long"] = 1
        # Uncomment to use shorts (Only used in futures/Github_touhoufan2024_user_data__ma__20250617_121401rgin mode. Check the documentation for more info)
        """
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["rsi"], self.buy_rsi.value)) &  # Signal: RSI crosses above buy_rsi
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] <= dataframe["bb_middleband"]) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 below BB middle
                (dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"] > dataframe["teGithub_touhoufan2024_user_data__ma__20250617_121401"].shift(1)) &  # Guard: teGithub_touhoufan2024_user_data__ma__20250617_121401 is raising
                (dataframe['volume'] > 0)  # Make sure Volume is not 0
            ),
            'exit_short'] = 1
        """
        return dataframe