查持仓和资金:两套字段对不上
这是工程记录。只打印可用资金、持仓量、成本,用来对账。不当调仓指令。不构成投资建议,不代操盘。
QMT:ACCOUNT + POSITION
python
#coding:gbk
def init(C):
C.acc = '你的资金账号'
C.acct_type = 'STOCK' # 两融 CREDIT
def handlebar(C):
if not C.is_last_bar():
return
accts = get_trade_detail_data(C.acc, C.acct_type, 'ACCOUNT') or []
poss = get_trade_detail_data(C.acc, C.acct_type, 'POSITION') or []
if accts:
a = accts[0]
print('available', getattr(a, 'm_dAvailable', None),
'balance', getattr(a, 'm_dBalance', None))
print('positions', len(poss))
for p in poss:
print(getattr(p, 'm_strInstrumentID', ''),
'vol', getattr(p, 'm_nVolume', None),
'can', getattr(p, 'm_nCanUseVolume', None),
'cost', getattr(p, 'm_dOpenCost', None) or getattr(p, 'm_dCostPrice', None))字段名不同版本可能略差,空的时候 dir(obj) 看实际属性。期货账号类型用 FUTURE。
PTrade:portfolio + get_position
python
def handle_data(context, data):
port = context.portfolio
log.info('cash=%s value=%s', port.cash, port.portfolio_value)
for sid, pos in (getattr(port, 'positions', {}) or {}).items():
if pos.amount == 0:
continue
log.info('%s amount=%s enable=%s cost=%s', sid, pos.amount, pos.enable_amount, pos.cost_basis)
one = get_position('600000.SS')
log.info('one amount=%s enable=%s', one.amount, one.enable_amount)get_positions() 不传代码时拿全部;传代码拿单只。对象字段是 amount / enable_amount / cost_basis,和 QMT 的 m_ 前缀不是一套。
坑
- 两套不能对字段名硬拷。先各自打印再映射到你自己的账本。
- QMT 查询带
strategyName时,ORDER/DEAL 会过滤;POSITION/ACCOUNT 仍是账户级,不要当成策略隔离账本。 - 可用不等于可卖。T+1、新买入、冻结,都会让
enable/m_nCanUseVolume小于总量。 - 信用账号看担保品和两融字段,不要用普通户的
m_dAvailable去套。 - PTrade 当天卖掉的票
amount=0仍在列表里,见 聚宽转 PTrade。
完整讨论和附件在 知识星球 Kimi量化研究所。
