KB / ARTICLE

策略案例:固定比例止盈止损

案例合集修订 R1发布于 2026-11-05

本案例在空仓且当根 K 线收阳时买入,之后按持仓成本计算浮动盈亏,达到设定的止盈或止损百分比就清仓。

完整代码

from qmfquant import Bar, FloatParam, IntParam, OrderSide, Strategy


class StopTakeStrategy(Strategy):
    quantity = IntParam(100, ge=100, title="买入数量")
    take_pct = FloatParam(8.0, ge=0.1, le=100, title="止盈百分比")
    stop_pct = FloatParam(4.0, ge=0.1, le=50, title="止损百分比")

    def on_start(self) -> None:
        self.entry_price = {}

    def on_bar(self, bar: Bar) -> None:
        symbol = bar.symbol
        if self.get_open_orders(symbol):
            return

        pos = self.get_position(symbol)
        available = self.get_available_position(symbol)
        entry = self.entry_price.get(symbol) or self.position.entry_price

        if pos == 0:
            if bar.close > bar.open:
                self.buy(symbol, quantity=int(self.params.quantity), tag="entry")
            return

        if entry and entry > 0 and available > 0:
            pnl_pct = (bar.close - entry) / entry * 100
            if pnl_pct >= float(self.params.take_pct) or pnl_pct <= -float(self.params.stop_pct):
                self.close_position(symbol)
                self.log(f"{symbol} 触发止盈止损,浮动={pnl_pct:.2f}%")

    def on_trade(self, trade) -> None:
        if trade.side == OrderSide.Buy:
            self.entry_price[trade.symbol] = trade.price

要点说明

  • entry_price 字典在 on_trade 里由实际成交价写入,比用当根 K 线收盘价估算成本更贴近真实成交。
  • 卖出前先判断 available > 0,否则 T+1 当天买入的仓位卖不掉,只会产生拒单。
  • self.get_open_orders(symbol) 的非空判断保证同一标的不会在挂单未结束时重复下单。

成本价也可直接读 self.position.entry_price / self.position.avg_price。不要用 get_holding_bars() 做实盘持仓天数判断。


相关阅读

已复制到剪贴板
案例合集修订 R1

返回案例合集板块

评论