策略中怎么获取我当前的持仓列表和委托列表啊?
策略中怎么获取我当前的持仓列表和委托列表啊?
在 vn.py 的策略中,你可以通过以下方法获取当前的持仓列表和委托列表:
在策略中,可以使用 self.cta_engine.main_engine.get_all_positions() 方法获取当前账户的全部持仓信息。
def get_positions(self):
"""获取当前持仓列表"""
positions = self.cta_engine.main_engine.get_all_positions()
for position in positions:
print(f"合约: {position.vt_symbol}, 方向: {position.direction}, 数量: {position.volume}, 均价: {position.price}, 盈亏: {position.pnl}")
positions 是一个 PositionData 对象的列表,每个对象包含以下字段:vt_symbol: 合约代码(格式为 symbol.exchange,例如 rb2210.SHFE)。direction: 持仓方向(多、空 或 净)。volume: 持仓数量。price: 持仓均价。pnl: 持仓盈亏。在策略中,可以使用 self.cta_engine.main_engine.get_all_active_orders() 方法获取当前账户的所有活动委托。
def get_orders(self):
"""获取当前委托列表"""
orders = self.cta_engine.main_engine.get_all_active_orders()
for order in orders:
print(f"委托号: {order.vt_orderid}, 合约: {order.vt_symbol}, 方向: {order.direction}, 开平: {order.offset}, 价格: {order.price}, 数量: {order.volume}, 状态: {order.status}")
orders 是一个 OrderData 对象的列表,每个对象包含以下字段:vt_orderid: 委托号(唯一标识)。vt_symbol: 合约代码。direction: 委托方向(多 或 空)。offset: 开平方向(开仓 或 平仓)。price: 委托价格。volume: 委托数量。status: 委托状态(提交中、未成交、部分成交、全部成交、已撤销 等)。你可以在策略的 on_tick、on_bar 或其他回调函数中调用上述方法,实时获取持仓和委托信息。
from vnpy.trader.constant import Direction, Offset
from vnpy.trader.object import PositionData, OrderData
class MyStrategy(CtaTemplate):
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
def on_tick(self, tick: TickData):
"""Tick 更新回调"""
self.get_positions() # 获取持仓列表
self.get_orders() # 获取委托列表
def get_positions(self):
"""获取当前持仓列表"""
positions = self.cta_engine.main_engine.get_all_positions()
for position in positions:
print(f"合约: {position.vt_symbol}, 方向: {position.direction}, 数量: {position.volume}, 均价: {position.price}, 盈亏: {position.pnl}")
def get_orders(self):
"""获取当前委托列表"""
orders = self.cta_engine.main_engine.get_all_active_orders()
for order in orders:
print(f"委托号: {order.vt_orderid}, 合约: {order.vt_symbol}, 方向: {order.direction}, 开平: {order.offset}, 价格: {order.price}, 数量: {order.volume}, 状态: {order.status}")
self.cta_engine.main_engine.get_all_positions() 获取持仓列表。self.cta_engine.main_engine.get_all_active_orders() 获取委托列表。通过以上方法,你可以在策略中轻松获取当前的持仓和委托列表。如果有其他问题,欢迎继续讨论!