# source: https://raw.githubusercontent.com/secondlinger/WinnieBari/73bedc96c87439cd3ca5ae33aca9cb01ed125468/user_data/strategies/MartingaleStrategy.py
from freqtrade.strategy.interface import IStrategy
from pandas import DataFrame


class Github_secondlinger_WinnieBari__MartingaleStrategy__20250919_003943(IStrategy):
    # --- 1. パラメータ定義 ---
    minimal_roi = {"0": 0.02}        # 利確：2%
    stoploss = -0.02                # 損切：2%
    initial_stake_amount = 10       # 基本ロット：10 USDT
    max_multiplier = 8              # ロットの最大倍数
    custom_info = {}                # 前回の結果を記憶する場所
    timeframe = "5m"                # 5分足

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema_fast'] = dataframe['close'].ewm(span=12).mean()
        dataframe['ema_slow'] = dataframe['close'].ewm(span=26).mean()
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (dataframe['ema_fast'] > dataframe['ema_slow']),
            'enter_long'
        ] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        return dataframe

    def custom_entry_amount(self, pair: str, current_rate: float, **kwargs) -> float:
        prev = self.custom_info.get('last_result', 'win')
        mult = self.custom_info.get('multiplier', 1)

        if prev == 'loss' and mult < self.max_multiplier:
            mult *= 2
        else:
            mult = 1

        self.custom_info['multiplier'] = mult
        return self.initial_stake_amount * mult

    def custom_exit(self, pair: str, trade, current_time, current_rate, **kwargs):
        # calc_profit_ratio に current_rate を渡すよう修正
        profit_ratio = trade.calc_profit_ratio(current_rate)
        if profit_ratio >= 0:
            self.custom_info['last_result'] = 'win'
        else:
            self.custom_info['last_result'] = 'loss'
        return None
