# source: https://raw.githubusercontent.com/wiktorj137/btc-strategy-lab/b68a5518b4a3eba2fde1733160d7d7de356023b5/user_data/strategies/EmaEnsembleVariants.py
# directory_url: https://github.com/wiktorj137/btc-strategy-lab/blob/main/user_data/strategies/
# User: wiktorj137
# Repository: btc-strategy-lab
# --------------------"""Warianty progu dla EmaEnsemble - tylko do badania, nie do produkcji.

Chodzi o histereze: wejscie i wyjscie na tym samym progu (0.5) daje pile,
bo cena bez konca oscyluje wokol srodkowych EMA. Ponizsze warianty roznia sie
STRUKTURA reguly, nie wartoscia parametru: "powyzej wszystkich EMA" albo
"ponizej wszystkich" to punkty wyznaczone przez sam zbior, nie przez dostrajanie.
"""
from __future__ import annotations

import numpy as np
import talib.abstract as ta
from pandas import DataFrame

from freqtrade.strategy import IStrategy

EMA_SET = (400, 600, 800, 1000, 1200)


class Github_wiktorj137_btc_strategy_lab__EmaEnsembleVariants__20260822_031820(IStrategy):
    INTERFACE_VERSION = 3
    timeframe = "1h"
    can_short = False
    process_only_new_candles = True
    startup_candle_count = 1300
    minimal_roi = {"0": 10}
    stoploss = -0.15
    trailing_stop = True

    enter_at = 0.5   # wejscie gdy udzial przekroczy ten poziom
    exit_at = 0.5    # wyjscie gdy spadnie ponizej

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        above = np.zeros(len(dataframe))
        for p in EMA_SET:
            above += (dataframe["close"] > ta.EMA(dataframe, timeperiod=p)).astype(float).to_numpy()
        dataframe["ema_score"] = above / len(EMA_SET)
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        s = dataframe["ema_score"]
        dataframe.loc[(s >= self.enter_at) & (s.shift(1) < self.enter_at)
                      & (dataframe["volume"] > 0), "enter_long"] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        s = dataframe["ema_score"]
        dataframe.loc[(s <= self.exit_at) & (s.shift(1) > self.exit_at), "exit_long"] = 1
        return dataframe


class EnsAllAll(Github_wiktorj137_btc_strategy_lab__EmaEnsembleVariants__20260822_031820):
    """Wejscie powyzej WSZYSTKICH EMA, wyjscie ponizej wszystkich."""
    enter_at, exit_at = 1.0, 0.0


class EnsAllHalf(Github_wiktorj137_btc_strategy_lab__EmaEnsembleVariants__20260822_031820):
    """Wejscie powyzej wszystkich, wyjscie gdy wiekszosc juz nie trzyma."""
    enter_at, exit_at = 1.0, 0.4


class EnsHalfAll(Github_wiktorj137_btc_strategy_lab__EmaEnsembleVariants__20260822_031820):
    """Wejscie gdy wiekszosc przebita, wyjscie dopiero ponizej wszystkich."""
    enter_at, exit_at = 0.6, 0.0


class EnsHalfZero(Github_wiktorj137_btc_strategy_lab__EmaEnsembleVariants__20260822_031820):
    """Wejscie na wiekszosci, wyjscie gdy zostanie tylko najdluzsza EMA."""
    enter_at, exit_at = 0.6, 0.2
