# source: https://raw.githubusercontent.com/remiotore/freqtrade/44beaeb6a420cd8e9f2e4ea93e11d6cfa192ee03/strategies/roger27.py
import numpy as np
import pandas as pd
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib

from freqtrade.strategy import IStrategy
from freqtrade.persistence import Trade



class Github_remiotore_freqtrade__roger27__20260111_210550(IStrategy):

    INTERFACE_VERSION = 3

    can_short = False

    minimal_roi = {







    "0":   0.50
    }

    stoploss = -0.25

    use_custom_stoploss = True

    use_custom_take_profit = True

    trailing_stop = True
    trailing_stop_positive = 0.001
    trailing_stop_positive_offset = 0.05
    trailing_only_offset_is_reached = False

    timeframe = '15m'

    process_only_new_candles = True
    
    max_profits = {}
    
    exit_profit_only = False
    
    def on_trade_update(self, trade: Trade, **kwargs):

        if trade.pair not in self.max_profits:
            self.max_profits[trade.pair] = 0

        if trade.current_profit_ratio > 0:
            self.max_profits[trade.pair] = max(self.max_profits[trade.pair], trade.current_profit_ratio)
        else:
            self.max_profits[trade.pair] = 0

    def on_trade_close(self, trade: Trade, **kwargs):

        self.max_profits.pop(trade.pair, None)
    
    def populate_indicators(self, dataframe: pd.DataFrame, metadata: dict) -> pd.DataFrame:
        """ Populates new indicators for given strategy

        Args:
            dataframe (pd.DataFrame): dataframe for the given pair
            metadata (dict): metadata for the given pair

        Returns:
            pd.DataFrame: dataframe with the defined indicators
        """

        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)
        dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50)
        dataframe['sma20'] = ta.SMA(dataframe, timeperiod=20)

        dataframe['ema200'] = ta.EMA(dataframe, timeperiod=200)
        dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
        dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20)

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

        dataframe['cdl3inside'] = ta.CDL3INSIDE(dataframe)
        dataframe['cdl3outside'] = ta.CDL3OUTSIDE(dataframe)
        dataframe['cdl3starsinsouth'] = ta.CDL3STARSINSOUTH(dataframe)
        dataframe['cdlhammer'] = ta.CDLHAMMER(dataframe)
        dataframe['cdlinvertedhammer'] = ta.CDLINVERTEDHAMMER(dataframe)

        dataframe['cdl3blackcrows'] = ta.CDL3BLACKCROWS(dataframe)
        dataframe['cdl3whitesoldiers'] = ta.CDL3WHITESOLDIERS(dataframe)
        dataframe['cdl3linestrike'] = ta.CDL3LINESTRIKE(dataframe)
        dataframe['cdlgravestonedoji'] = ta.CDLGRAVESTONEDOJI(dataframe)
        dataframe['cdlshootingstar'] = ta.CDLSHOOTINGSTAR(dataframe)
        dataframe['cdl3inside'] = ta.CDL3INSIDE(dataframe)
        dataframe['cdl3outside'] = ta.CDL3OUTSIDE(dataframe)
        dataframe['cdl3starsinsouth'] = ta.CDL3STARSINSOUTH(dataframe)
        dataframe['cdlhammer'] = ta.CDLHAMMER(dataframe)
        dataframe['cdlinvertedhammer'] = ta.CDLINVERTEDHAMMER(dataframe)

        dataframe['cdlengulfing'] = ta.CDLENGULFING(dataframe)

        dataframe['ATR'] = ta.ATR(dataframe, timeperiod=4)

        dataframe['ATR_stoploss'] = dataframe['ATR'] * 6.5

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']
        
        return dataframe
    
    def populate_entry_trend(self, dataframe: pd.DataFrame, metadata: dict) -> pd.DataFrame:
        """ Populate rules for the "buy" signal

        Args:
            dataframe (pd.DataFrame): dataframe for the given pair
            metadata (dict): metadata for the given pair

        Returns:
            pd.DataFrame: dataframe with the defined indicators
        """

        bullish_conditions = (

            (dataframe['ema50'] > dataframe['ema200']) & # Long term trend indicator
            (dataframe['bb_percent'] < 0.15) & # Price is near the lower Bollinger Band
            (dataframe['bb_width'] < 0.05) # Bollinger Bands are narrow
        )

        candlestick_patterns = (
            (dataframe['cdl3inside'] == 100) |  # 3 Inside Up
            (dataframe['cdl3outside'] == 100) |  # 3 Outside Up
            (dataframe['cdl3starsinsouth'] == 100) |  # 3 Stars In The South
            (dataframe['cdlhammer'] == 100) |  # Hammer
            (dataframe['cdlinvertedhammer'] == 100) | # Inverted Hammer
            (dataframe['cdl3whitesoldiers'] == 100) | # 3 White Soldiers
            (dataframe['cdl3linestrike'] == 100) | # 3 Line Strike
            (dataframe['cdlgravestonedoji'] == 100) |  # Gravestone Doji
            (dataframe['cdlshootingstar'] == 100)  # Shooting Star
        )

        macd_condition = (
            (dataframe['macd'] > dataframe['macdsignal'])  # MACD line above signal line
        )

        dataframe.loc[bullish_conditions | (candlestick_patterns & macd_condition), 'buy'] = 1
          
        return dataframe

    def populate_exit_trend(self, dataframe: pd.DataFrame, metadata: dict) -> pd.DataFrame:
        """ Populate rules for the "sell" signal
        
        Args:
            dataframe (pd.DataFrame): dataframe for the given pair
            metadata (dict): metadata for the given pair
            
        Returns:
            pd.DataFrame: dataframe with the defined indicators
        """

        bearish_conditions = (
            (dataframe['ema20'] < dataframe['ema50']) &
            (dataframe['bb_percent'] > 0.85) &
            (dataframe['bb_width'] > 0.05)
            
        )

        candlestick_patterns = (
            (dataframe['cdl3blackcrows'] == -100) |  # 3 Black Crows
            (dataframe['cdl3whitesoldiers'] == 100) |  # 3 White Soldiers
            (dataframe['cdl3linestrike'] == -100) |  # 3 Line Strike
            (dataframe['cdlgravestonedoji'] == -100) |  # Gravestone Doji
            (dataframe['cdlshootingstar'] == -100) | # Shooting Star
            (dataframe['cdl3inside'] == -100) | # 3 Inside Down
            (dataframe['cdl3outside'] == -100) | # 3 Outside Down
            (dataframe['cdl3starsinsouth'] == -100) | # 3 Stars In The South
            (dataframe['cdlhammer'] == -100) | # Hammer
            (dataframe['cdlinvertedhammer'] == -100)  # Inverted Hammer
            
        )

        macd_condition = (
        (dataframe['macd'] < dataframe['macdsignal'])  # MACD line below signal line
    )

        dataframe.loc[bearish_conditions & candlestick_patterns & macd_condition, 'sell'] = 1
        
        return dataframe
    
    
    def calc_stop_loss_pct(self, current_rate: float, atr_multiplier: float) -> float:
        return -atr_multiplier * current_rate

    def calculate_dynamic_take_profit(self, dataframe: pd.DataFrame, trade: Trade) -> float:

        entry_atr = dataframe.loc[dataframe['date'] == trade.open_date_utc, 'ATR'].iloc[0]

        atr_multiplier = 6.5

        take_profit_level = trade.open_rate + (entry_atr * atr_multiplier)
        
        return take_profit_level

    def custom_take_profit(self, pair: str, trade: 'Trade', current_profit: float, current_rate: float, **kwargs) -> float:

        dynamic_take_profit = self.calculate_dynamic_take_profit(self.dataframe, trade)

        adjusted_take_profit = max(dynamic_take_profit, self.minimal_roi[0])
        
        return adjusted_take_profit
    
    def custom_stoploss(self, pair: str, trade: 'Trade', current_profit: float, current_rate: float, **kwargs) -> float:

         max_profit = self.max_profits.get(pair, current_profit)

         peak_profit_drawdown = max_profit - current_profit

         atr_stoploss = self.calc_stop_loss_pct(current_rate, 6.5)

         if peak_profit_drawdown > 0.02:  # If drawdown from peak is greater than 5%
             atr_stoploss *= 0.7  # Tighten the stop loss by 30%
         elif peak_profit_drawdown > 0.1:  # If drawdown from peak is greater than 10%
             atr_stoploss *= 0.5  # Tighten the stop loss by 50%

         if current_profit > 0.10:  # If current profit is above 5%
             atr_stoploss *= 0.7  # Tighten the stop loss by 30%
         elif current_profit > 0.05:  # If current profit is above 10%
             atr_stoploss *= 0.5  # Tighten the stop loss by 50%

         adjusted_stoploss = max(atr_stoploss, self.stoploss)

         return adjusted_stoploss