微盘轮动优先补空位并按实际额度提示限制
This commit is contained in:
parent
a53c4f0c99
commit
1c9cf686ec
|
|
@ -206,7 +206,7 @@ def preflight(members, budget, allowed_boards, costs):
|
|||
|
||||
|
||||
def orders(state, snapshot, *, original, micro, quotes, cash, account_mv, cap_amount,
|
||||
reserve_cash=0., pending=(), control='run', blacklisted=(), costs=None):
|
||||
reserve_cash=0., pending=(), control='run', blacklisted=(), costs=None, unavailable=()):
|
||||
"""只形成意图,不把计划卖出计入现金。调用者落表后再执行。"""
|
||||
from app.core.planner import plan_reduce_exposure
|
||||
costs = costs or {}
|
||||
|
|
@ -251,7 +251,11 @@ def orders(state, snapshot, *, original, micro, quotes, cash, account_mv, cap_am
|
|||
candidates = sorted(target) if phase == 'entering_micro' else sorted(set(missing)|{
|
||||
c for c, t in objectives.items() if int(t['qty']) > int(micro_by.get(c, {}).get('total_qty') or 0)})
|
||||
per_new = available/len(missing) if missing else 0.
|
||||
seat_first = state.get('rule_version') == EXECUTION_RULE
|
||||
requests = {}
|
||||
for c in candidates:
|
||||
if c in unavailable:
|
||||
continue
|
||||
if c in original_by or c in active_codes or c in blacklisted:
|
||||
waits.append(c+'旧仓、在途委托或黑名单阻止买入')
|
||||
continue
|
||||
|
|
@ -272,23 +276,48 @@ def orders(state, snapshot, *, original, micro, quotes, cash, account_mv, cap_am
|
|||
waits.append(c+'份额不足最小交易单位及费用')
|
||||
continue
|
||||
remaining_qty = max(0, quantities[c]-owned_qty)
|
||||
desired = remaining_qty*price+fee(remaining_qty*price, 'buy', **costs) if remaining_qty else 0.
|
||||
else:
|
||||
if c not in objectives:
|
||||
target_qty = buy_qty(c, price, per_new, costs)
|
||||
if seat_first and not target_qty:
|
||||
minimum = min_qty(c)
|
||||
if minimum*price+fee(minimum*price, 'buy', **costs) <= available:
|
||||
target_qty = minimum
|
||||
if not target_qty:
|
||||
waits.append(c+'可用资金不足最小交易单位及费用')
|
||||
continue
|
||||
objectives[c] = {'qty': target_qty, 'snapshot_version': snapshot['snapshot_version'],
|
||||
'effective_date': snapshot['effective_date']}
|
||||
remaining_qty = max(0, int(objectives[c]['qty'])-owned_qty)
|
||||
desired = remaining_qty*price+fee(remaining_qty*price, 'buy', **costs) if remaining_qty else 0.
|
||||
budget = min(available, desired)
|
||||
qty = buy_qty(c, price, budget, costs)
|
||||
qty = min(qty, remaining_qty)
|
||||
if remaining_qty >= min_qty(c):
|
||||
requests[c] = (price, remaining_qty)
|
||||
|
||||
def charge(code, qty):
|
||||
amount = requests[code][0]*qty
|
||||
return amount+fee(amount, 'buy', **costs) if qty else 0.
|
||||
|
||||
seats = [c for c in state['target'] if c in requests and c not in micro_by] if seat_first else []
|
||||
allocation = {}
|
||||
for c in seats:
|
||||
minimum = min_qty(c)
|
||||
cost = charge(c, minimum)
|
||||
if cost <= available:
|
||||
allocation[c] = minimum
|
||||
available -= cost
|
||||
else:
|
||||
waits.append(c+'可用现金或全账户剩余仓位不足一手,等待补入')
|
||||
ordered = seats+[c for c in requests if c not in seats]
|
||||
for c in ordered:
|
||||
price, remaining_qty = requests[c]
|
||||
qty = allocation.get(c, 0)
|
||||
if len(allocation) == len(seats):
|
||||
reserved = charge(c, qty)
|
||||
funded = buy_qty(c, price, available+reserved, costs)
|
||||
new_qty = max(qty, min(funded, remaining_qty//100*100))
|
||||
available -= charge(c, new_qty)-reserved
|
||||
qty = new_qty
|
||||
if qty:
|
||||
result.append({'book_id': 'micro30', 'ts_code': c, 'side': 'buy', 'qty': qty, 'reason': '初始建仓补齐' if phase == 'entering_micro' else '名单调入'})
|
||||
available -= qty*price+fee(qty*price, 'buy', **costs)
|
||||
return result, waits
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1533,18 +1533,9 @@ def build_daily_report(ymd: int = None) -> dict:
|
|||
attention.append({"type": "行情缺失", "codes": v["price_missing"]})
|
||||
if not v["sector_ready"]:
|
||||
attention.append({"type": "行业约束停用", "hint": "PMS_SECTOR_SOURCE 未配置"})
|
||||
# 总规模与账户实际总资产的偏差。**这条必须每天摆出来**: 三道仓位闸 (总仓/单股/只数) 全部
|
||||
# 以 PMS_TOTAL_SCALE 为基准算, 而它是用户命令参数, 不是账户余额。两者一旦差得远, 规划器
|
||||
# 会排出账户根本执行不了的方案, 却一路过闸 —— 到 QMT 那儿才被 INSUFFICIENT_CASH 拒。
|
||||
# 07-30 就是这个情形: scale 200 万 vs 模拟账户 98 万, 差一倍而页面上看不出任何异常。
|
||||
ta, scale_v = t.get("total_asset"), float(t.get("scale") or 0)
|
||||
if ta and scale_v > 0:
|
||||
gap = float(ta) / scale_v - 1
|
||||
if abs(gap) > param_store.get_float("PMS_SCALE_GAP_ALARM", 0.10):
|
||||
attention.append({"type": "规模与账户不符", "scale": scale_v,
|
||||
"total_asset": round(float(ta), 2), "gap": round(gap, 4),
|
||||
"hint": "仓位上限按 scale 算, 资金校验按账户算 —— 差得远时方案会"
|
||||
"过闸但下不出去。改 PMS_TOTAL_SCALE 或核对账户"})
|
||||
buying_room = portfolio.account_buying_room(t, v['params'])
|
||||
if buying_room.get('warning'):
|
||||
attention.append({'type': '账户新增买入受限', 'hint': buying_room['warning']})
|
||||
if t.get("cash_source") != "ws":
|
||||
attention.append({"type": "资金快照未接通", "hint": t.get("cash_why") or "",
|
||||
"note": "买入前的资金校验已降级 (只按 scale−市值 估算), 见规则闸的 "
|
||||
|
|
|
|||
|
|
@ -344,6 +344,26 @@ def account_performance(cash=None) -> dict:
|
|||
return empty
|
||||
|
||||
|
||||
def account_buying_room(totals, params) -> dict:
|
||||
if totals.get('cash_source') != CASH_WS:
|
||||
return {}
|
||||
scale, ratio = params.get('scale'), params.get('portfolio_cap')
|
||||
market_value, cash = totals.get('account_market_value'), totals.get('cash_avail')
|
||||
if not all(isinstance(value, (int, float)) and math.isfinite(value) and value >= 0
|
||||
for value in (scale, ratio, market_value, cash)) or not scale:
|
||||
return {}
|
||||
ceiling = round(scale*ratio, 2)
|
||||
cap_room = round(ceiling-market_value, 2)
|
||||
cash_room = round(cash-scale*params.get('cash_reserve', 0), 2)
|
||||
if cap_room <= 0:
|
||||
warning = f'账户新增买入受限:持仓市值 {market_value:,.2f} 元,仓位上限 {ceiling:,.2f} 元,当前无新增仓位额度。卖出不受这项限制。'
|
||||
elif cash_room <= 0:
|
||||
warning = '账户新增买入受限:扣除计划保留的资金后,没有可用于新增买入的现金。卖出不受这项限制。'
|
||||
else:
|
||||
warning = ''
|
||||
return {'cap': ceiling, 'cap_room': cap_room, 'cash_room': cash_room, 'warning': warning}
|
||||
|
||||
|
||||
def overview() -> dict:
|
||||
"""页面顶部仪表 (总览)。任何一环取不到都不该让页面开不了 —— 逐项 try。"""
|
||||
try:
|
||||
|
|
@ -364,6 +384,7 @@ def overview() -> dict:
|
|||
"account_performance": account_performance(t),
|
||||
"holding_performance": holding_performance(position_groups(v)),
|
||||
"account_market_value": t["account_market_value"], "frozen_cash": t["frozen_cash"],
|
||||
"account_buying_room": account_buying_room(t, p),
|
||||
"float_pnl": t["float_pnl"],
|
||||
"float_pnl_pct": t["float_pnl_pct"], "solid_names": t["solid_names"],
|
||||
"neg_names": t["neg_names"], "autonomy": p["autonomy"],
|
||||
|
|
|
|||
|
|
@ -536,7 +536,8 @@ def _tick(now=None, *, prepare_only=False, day_orders=None):
|
|||
planning_quotes = {**quotes, **buy_prices}
|
||||
intents, waits = core.orders(s, value, original=original, micro=micro, quotes=planning_quotes,
|
||||
cash=cash, account_mv=account_mv, cap_amount=cap, reserve_cash=reserve,
|
||||
pending=pending, control=config['control'], blacklisted=black, costs=config['costs'])
|
||||
pending=pending, control=config['control'], blacklisted=black, costs=config['costs'],
|
||||
unavailable=unavailable if s.get('rule_version') == core.EXECUTION_RULE else ())
|
||||
# 纸面档明确采用全沪深权限假设,不把它当实际账户权限判收。
|
||||
issues = core.preflight(value['members'], budget, boards, config['costs']) if value['basket_ready'] else ['名单未就绪']
|
||||
if issues and s.get('rule_version') != core.EXECUTION_RULE:
|
||||
|
|
|
|||
|
|
@ -765,8 +765,8 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
|
|||
<el-alert v-if="macroUnavailable" class="banner" type="warning" show-icon :closable="false"
|
||||
:title="'大盘冷热的数据读不到,今天这一层不做任何动作、也不加限制: ' + macroUnavailable"></el-alert>
|
||||
|
||||
<el-alert v-if="scaleGap" class="banner" type="warning" effect="dark" show-icon :closable="false"
|
||||
:title="'参数总规模与账户实际对不上 —— 参数里写的是 ' + money(ov.scale) + ',账户总资产是 ' + money(ov.total_asset) + '(差 ' + pct(scaleGap) + ')。仓位上限按参数算,钱够不够按账户算。两个数差得远,方案会通过检查但下不出去。'"></el-alert>
|
||||
<el-alert v-if="ov.account_buying_room?.warning" class="banner" type="warning" effect="dark" show-icon :closable="false"
|
||||
:title="ov.account_buying_room.warning"></el-alert>
|
||||
|
||||
<!-- ==================== 交易员视图 (2026-08-26 三栏改版) ==================== -->
|
||||
<div v-show="mode==='trader'">
|
||||
|
|
@ -3315,14 +3315,6 @@ createApp({
|
|||
// ---- ws 通道监控 (只读)
|
||||
const wsRaw = ref({}), wsAuto = ref(true), wsHidePong = ref(true);
|
||||
let wsTimer = null;
|
||||
// 总规模(用户命令参数) 与 账户实际总资产(ws 资金快照) 的偏差。三道仓位闸都按 scale 算,
|
||||
// 资金校验按账户算 —— 差得远时方案会过闸但下不出去, 而页面上原来完全看不出来。
|
||||
const scaleGap = computed(() => {
|
||||
const ta = Number(ov.value.total_asset || 0), s = Number(ov.value.scale || 0);
|
||||
if (!ta || !s) return 0;
|
||||
const g = ta / s - 1;
|
||||
return Math.abs(g) > 0.10 ? g : 0;
|
||||
});
|
||||
|
||||
// 通道状态优先取 ws-channel (管理员接口), 取不到回落 dispatch-mode 里的 channel ——
|
||||
// 纯交易员没有 ws-channel 权限, 原来「通道没连上」这类告警对他们永远不亮 (2026-08-28)。
|
||||
|
|
@ -5869,7 +5861,6 @@ createApp({
|
|||
positions, positionGroups, positionTab, positionLedgerTab, positionKey, lotsByPosition, instructions, ledger, ledgerToday, proposals, preparingProposals,
|
||||
opsDrawer, opsResult, opsLoading, issuing, form, curSpec, dirtyCount, dm,
|
||||
money, costPrice, pct, groupLabel, fieldLabel, stTag, cuTag, logicTag, canCancel, progPct, insPct,
|
||||
scaleGap,
|
||||
wsRaw, wsAuto, wsHidePong, wsc, wst, wsMode, wsOrders, wsInbox, wsWarnings, loadWs,
|
||||
loadAll, loadParams, saveParams, loadPlans, loadLots, onCmdChange, issue,
|
||||
cancelCmd, replan, decide, decideDlg, decideCodes, submitDecide, ops, loadSchema, cancelIns, researchData, researchSections, researchMaterials, researchSource, openResearch,
|
||||
|
|
|
|||
|
|
@ -104,6 +104,23 @@ class AccountFundsTest(unittest.TestCase):
|
|||
self.assertEqual(result['portfolio_mv'], 1000)
|
||||
self.assertEqual(result['cash_avail'], 1806071.62)
|
||||
|
||||
def test_buying_room_is_not_a_warning_just_because_capital_differs_from_equity(self):
|
||||
self.fake = install_fakes(params={'PMS_TOTAL_SCALE':'1967927.74','PMS_PORTFOLIO_CAP':'0.70'})
|
||||
self.funds(available_cash=383116.74, market_value=1363207., total_asset=1746323.74)
|
||||
result = portfolio.overview()['account_buying_room']
|
||||
self.assertEqual(result, {'cap':1377549.42,'cap_room':14342.42,'cash_room':383116.74,'warning':''})
|
||||
|
||||
def test_buying_warning_uses_real_account_market_value_and_actual_cash(self):
|
||||
self.fake = install_fakes(params={'PMS_TOTAL_SCALE':'2000000','PMS_PORTFOLIO_CAP':'0.70'})
|
||||
self.funds(available_cash=200000, market_value=1450000, total_asset=1650000)
|
||||
result = portfolio.overview()['account_buying_room']
|
||||
self.assertEqual(result['cap_room'], -50000.)
|
||||
self.assertIn('当前无新增仓位额度', result['warning'])
|
||||
self.funds(available_cash=0, market_value=1000000, total_asset=1000000)
|
||||
self.assertIn('没有可用于新增买入的现金', portfolio.overview()['account_buying_room']['warning'])
|
||||
self.funds(available_cash=200000, market_value=None, total_asset=1000000)
|
||||
self.assertEqual(portfolio.overview()['account_buying_room'], {})
|
||||
|
||||
|
||||
class AccountPerformanceTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
|
|
|
|||
|
|
@ -137,6 +137,33 @@ class TargetTests(unittest.TestCase):
|
|||
quotes={'600000.SH': {'price': 1}}, cash=10000, account_mv=0, cap_amount=100000)
|
||||
self.assertEqual(orders[0]['qty'], 200)
|
||||
|
||||
def test_tight_headroom_buys_all_four_empty_seats_before_topping_up(self):
|
||||
snap = snapshot(); s = state(snap)
|
||||
listed = [row['code'] for row in snap['members']]
|
||||
missing = listed[-4:-1]+['688251.SH']
|
||||
s['target'] = listed[:-4]+missing
|
||||
s['entry_quantities'] = {code: 2000 for code in s['target']}
|
||||
held = [{'ts_code':code, 'total_qty':100} for code in listed[:-4]]
|
||||
quotes = {code: {'price':13.2 if code=='688251.SH' else 10.} for code in s['target']}
|
||||
orders, waits = m.orders(s, snap, original=[], micro=held, quotes=quotes,
|
||||
cash=383116.74, account_mv=1371500, cap_amount=1377549.42)
|
||||
buys = [row for row in orders if row['side']=='buy']
|
||||
self.assertEqual([row['ts_code'] for row in buys], missing)
|
||||
self.assertGreaterEqual(buys[-1]['qty'], 200)
|
||||
costs = [row['qty']*quotes[row['ts_code']]['price'] for row in buys]
|
||||
self.assertLessEqual(sum(cost+m.fee(cost,'buy') for cost in costs), 6049.42)
|
||||
self.assertEqual(waits, [])
|
||||
self.assertTrue(all(qty == 2000 for qty in s['entry_quantities'].values()))
|
||||
|
||||
def test_full_cap_waits_for_capacity_but_still_sells_removed_securities(self):
|
||||
snap = snapshot(); s = state(snap)
|
||||
orders, waits = m.orders(s, snap, original=[], micro=[{'ts_code':'600099.SH','total_qty':100}],
|
||||
quotes={row['code']:{'price':10.} for row in snap['members']},
|
||||
cash=383116.74, account_mv=1377550, cap_amount=1377549.42)
|
||||
self.assertEqual([(row['ts_code'],row['side']) for row in orders],[('600099.SH','sell')])
|
||||
self.assertEqual(len(waits), 50)
|
||||
self.assertTrue(all('全账户剩余仓位不足一手' in reason for reason in waits))
|
||||
|
||||
def test_old_positions_do_not_create_cash(self):
|
||||
snap = snapshot(); s = state(snap)
|
||||
orders, _ = m.orders(s, snap, original=[{'ts_code': '000001.SZ', 'total_qty': 100}], micro=[],
|
||||
|
|
|
|||
Loading…
Reference in New Issue