Skip to content

模擬交易賣出平倉失敗 #224

@ericwllo1991-coder

Description

@ericwllo1991-coder

请输入香港股票代码(例如00700):00020
设置股票 HK.00020,每手股数:1000,成功订阅行情
从2025-01-01回测至2025-10-15
2025-01-02 00:00:00 买入5000股,价格1.41,持仓5000,资金92950.00
2025-01-03 00:00:00 买入5000股,价格1.33,持仓10000,资金86300.00
2025-01-06 00:00:00 买入5000股,价格1.33,持仓15000,资金79650.00
2025-01-08 00:00:00 买入5000股,价格1.31,持仓20000,资金73100.00
2025-01-09 00:00:00 买入5000股,价格1.31,持仓25000,资金66550.00
2025-01-10 00:00:00 买入5000股,价格1.28,持仓30000,资金60150.00
2025-01-13 00:00:00 买入5000股,价格1.3,持仓35000,资金53650.00
2025-01-16 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-17 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-20 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-21 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-22 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-23 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-24 00:00:00 卖出失败: 无法同时买多和卖空
2025-01-27 00:00:00 卖出失败: 无法同时买多和卖空

def buy(self, date_str, price):
    max_qty = int(self.cash / price // self.lot_size) * self.lot_size
    if max_qty < self.lot_size:
        print(f"{date_str} 资金不足,无法买入")
        return False
    qty = min(self.lot_size * 5, max_qty)
    ret, data = self.trade_ctx.place_order(price=price, qty=qty, code=self.symbol,
                                           trd_side='BUY', trd_env=TrdEnv.SIMULATE)
    if ret != 0:
        print(f"{date_str} 买入失败: {data}")
        return False
    self.cash -= price * qty
    prev_pos = self.position
    self.position += qty
    self.avg_price = (self.avg_price * prev_pos + price * qty) / self.position if self.position > 0 else 0
    print(f"{date_str} 买入{qty}股,价格{price},持仓{self.position},资金{self.cash:.2f}")
    self.record(date_str, "买入", price, qty)
    time.sleep(2)
    return True

def sell(self, date_str, price):
    if self.position < self.lot_size:
        print(f"{date_str} 持仓不足,无法卖出")
        return False
    qty = min(self.lot_size * 5, (self.position // self.lot_size) * self.lot_size)
    ret, data = self.trade_ctx.place_order(price=price, qty=qty, code=self.symbol,
                                           trd_side='SELL', trd_env=TrdEnv.SIMULATE)
    if ret != 0:
        print(f"{date_str} 卖出失败: {data}")
        return False
    self.position -= qty
    self.cash += price * qty
    print(f"{date_str} 卖出{qty}股,价格{price},持仓{self.position},资金{self.cash:.2f}")
    self.record(date_str, "卖出", price, qty)
    time.sleep(2)
    return True

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions