# source: https://raw.githubusercontent.com/aragier/tradingStrategies/ba3f2fd3be7a23d51a2f518cb043f0db05091e41/user_data/strategies/BtcEma9_21Scalp.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,
    BooleanParameter,
    CategoricalParameter,
    DecimalParameter,
    IntParameter,
    RealParameter,
    timeframe_to_minutes,
    timeframe_to_next_date,
    timeframe_to_prev_date,
    merge_informative_pair,
    stoploss_from_absolute,
    stoploss_from_open,
)

# --------------------------------
import talib.abstract as ta
from technical import qtpylib


class Github_aragier_tradingStrategies__BtcEma9_21Scalp__20260327_161149(IStrategy):
    """
    Classic 9/21 EMA Crossover Scalping Strategy for BTC Futures.

    Entry: EMA9 crosses EMA21, confirmed by RSI momentum and ADX trend strength.
    Exit: Opposite EMA crossover, trailing stop, or ROI target.

    Designed for 5m timeframe, futures (long + short).
    """

    INTERFACE_VERSION = 3

    can_short: bool = True

    # --- Minimal ROI ---
    # Scalping: quick exits at modest profit targets
    minimal_roi = {
        "30": 0.01,   # 1% after 30 min
        "15": 0.02,   # 2% after 15 min
        "0": 0.03,    # 3% immediately
    }

    # --- Stoploss ---
    stoploss = -0.02  # -2%

    # --- Trailing Stop ---
    trailing_stop = True
    trailing_stop_positive = 0.005      # Trail at 0.5% once offset is reached
    trailing_stop_positive_offset = 0.01  # Activate after 1% profit
    trailing_only_offset_is_reached = True

    # --- Timeframe ---
    timeframe = "5m"

    # --- General settings ---
    process_only_new_candles = True
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # --- Hyperoptable Parameters ---
    # EMA periods
    ema_fast_period = IntParameter(5, 15, default=9, space="buy", optimize=True, load=True)
    ema_slow_period = IntParameter(15, 30, default=21, space="buy", optimize=True, load=True)

    # RSI thresholds
    rsi_long_min = IntParameter(40, 60, default=50, space="buy", optimize=True, load=True)
    rsi_short_max = IntParameter(40, 60, default=50, space="sell", optimize=True, load=True)

    # ADX threshold
    adx_threshold = IntParameter(15, 35, default=25, space="buy", optimize=True, load=True)

    # Startup candles: need enough for the longest indicator (ADX uses 14 period internally)
    startup_candle_count: int = 30

    # --- Order types ---
    order_types = {
        "entry": "limit",
        "exit": "limit",
        "stoploss": "market",
        "stoploss_on_exchange": False,
    }

    order_time_in_force = {"entry": "GTC", "exit": "GTC"}

    # --- Plot config for FreqUI ---
    plot_config = {
        "main_plot": {
            "ema_fast": {"color": "blue"},
            "ema_slow": {"color": "orange"},
        },
        "subplots": {
            "RSI": {
                "rsi": {"color": "red"},
            },
            "ADX": {
                "adx": {"color": "purple"},
            },
        },
    }

    def informative_pairs(self):
        return []

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # EMA - Fast and Slow
        dataframe["ema_fast"] = ta.EMA(dataframe, timeperiod=self.ema_fast_period.value)
        dataframe["ema_slow"] = ta.EMA(dataframe, timeperiod=self.ema_slow_period.value)

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

        # ADX - trend strength
        dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # --- Long Entry ---
        # EMA9 crosses above EMA21 + RSI confirms upward momentum + ADX shows trend
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["ema_fast"], dataframe["ema_slow"]))
                & (dataframe["rsi"] > self.rsi_long_min.value)
                & (dataframe["adx"] > self.adx_threshold.value)
                & (dataframe["volume"] > 0)
            ),
            "enter_long",
        ] = 1

        # --- Short Entry ---
        # EMA9 crosses below EMA21 + RSI confirms downward momentum + ADX shows trend
        dataframe.loc[
            (
                (qtpylib.crossed_below(dataframe["ema_fast"], dataframe["ema_slow"]))
                & (dataframe["rsi"] < self.rsi_short_max.value)
                & (dataframe["adx"] > self.adx_threshold.value)
                & (dataframe["volume"] > 0)
            ),
            "enter_short",
        ] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # --- Exit Long ---
        # Opposite crossover: EMA9 crosses below EMA21
        dataframe.loc[
            (
                (qtpylib.crossed_below(dataframe["ema_fast"], dataframe["ema_slow"]))
                & (dataframe["volume"] > 0)
            ),
            "exit_long",
        ] = 1

        # --- Exit Short ---
        # Opposite crossover: EMA9 crosses above EMA21
        dataframe.loc[
            (
                (qtpylib.crossed_above(dataframe["ema_fast"], dataframe["ema_slow"]))
                & (dataframe["volume"] > 0)
            ),
            "exit_short",
        ] = 1

        return dataframe
