# source: https://raw.githubusercontent.com/RudoRonuma/freqtrade/577d2b949274ed881d00154139a3ee0f91eb5c6f/user_data/strategies/master_strategy.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 Optional, Union

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,
)

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


class Github_RudoRonuma_freqtrade__master_strategy__20250511_220746(IStrategy):
    """
    The master strategy.
    When testing it with hyperopt, make sure to set remove_unrelated_hyperopt_params to
    true in config file.
    """
    # region General Strategy Params

    # 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

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

    minimal_roi = {
        "0": 0.99  # Let TSL and exit signals do most of the work
        # "2880": 0.05,
        # "1440": 0.03
    }

    # Optimal 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 = True
    trailing_stop_positive = 0.05
    trailing_stop_positive_offset = 0.15

    # Optimal timeframe for the strategy.
    timeframe = "4h"

    # 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 = 200

    # endregion

    # region BTC params
    # buy params for btc
    buy_adx_threshold_btc = IntParameter(low=1, high=50, default=20, space="buy", optimize=True)
    buy_fishRsiNorma_btc = IntParameter(low=1, high=50, default=9, space="buy", optimize=True)
    buy_rsi_floor_btc = IntParameter(low=10, high=20, default=12, space="buy", optimize=True)
    buy_stoch_fastd_level_btc = IntParameter(
        low=10, high=35, default=34, space="buy", optimize=True
    )
    buy_volumeAVG_btc = IntParameter(low=1, high=300, default=136, space="buy", optimize=True)
    buy_volume_multiplier_btc = IntParameter(low=3, high=6, default=4, space="buy", optimize=True)

    # sell params for btc
    sell_fisherRsiNorma_exit_btc = IntParameter(
        low=1, high=100, default=70, space="sell", optimize=True
    )
    sell_minusDI_exit_btc = IntParameter(low=1, high=100, default=4, space="sell", optimize=True)
    sell_rsi_exit_btc = IntParameter(low=60, high=90, default=74, space="sell", optimize=True)
    sell_trigger_btc = CategoricalParameter(
        ["rsi-macd-minusdi", "sar-fisherRsi"],
        default="rsi-macd-minusdi",
        space="sell",
        optimize=True,
    )

    # endregion

    # region HyperOpt params

    # Buy hyperspace params:
    buy_params = {
        # btc params
        "buy_adx_threshold_btc": 10,
        "buy_fishRsiNorma_btc": 27,
        "buy_rsi_floor_btc": 15,
        "buy_stoch_fastd_level_btc": 27,
        "buy_volumeAVG_btc": 111,
        "buy_volume_multiplier_btc": 3,
        # eth params
    }

    # Sell hyperspace params:
    sell_params = {
        # btc params
        "sell_fisherRsiNorma_exit_btc": 58,
        "sell_minusDI_exit_btc": 14,
        "sell_rsi_exit_btc": 70,
        "sell_trigger_btc": "rsi-macd-minusdi",
        # eth params
    }

    # endregion

    # region Order and Plot params

    # Optional order type mapping.
    order_types = {
        "entry": "limit",
        "exit": "limit",
        "stoploss": "market",
        "stoploss_on_exchange": False,
    }

    # Optional order time in force.
    order_time_in_force = {"entry": "GTC", "exit": "GTC"}

    plot_config = {
        "main_plot": {
            "tema": {},
            "sar": {"color": "white"},
        },
        "subplots": {
            "MACD": {
                "macd": {"color": "blue"},
                "macdsignal": {"color": "orange"},
            },
            "RSI": {
                "rsi": {"color": "red"},
            },
        },
    }

    # endregion

    # region Master-Strategy methods
    def informative_pairs(self):
        """
        Define additional, informative 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 information, please consult the documentation
        :return: List of tuples in the format (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

        Performance Note: For the best performance 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 information, like the currently traded pair
        :return: a Dataframe with all mandatory indicators for the strategies
        """
        target_pair = metadata["pair"]
        if target_pair == "BTC/USDT":
            dataframe = self.populate_indicators_btc(dataframe, metadata)
        elif target_pair == "ETH/USDT":
            dataframe = self.populate_indicators_eth(dataframe, metadata)
        else:
            print(f"WARNING: the pair {target_pair} is not supported yet")
            return dataframe

        # do things which are common between all pairs in here
        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 information, like the currently traded pair
        :return: DataFrame with entry columns populated
        """
        target_pair = metadata["pair"]
        if target_pair == "BTC/USDT":
            dataframe = self.populate_entry_trend_btc(dataframe, metadata)
        elif target_pair == "ETH/USDT":
            dataframe = self.populate_entry_trend_eth(dataframe, metadata)
        else:
            print(f"WARNING: the pair {target_pair} is not supported yet")
            return dataframe

        # do things which are common between all pairs in here
        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 information, like the currently traded pair
        :return: DataFrame with exit columns populated
        """
        target_pair = metadata["pair"]
        if target_pair == "BTC/USDT":
            dataframe = self.populate_exit_trend_btc(dataframe, metadata)
        elif target_pair == "ETH/USDT":
            dataframe = self.populate_exit_trend_eth(dataframe, metadata)
        else:
            print(f"WARNING: the pair {target_pair} is not supported yet")
            return dataframe

        # do things which are common between all pairs in here
        return dataframe

    # endregion

    # region BTC-stragey methods

    def populate_indicators_btc(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # ADX
        dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)

        # MACD
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]

        # Minus Directional Indicator / Movement
        dataframe["minus_di"] = ta.MINUS_DI(dataframe)

        # RSI
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
        dataframe["mfi"] = ta.MFI(dataframe)

        # Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (dataframe["rsi"] - 50)
        dataframe["fisher_rsi"] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)
        # Inverse Fisher transform on RSI normalized, value [0.0, 100.0] (https://goo.gl/2JGGoy)
        dataframe["fisher_rsi_norma"] = 50 * (dataframe["fisher_rsi"] + 1)

        # Stoch fast
        stoch_fast = ta.STOCHF(dataframe)
        dataframe["fastd"] = stoch_fast["fastd"]
        dataframe["fastk"] = stoch_fast["fastk"]

        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe["bb_lowerband"] = bollinger["lower"]

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

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

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

        # SMA - Simple Moving Average
        dataframe["sma"] = ta.SMA(dataframe, timeperiod=40)

        dataframe["ema21"] = ta.EMA(dataframe, timeperiod=21)
        dataframe["ema55"] = ta.EMA(dataframe, timeperiod=55)

        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"]

        # Keep your volume calculation as it was impactful
        dataframe["volume_mean_long"] = (
            dataframe["volume"].rolling(self.buy_volumeAVG_btc.value).mean()
        )

        return dataframe

    def populate_entry_trend_btc(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        current_dust_condition = dataframe["close"] > 0.00000200
        dataframe.loc[
            # Prod
            (
                current_dust_condition
                & (
                    dataframe["volume"]
                    > dataframe["volume"].rolling(self.buy_volumeAVG_btc.value).mean()
                    * self.buy_volume_multiplier_btc.value
                )
                & (dataframe["close"] < dataframe["sma"])
                & (qtpylib.crossed_above(dataframe["fastk"], dataframe["fastd"]))
                & (dataframe["fastd"] < self.buy_stoch_fastd_level_btc.value)
                & (dataframe["adx"] > self.buy_adx_threshold_btc.value)
                & (dataframe["rsi"] > self.buy_rsi_floor_btc.value)
                & (dataframe["fisher_rsi_norma"] < self.buy_fishRsiNorma_btc.value)
            ),
            "enter_long",
        ] = 1

        return dataframe

    def populate_exit_trend_btc(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        rsi_sell_condition = qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi_exit_btc.value)
        conditions = []
        if self.sell_trigger_btc.value == "rsi-macd-minusdi":
            conditions.append(rsi_sell_condition)
            conditions.append(dataframe["macd"] < 0)
            conditions.append(dataframe["minus_di"] > self.sell_minusDI_exit_btc.value)
        if self.sell_trigger_btc.value == "sar-fisherRsi":
            conditions.append(dataframe["sar"] > dataframe["close"])
            conditions.append(
                dataframe["fisher_rsi_norma"] > self.sell_fisherRsiNorma_exit_btc.value
            )

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), "exit_long"] = 1

        return dataframe

    # endregion

    # region BTC-stragey methods

    def populate_indicators_eth(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # ADX
        dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)

        # MACD
        macd = ta.MACD(dataframe)
        dataframe["macd"] = macd["macd"]
        dataframe["macdsignal"] = macd["macdsignal"]

        # Minus Directional Indicator / Movement
        dataframe["minus_di"] = ta.MINUS_DI(dataframe)

        # RSI
        dataframe["rsi"] = ta.RSI(dataframe, timeperiod=14)
        dataframe["mfi"] = ta.MFI(dataframe)

        # Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (dataframe["rsi"] - 50)
        dataframe["fisher_rsi"] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)
        # Inverse Fisher transform on RSI normalized, value [0.0, 100.0] (https://goo.gl/2JGGoy)
        dataframe["fisher_rsi_norma"] = 50 * (dataframe["fisher_rsi"] + 1)

        # Stoch fast
        stoch_fast = ta.STOCHF(dataframe)
        dataframe["fastd"] = stoch_fast["fastd"]
        dataframe["fastk"] = stoch_fast["fastk"]

        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe["bb_lowerband"] = bollinger["lower"]

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

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

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

        # SMA - Simple Moving Average
        dataframe["sma"] = ta.SMA(dataframe, timeperiod=40)

        dataframe["ema21"] = ta.EMA(dataframe, timeperiod=21)
        dataframe["ema55"] = ta.EMA(dataframe, timeperiod=55)

        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"]

        # Keep your volume calculation as it was impactful
        dataframe["volume_mean_long"] = (
            dataframe["volume"].rolling(self.buy_volumeAVG_btc.value).mean()
        )

        return dataframe

    def populate_entry_trend_eth(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        current_dust_condition = dataframe["close"] > 0.00000200
        dataframe.loc[
            # Prod
            (
                current_dust_condition
                & (
                    dataframe["volume"]
                    > dataframe["volume"].rolling(self.buy_volumeAVG_btc.value).mean()
                    * self.buy_volume_multiplier_btc.value
                )
                & (dataframe["close"] < dataframe["sma"])
                & (qtpylib.crossed_above(dataframe["fastk"], dataframe["fastd"]))
                & (dataframe["fastd"] < self.buy_stoch_fastd_level_btc.value)
                & (dataframe["adx"] > self.buy_adx_threshold_btc.value)
                & (dataframe["rsi"] > self.buy_rsi_floor_btc.value)
                & (dataframe["fisher_rsi_norma"] < self.buy_fishRsiNorma_btc.value)
            ),
            "enter_long",
        ] = 1

        return dataframe

    def populate_exit_trend_eth(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        rsi_sell_condition = qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi_exit_btc.value)
        conditions = []
        if self.sell_trigger_btc.value == "rsi-macd-minusdi":
            conditions.append(rsi_sell_condition)
            conditions.append(dataframe["macd"] < 0)
            conditions.append(dataframe["minus_di"] > self.sell_minusDI_exit_btc.value)
        if self.sell_trigger_btc.value == "sar-fisherRsi":
            conditions.append(dataframe["sar"] > dataframe["close"])
            conditions.append(
                dataframe["fisher_rsi_norma"] > self.sell_fisherRsiNorma_exit_btc.value
            )

        if conditions:
            dataframe.loc[reduce(lambda x, y: x & y, conditions), "exit_long"] = 1

        return dataframe

    # endregion
