def calculate_pnl(self, position: PositionData) -> None: """""" tick = self.ticks.get(position.vt_symbol, None) if tick: contract = self.main_engine.get_contract(position.vt_symbol) if position.direction == Direction.SHORT: multiplier = -position.volume * contract.size else: multiplier = position.volume * contract.size position.pnl = (tick.last_price - position.price) * multiplier position.pnl = round(position.pnl, 2)
def on_query_position(self, data, request): """""" if self.check_error(data, "查询持仓"): return # Clear all buf data for position in self.positions.values(): position.volume = 0 position.frozen = 0 position.price = 0 position.pnl = 0 for d in data["data"]: key = f"{d['contract_code']}_{d['direction']}" position = self.positions.get(key, None) if not position: position = PositionData( symbol=d["contract_code"], exchange=Exchange.HUOBI, direction=DIRECTION_HBDM2VT[d["direction"]], gateway_name=self.gateway_name) self.positions[key] = position position.volume = d["volume"] position.frozen = d["frozen"] position.price = d["cost_hold"] position.pnl = d["profit"] for position in self.positions.values(): self.gateway.on_position(position)
def on_position_info(self, packet: dict) -> None: """""" positions = {} data = packet.get("data", []) for d in data: position = PositionData(symbol=d["symbol"].replace('.', '-'), exchange=Exchange.OTC, direction=Direction.NET, gateway_name=self.gateway_name) if d["type"] == POSITION_TYPE_BUY: position.volume = d["volume"] else: position.volume = -d["volume"] position.price = d["price"] position.pnl = d["current_profit"] positions[position.symbol] = position for symbol in self.position_symbols: if symbol not in positions: position = PositionData(symbol=symbol, exchange=Exchange.OTC, direction=Direction.NET, gateway_name=self.gateway_name) positions[symbol] = position for position in positions.values(): self.position_symbols.add(position.symbol) self.on_position(position)