# source: https://raw.githubusercontent.com/AHA-HH/freqtrade_sample_strategies/c1f35e3ac86b9707c01e815bc241b12221569a16/user_data/strategies/single_asset_strategy.py
from freqtrade.strategy.interface import IStrategy
from pandas import DataFrame

class Github_AHA_HH_freqtrade_sample_strategies__single_asset_strategy__20250601_195240(IStrategy):
    timeframe = '1h'
    startup_candle_count = 30
    stoploss = -0.99
    trailing_stop = True
    use_custom_stoploss = True
    use_exit_signal = False
    use_custom_exit = False
    minimal_roi = {"0": 0.1}
    process_only_new_candles = True

    def populate_indicators(self, df: DataFrame, metadata: dict) -> DataFrame:
        df['20_high'] = df['high'].rolling(20).max()
        df['20_low'] = df['low'].rolling(20).min()
        df['3_low'] = df['low'].rolling(3).min()
        return df

    def populate_entry_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
        df.loc[
            (df['close'] > df['20_high'].shift(1)),
            'enter_long'
        ] = 1

        df.loc[
            (df['close'] < df['20_low'].shift(1)),
            'enter_short'
        ] = 1

        return df

    def custom_stoploss(self, pair, trade, current_time, current_rate, current_profit, **kwargs):
        df = self.dp.get_analyzed_dataframe(pair, self.timeframe)
        if df is None or len(df) < 3:
            return 1
        try:
            idx = df.index.get_loc(trade.open_date_utc, method='nearest')
            # trailing_low = df['3_low'].iloc[idx]
            trailing_low = df['3_low'].iloc[-1]
            if current_rate < trailing_low:
                return 0.01
        except Exception:
            pass
        return 1

    def confirm_trade_entry(self, *args, **kwargs) -> bool:
        return len(self.wallets.get_all_open_trades()) == 0
    
    def populate_exit_trend(self, df: DataFrame, metadata: dict) -> DataFrame:
        df['exit_long'] = 0
        df['exit_short'] = 0
        return df