实际使用过程中,上海交易所品种,有老仓的情况下,开新仓,再平老仓,剩下的当日持仓均价变成了0,如图

description

论坛里翻到以前的贴子

enter link description here

对应代码如下:

计算之前已有仓位的持仓总成本

     cost: float = position.price * position.volume * size

     position.opencost = data["OpenCost"]
     position.openprice = 0
     # 累加更新持仓数量和盈亏
     position.volume += data["Position"]
     position.pnl += data["PositionProfit"]

     # 计算更新后的持仓总成本和均价
     if position.volume and size:
         cost += data["PositionCost"]
         position.price = cost / (position.volume * size)
         # 计算开仓均价
         position.openprice = position.opencost / (position.volume * size)

         # 更新仓位冻结数量
     if position.direction == Direction.LONG:
         position.frozen += data["ShortFrozen"]
     else:
         position.frozen += data["LongFrozen"]

     # 计算浮盈
     position.settlementPrice = data["SettlementPrice"]
     floatprofit = position.settlementPrice * position.volume * size - position.opencost
     if position.direction == Direction.LONG:
         position.floatProfit = floatprofit
     else:
         position.floatProfit = -floatprofit