# source: https://raw.githubusercontent.com/Kazu-takahashi1213/freqtrade/000c5a121c3651afc50703fc23f767967b8415b3/strategies/ShortTermStrategy.py
from freqtrade.strategy import IStrategy
from pandas import DataFrame
import sys, os

# src ディレクトリを追加
sys.path.append(os.path.join(os.path.dirname(__file__), "../src"))

from data_pipeline.feature_store import compute_features
from model.trainer import load_model, predict_direction

class Github_Kazu_takahashi1213_freqtrade__ShortTermStrategy__20250617_234608(IStrategy):
    """
    数秒～数分単位の短期トレード戦略
    モデル出力で buy/sell/hold を判断
    """
    # Freqtrade の必須設定
    timeframe = '1m'
    minimal_roi = {"0": 0.01}
    stoploss = -0.02
    trailing_stop = False

    # 学習済みモデルの読み込み
    def __init__(self, config: dict) -> None:
        super().__init__(config)
        model_path = os.path.join(self.config['user_data_dir'], 'model', 'lgbm_model.txt')
        self.model = load_model(model_path)

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # テクニカル指標を付与
        return compute_features(dataframe)

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # 最新の特徴量行だけを抽出
        feature_row = dataframe.iloc[[-1]].copy()
        signal = predict_direction(self.model, feature_row)
        dataframe.loc[dataframe.index[-1], 'enter_long'] = 1 if signal == 1 else 0
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        feature_row = dataframe.iloc[[-1]].copy()
        signal = predict_direction(self.model, feature_row)
        dataframe.loc[dataframe.index[-1], 'exit_long'] = 1 if signal == -1 else 0
        return dataframe

