tradingSystem/app/services/rotation_accounting.py

109 lines
5.3 KiB
Python

"""实有策略现金与净值。账本迁移演练后,在无在途委托的维护窗口初始化。"""
import datetime as dt
from app.core import rotation_account as core, strategy_book as books
from app.repo import rotation_repo as store, pms_repo, qmt_repo
from app.services import market
from app.core import ws_codec
def marked_values():
values = {b: 0. for b in core.BOOKS}
missing = []
positions = []
with books.scope('all'):
rows = pms_repo.list_positions(only_open=True)
for r in rows:
quote = market.day_snapshot(r['ts_code'])
price = quote.get('price')
if not price or price <= 0:
missing.append(r['ts_code'])
continue
value = int(r['total_qty'])*price
values[r['book_id']] += value
positions.append({'book_id': r['book_id'], 'code': r['ts_code'], 'qty': r['total_qty'],
'market_value': value, 'price': price, 'cost': float(r.get('avg_cost') or 0)*int(r['total_qty'])})
if missing:
raise ValueError('策略估值行情缺失:'+','.join(missing))
return values, positions
def initialize():
"""只在显式迁移操作中调用;不可在交易路径猜测重建现金归属。"""
from app.db import session as db
from app.services.rotation_service import reconcile_books
with store.account_guard():
if store.get('capital:live')[0]:
return {'exists': True}
pending = db.fetch_all("SELECT instruction_id FROM pms_qmt_order WHERE status IN ('QUEUED','SENDING','SENT','ACCEPTED','SUBMITTED','PARTIAL') LIMIT 1")
if pending or not reconcile_books()['ok']:
raise ValueError('现金初始化需要无在途委托且数量对账一致')
snap = qmt_repo.latest_snapshot('funds')
if not snap or snap.get('age_sec', 999) > 60:
raise ValueError('现金初始化需要一分钟内资金快照')
funds = ws_codec.parse_funds_snapshot(snap['payload'])
if funds.get('available_cash') is None or funds.get('frozen_cash', 0):
raise ValueError('资金冻结未解除或现金未知')
values, _ = marked_values()
if values['micro30']:
raise ValueError('迁移初始微盘账本必须为空')
value = core.seed(float(funds['available_cash']), values)
value.update(started_at=dt.datetime.now().isoformat(), source_funds_seq=snap['seq'])
store.put_once('capital:live', 'capital', value)
return {'initialized': True, 'source_funds_seq': snap['seq']}
def reserve_book(book, demand, pending, phase):
"""账户锁内调用。只划拨已存在现金,跨策略在途保留不可再次使用。"""
reserved = {b: 0. for b in core.BOOKS}
with books.scope('all'):
for o in pending:
if o['side'] != 'buy':
continue
parent = pms_repo.get_instruction(o['parent_id'])
if not parent or parent.get('book_id') not in core.BOOKS:
raise ValueError('在途委托策略归属未知')
remaining = max(0, int(o['qty'])-int(o.get('cum_qty') or 0))
if remaining:
from app.services.rotation_service import configuration
from app.core.micro_rotation import fee
amount = remaining*float(o['limit_price'])
reserved[parent['book_id']] += amount+fee(amount,'buy',**configuration()['costs'])
with store.locked('capital:live', 'capital', {}) as value:
if not value.get('cash'):
raise ValueError('分策略现金尚未初始化')
need = max(0., demand-(value['cash'][book]-reserved[book]))
if not need:
return
source = 'original' if book == 'micro30' else 'micro30'
if (book == 'micro30' and phase not in ('entering_micro','micro')) or (book == 'original' and phase not in ('returning_original','original')):
raise ValueError('当前阶段不允许现金划拨')
if value['cash'][source]-reserved[source] < need-1e-6:
raise ValueError('源策略现金不足或仍被在途委托占用')
values, _ = marked_values()
key = 'allocation:'+str(len(value['transfers'])+1)
core.transfer(value, source, book, need, values, key)
store.put_once('transfer:'+key, 'cash_transfer', {'key': key, **value['transfers'][key]})
def record_fill(book, side, amount, fees, key):
with store.locked('capital:live', 'capital', {}) as value:
if not value.get('cash'):
raise ValueError('分策略现金尚未初始化')
core.fill(value, book, side, amount, fees, key)
def view():
value, _ = store.get('capital:live')
if not value:
return {'ready': False, 'reason': '分策略现金尚未初始化'}
values, positions = marked_values()
result = core.metrics(value, values)
snap = qmt_repo.latest_snapshot('funds')
cash_difference = None
if snap and snap.get('age_sec', 999) <= 60:
funds = ws_codec.parse_funds_snapshot(snap['payload'])
if funds.get('available_cash') is not None and funds.get('frozen_cash') is not None:
cash_difference = result['account']['cash']-funds['available_cash']-funds['frozen_cash']
return {'ready': True, 'metrics': result, 'positions': positions, 'cash_difference': cash_difference,
'started_at': value.get('started_at'), 'transfer_count': len(value['transfers'])}