from vnpy_ctastrategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)

class SimpleTestStrategy(CtaTemplate):
    """最简单的测试策略，用于排查回测API问题"""
    
    author = "姜维"
    
    # 策略参数
    fast_window = 5
    slow_window = 20
    
    # 策略变量
    fast_ma = 0
    slow_ma = 0
    
    parameters = ["fast_window", "slow_window"]
    variables = ["fast_ma", "slow_ma"]
    
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """初始化策略"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        
        # 创建K线合成器
        self.bg = BarGenerator(self.on_bar)
        # 创建数组管理器
        self.am = ArrayManager()
    
    def on_init(self):
        """策略初始化"""
        self.write_log("策略初始化")
        # 预加载10根K线
        self.load_bar(10)
    
    def on_start(self):
        """策略启动"""
        self.write_log("策略启动")
    
    def on_stop(self):
        """策略停止"""
        self.write_log("策略停止")
    
    def on_tick(self, tick: TickData):
        """Tick推送"""
        self.bg.update_tick(tick)
    
    def on_bar(self, bar: BarData):
        """K线推送"""
        # 更新数组
        self.am.update_bar(bar)
        if not self.am.inited:
            return
        
        # 计算指标
        self.fast_ma = self.am.sma(self.fast_window)
        self.slow_ma = self.am.sma(self.slow_window)
        
        # 简单交易逻辑
        if self.fast_ma > self.slow_ma and not self.pos:
            self.buy(bar.close_price, 1)
        elif self.fast_ma < self.slow_ma and self.pos > 0:
            self.sell(bar.close_price, 1)