# source: https://raw.githubusercontent.com/IdifixNL/freqtrade-live-trader/fa25de910a2b854c0fa07332bed21c7a22668574/user_data/strategies/ultra_creative_strategy_final.py
# Required imports for FreqTrade strategy
from freqtrade.strategy import IStrategy, IntParameter
import pandas as pd
import pandas_ta as ta
from pandas import DataFrame

class Github_IdifixNL_freqtrade_live_trader__ultra_creative_strategy_final__20251005_165005(IStrategy):
    INTERFACE_VERSION = 3
    timeframe = '3m'
    
    minimal_roi = {"0": 0.08}
    stoploss = -0.22
    
    trailing_stop = True
    trailing_stop_positive = 0.02
    trailing_stop_positive_offset = 0.03
    trailing_only_offset_is_reached = True
    
    # Never sell at a loss - ignore exit signals when in loss
    use_custom_stoploss = True
    
    process_only_new_candles = True
    startup_candle_count: int = 30
    
    def custom_stoploss(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
                        current_profit: float, **kwargs) -> float:
        """
        Custom stoploss logic - never sell at a loss.
        Returns a very low stoploss (-0.99) when in profit to allow normal exit,
        but returns 1 (no stoploss) when in loss to prevent selling at a loss.
        """
        if current_profit > 0:
            # In profit - allow normal stoploss behavior
            return -0.22
        else:
            # In loss - disable stoploss (return 1 means no stoploss trigger)
            return 1
    
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Dynamic indicators generated with complexity: simple
        # MACD returns multiple columns
        macd_result = ta.macd(dataframe["close"])
        dataframe["indicator_0_macd"] = macd_result["MACD_12_26_9"]
        dataframe["indicator_0_signal"] = macd_result["MACDs_12_26_9"]
        dataframe["indicator_0_hist"] = macd_result["MACDh_12_26_9"]
        dataframe["indicator_1"] = dataframe["volume"].ewm(span=60).mean()
        
        return dataframe
    
    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                ((dataframe["indicator_0_macd"].diff() > 0) & (dataframe["close"].diff() < 0).fillna(False)) & ((dataframe["indicator_0_signal"] > 0).fillna(False))
            ),
            'enter_long'] = 1
        return dataframe
    
    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                ((dataframe["indicator_0_hist"] > dataframe["indicator_1"]).fillna(False)) & ((dataframe["indicator_1"] > 0).fillna(False))
            ),
            'exit_long'] = 1
        return dataframe
    
    def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float,
                          rate: float, time_in_force: str, exit_reason: str,
                          current_time: 'datetime', **kwargs) -> bool:
        """
        Confirm trade exit - never allow selling at a loss.
        Only allow exits when the trade is profitable.
        """
        # Calculate current profit
        current_profit = trade.calc_profit_ratio(rate)
        
        # Only allow exit if in profit
        if current_profit > 0:
            return True
        else:
            # Prevent selling at a loss
            return False
