交易指令按策略分组并隔离查询撤单

This commit is contained in:
baobao 2026-11-02 09:36:29 +08:00 committed by Codex deployment
parent 1d73431f04
commit 381ddf836c
4 changed files with 160 additions and 31 deletions

View File

@ -444,12 +444,17 @@ def api_lots(ts_code: str, status: str = Query("OPEN"),
@app.get("/api/instructions")
def api_instructions(status: str = Query(None), limit: int = 200,
include_archived: bool = Query(False)):
include_archived: bool = Query(False),
book_id: Literal["original", "micro30"] = Query("original")):
statuses = [s for s in (status or "").split(",") if s] or None
def _list():
from app.core import strategy_book as books
from app.services.execution_conflicts import instruction_progress
return instruction_progress(pms_repo.list_instructions(statuses=statuses, limit=limit,
include_archived=include_archived))
if book_id == books.MICRO and not settings.INFRA_STRATEGY_BOOK_SCHEMA:
return []
with books.scope(book_id):
return instruction_progress(pms_repo.list_instructions(statuses=statuses, limit=limit,
include_archived=include_archived))
return ok(_list)
@ -790,11 +795,18 @@ def api_sweep_windows():
@app.post("/api/instructions/{instruction_id}/cancel")
def api_cancel_instruction(instruction_id: str, payload: dict = Body(default={})):
def api_cancel_instruction(instruction_id: str, payload: dict = Body(default={}),
book_id: Literal["original", "micro30"] = Query("original")):
from app.core import strategy_book as books
from app.services import executor
return ok_logged("cancel_instruction", executor.cancel_instruction, instruction_id,
def _cancel(iid, reason):
if book_id == books.MICRO and not settings.INFRA_STRATEGY_BOOK_SCHEMA:
return {"ok": False, "error": "微盘轮动账本尚未启用"}
with books.scope(book_id):
return executor.cancel_instruction(iid, reason)
return ok_logged("cancel_instruction", _cancel, instruction_id,
payload.get("reason") or "页面人工撤销",
params={"instruction_id": instruction_id})
params={"instruction_id": instruction_id, "book_id": book_id})
@app.post("/api/ops/scan-proposals")

View File

@ -368,6 +368,10 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
状态芯片一行、「下一步」短语一行放下, 具体说明进悬停。 */
.position-tabs > .el-tabs__header{margin-bottom:8px;}
.position-tabs .tabn{margin-left:6px;}
.instruction-books .el-tabs__item{padding:0 14px;}
.instruction-status > .el-tabs__header{margin-bottom:8px;}
.instruction-status .el-tabs__item{font-size:12px;height:32px;padding:0 9px;}
.instruction-status .el-tabs__nav-wrap::after{height:0;}
.book-heading{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;margin:10px 0;}
.book-heading .book-stat{font-size:12px;color:var(--muted);}
.postbl .el-scrollbar__wrap{overflow-x:auto;}
@ -1184,10 +1188,16 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
</div>
<!-- 当日指令 -->
<div class="panel tblk" id="t-ins">
<div class="panel tblk postbl" id="t-ins">
<h3>当日指令</h3>
<div class="sub2">在办买卖安排及今日成交;跨日买入须重新复核</div>
<el-tabs v-model="insTab">
<el-tabs v-model="instructionTab" class="position-tabs instruction-books">
<el-tab-pane v-for="book in instructionBooks" :key="book.id" :name="'ins-'+book.id">
<template #label>{{ book.name }} <span class="tabn">{{ instructionReady[book.id] ? instructionCounts[book.id] : '—' }}</span></template>
</el-tab-pane>
</el-tabs>
<el-alert v-if="!instructionReady[instructionBook]" title="该策略指令读取失败,请刷新后重试。" type="warning" :closable="false"></el-alert>
<el-tabs v-else v-model="insTab" class="instruction-status">
<el-tab-pane name="live">
<template #label>未成交 <span class="tabn">{{ insLive.length }}</span></template>
<el-table :data="insLive" size="small" max-height="280" empty-text="现在没有未成交的买卖单">
@ -1196,7 +1206,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<el-table-column label="计划量 / 已成交" width="130" align="right"><template #default="s"><span class="mono">{{ s.row.qty }} / {{ s.row.exec_qty||0 }}</span></template></el-table-column>
<el-table-column label="委托限价" width="88" align="right"><template #default="s"><span class="mono">{{ s.row.execution_limit||'—' }}</span></template></el-table-column>
<el-table-column label="进展" min-width="130"><template #default="s"><span class="chip idle" :title="s.row.execution_note || ''"><span class="dot"></span>{{ s.row.execution_label || tx('insStatus', s.row.status) }}</span></template></el-table-column>
<el-table-column label="操作" width="76" fixed="right"><template #default="s"><button class="tbtn sm" @click="cancelIns(s.row.instruction_id)">撤单</button></template></el-table-column>
<el-table-column label="操作" width="76" fixed="right"><template #default="s"><button class="tbtn sm" @click="cancelIns(s.row)">撤单</button></template></el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane name="done">
@ -1216,7 +1226,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<el-table-column label="怎么结束的" min-width="150"><template #default="s"><span class="chip warn"><span class="dot"></span>{{ s.row.execution_label || tx('insStatus', s.row.status) }}</span></template></el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane name="deny">
<el-tab-pane v-if="instructionBook==='original'" name="deny">
<template #label>未建仓候选 <span class="tabn">{{ denyToday.length }}</span></template>
<div class="sub2" style="margin:8px 2px 4px">未建仓候选</div>
<el-table :data="denyToday" size="small" max-height="320" empty-text="当前没有未建仓的候选">
@ -1999,11 +2009,17 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
</el-tabs>
</div>
<div class="panel">
<div class="panel postbl" id="instruction-ledger">
<h3>在途指令
<el-checkbox v-model="showAllInstr" size="small" style="margin-left:12px;font-weight:normal">显示已了结</el-checkbox>
</h3>
<el-table :data="instrLive" size="small" border max-height="320" empty-text="没有在途指令">
<el-tabs v-model="instructionLedgerTab" class="position-tabs instruction-books">
<el-tab-pane v-for="book in instructionBooks" :key="book.id" :name="'ins-ledger-'+book.id">
<template #label>{{ book.name }}</template>
</el-tab-pane>
</el-tabs>
<el-alert v-if="!instructionReady[instructionLedgerBook]" title="该策略指令读取失败,请刷新后重试。" type="warning" :closable="false"></el-alert>
<el-table v-else :data="instrLive" size="small" border max-height="320" empty-text="该策略暂无指令">
<el-table-column type="expand" width="40">
<template #default="s">
<div style="padding:6px 16px">
@ -2047,9 +2063,9 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
</el-table-column>
<el-table-column prop="status" label="状态" width="115"></el-table-column>
<el-table-column prop="origin_type" label="来源" width="80"></el-table-column>
<el-table-column label="操作" width="90">
<el-table-column label="操作" width="90" fixed="right">
<template #default="s">
<el-button size="small" @click="cancelIns(s.row.instruction_id)">撤销</el-button>
<el-button v-if="canCancelIns(s.row)" size="small" @click="cancelIns(s.row)">撤销</el-button>
</template>
</el-table-column>
</el-table>
@ -2794,6 +2810,13 @@ createApp({
const positionKey = row => (row.book_id || 'original') + ':' + row.ts_code;
const lotsRequests = {};
const instructions = ref([]), ledger = ref([]), proposals = ref([]), preparingProposals = ref([]);
const instructionBooks = [{id:'original',name:'主观量化'}, {id:'micro30',name:'微盘轮动'}];
const instructionReady = reactive({original:true,micro30:true});
const instructionTab = ref('ins-original'), instructionLedgerTab = ref('ins-ledger-original');
const instructionBook = computed(() => instructionTab.value.slice(4));
const instructionLedgerBook = computed(() => instructionLedgerTab.value.slice(11));
const bookInstructions = computed(() => instructions.value.filter(r => r.book_id===instructionBook.value));
const instructionBookName = book => (instructionBooks.find(b => b.id===book)||{}).name || '策略待核实';
const strategies = ref([]), stratEnabled = ref(false), opLog = ref([]);
const autoScanRes = ref(null), autoScanBusy = ref(false); // 自动挂载试算 (2026-08-25)
const autoInfo = ref(null); // 自动挂载仪表: 总开关 + 今天正式一跳跑没跑 (2026-08-26)
@ -2839,6 +2862,7 @@ createApp({
} finally { dividendBusy.value = ''; }
}
const insTab = ref('live');
watch(instructionBook, () => { if (insTab.value==='deny') insTab.value='live'; });
const stratDlg = reactive({ visible:false, busy:false, reasons:[], ts_code:'', price:0,
total_qty:0, avail_qty:0, cushion_pct:null, type:'T0', autonomy:'auto',
p:{ t_ratio:0.2, lower:0, upper:0, center:0, step_pct:0.02, per_lot:100, max_capital:0,
@ -3240,11 +3264,15 @@ createApp({
const id = String(r.instruction_id || '');
// 策略指令的前缀是 STR{ymd} (strategy_runner), 不是 INS_ —— 原来它们一进终态就从
// 「已成交/已终止」和消息栏同时消失, 交易员眼看着自己的单子凭空不见 (2026-08-28)
return !y || id.indexOf('INS_' + y + '_') === 0 || id.indexOf('STR' + y) === 0; };
return !y || id.indexOf('INS_' + y + '_') === 0 || id.indexOf('STR' + y) === 0
|| (id.startsWith('ROT_') && String(r.created_at||'').slice(0,10).replaceAll('-','')===y); };
// 已归档的一律不进「当日指令」三档 —— 归档=从所有面板隐藏。
const insLive = computed(() => (instructions.value || []).filter(r => _LIVE_INS.includes(r.status) && !_isArch(r)));
const insDone = computed(() => (instructions.value || []).filter(r => r.status === 'CONFIRMED' && _sameDayIns(r) && !_isArch(r)));
const insEnd = computed(() => (instructions.value || []).filter(r => ['EXPIRED', 'CANCELLED', 'REJECTED'].includes(r.status) && _sameDayIns(r) && !_isArch(r)));
const canCancelIns = r => _LIVE_INS.includes(r.status) && !_isArch(r);
const insLive = computed(() => bookInstructions.value.filter(canCancelIns));
const insDone = computed(() => bookInstructions.value.filter(r => r.status === 'CONFIRMED' && _sameDayIns(r) && !_isArch(r)));
const insEnd = computed(() => bookInstructions.value.filter(r => ['EXPIRED', 'CANCELLED', 'REJECTED'].includes(r.status) && _sameDayIns(r) && !_isArch(r)));
const instructionCounts = computed(() => Object.fromEntries(instructionBooks.map(b => [b.id,
instructions.value.filter(r => r.book_id===b.id && !_isArch(r) && (_LIVE_INS.includes(r.status) || _sameDayIns(r))).length])));
// 在办/在途/策略列表: 默认只看进行中; 「显示已完成」开关放开终态。命令与策略开关还会拉出已归档 (带恢复按钮)。
const _CMD_ACTIVE = ['PENDING', 'PLANNING', 'EXECUTING', 'PARTIAL', 'EFFECTIVE'];
const _STRAT_ACTIVE = ['ACTIVE', 'PAUSED'];
@ -3252,14 +3280,14 @@ createApp({
r => showAllCommands.value ? true : (_CMD_ACTIVE.includes(r.status) && !_isArch(r))));
const strategiesShown = computed(() => (strategies.value || []).filter(
r => showAllStrategies.value ? true : (_STRAT_ACTIVE.includes(r.status) && !_isArch(r))));
const instrLive = computed(() => (instructions.value || []).filter(
r => showAllInstr.value ? true : (_LIVE_INS.includes(r.status) && !_isArch(r))));
const instrLive = computed(() => instructions.value.filter(r => r.book_id===instructionLedgerBook.value
&& (showAllInstr.value || canCancelIns(r))));
// 哪些行可「移除」(只终态): 与后端 archive_* 的终态集一致。
const cmdArchivable = r => ['DONE', 'CANCELLED', 'SUPERSEDED'].includes(r.status);
const stratArchivable = r => ['CANCELLED', 'DONE'].includes(r.status);
// 每只候选今天为什么下单/没下单: 已落地的事实(指令/提议)优先, 其余看 /api/open-scan 的只读处置。
function dispOf(code) {
const inst = (instructions.value || []).find(i => i.ts_code === code && i.action === 'OPEN'
const inst = (instructions.value || []).find(i => i.book_id === 'original' && i.ts_code === code && i.action === 'OPEN'
&& (_LIVE_INS.includes(i.status) || _sameDayIns(i))); // 旧的终态单不算「已下单」(2026-08-28)
if (inst) {
// 系统自决自动采纳的指令 (2026-09-14): 进度里 auto 为真且理由以「系统采纳」开头, 显示「系统已采纳」。
@ -3935,9 +3963,14 @@ createApp({
positionGroups.value = d.strategy_groups || [];
}
async function loadInstructions() {
const d = await call('get',
'/api/instructions?status=PROPOSED,RULE_PASSED,JUDGE_PASSED,DISPATCHED,WAIT_REVIEW,CONFIRMED,EXPIRED,CANCELLED,REJECTED&limit=200');
instructions.value = d.data || [];
// 每个策略独立取最近200条,避免另一策略的历史记录挤掉当前指令。
const groups = await Promise.all(instructionBooks.map(async book => {
const d = await call('get',
'/api/instructions?status=PROPOSED,RULE_PASSED,JUDGE_PASSED,DISPATCHED,WAIT_REVIEW,CONFIRMED,EXPIRED,CANCELLED,REJECTED&limit=200&book_id='+book.id);
instructionReady[book.id] = d.ok===true && Array.isArray(d.data);
return instructionReady[book.id] ? d.data.map(row => ({...row,book_id:book.id})) : [];
}));
instructions.value = groups.flat();
}
async function loadLedger() {
const d = await call('get', '/api/ledger?limit=60'); ledger.value = d.data || [];
@ -4502,12 +4535,13 @@ createApp({
loading.value = false;
wsPollSync();
}
async function cancelIns(iid) {
async function cancelIns(row) {
const iid = row.instruction_id, book = row.book_id;
try {
await ElementPlus.ElMessageBox.confirm('撤销指令 ' + iid + '?', '确认',
await ElementPlus.ElMessageBox.confirm('撤销「' + instructionBookName(book) + '」的 ' + nm(row.ts_code) + ' 指令?', '确认撤单',
{ type: 'warning' });
} catch (e) { return; }
const d = await call('post', '/api/instructions/' + iid + '/cancel', {});
const d = await call('post', '/api/instructions/' + encodeURIComponent(iid) + '/cancel?book_id='+encodeURIComponent(book), {});
ElementPlus.ElMessage[(d.ok ? 'success' : 'error')](d.message || d.error);
await Promise.all([loadInstructions(), loadLedger()]);
}
@ -4943,8 +4977,9 @@ createApp({
if (_isArch(r) || !_sameDayIns(r)) continue;
const t = _at(r, ['updated_at', 'created_at', 'at', 'dispatched_at']);
out.push({ kind:'order', badge:insBadge(r), time:_hm(t), sort:_hms(t), ts_code:r.ts_code,
book_id:r.book_id, ins_status:r.status,
cat:tx('action', r.action) + ' · ' + (r.execution_label || tx('insStatus', r.status)),
strong:true, why:insWhy(r), goLabel:'看在办', go:'ins' });
strong:true, why:instructionBookName(r.book_id) + ' · ' + insWhy(r), goLabel:'看在办', go:'ins' });
}
// 3) 待确认提议 —— 自主档位是「只提议」时, 新提议在这里也提醒一次
for (const p of (proposals.value || [])) {
@ -5011,7 +5046,9 @@ createApp({
function setMsgKind(k) { msgKind.value = k; msgOpen.value = true; }
function msgGo(m) {
if (m.go === 'sig') { sigTab.value = 'brief'; openRailSide('l'); }
else if (m.go === 'ins') { msgOpen.value = false; scrollTo('t-ins'); }
else if (m.go === 'ins') { instructionTab.value='ins-'+m.book_id;
insTab.value=m.ins_status==='CONFIRMED'?'done':_LIVE_INS.includes(m.ins_status)?'live':'end';
msgOpen.value = false; scrollTo('t-ins'); }
else if (m.go === 'prop') { sectClosed.prop = false; openRailSide('r'); }
else if (m.go === 'strat') { sectClosed.strat = false; openRailSide('r'); }
}
@ -5161,6 +5198,8 @@ createApp({
showLedger, onPosExpand,
dividend, dividendShown, dividendBusy, dividendMore, prepareDividend, loadDividend,
openScan, insTab, todayYmd, insLive, insDone, insEnd, dispOf, conOf, loadOpenScan, denyToday,
instructionBooks, instructionReady, instructionTab, instructionLedgerTab, instructionBook,
instructionLedgerBook, instructionCounts, canCancelIns,
commandsShown, strategiesShown, instrLive, showAllCommands, showAllStrategies, showAllInstr,
cmdArchivable, stratArchivable, archiveRow,
showOpLog, showSettings, watchCandidates, scanNotes, marketOpen, marketState, lastRefresh, autoRefresh,

View File

@ -9,7 +9,7 @@
test_batch52_units.py 当日限价、撤单拒绝、迟到成交、发送恢复与真实SQL状态保护 (22例)
test_batch51_units.py 跨日决策复核、撤单回报、数量约束、人工确认与真实SQL事务及完整选股接线 (36例)
test_batch50_units.py QMT限价等待、价格来源故障、用户暂停、配额防重、试算隔离及收盘边界 (17例)
test_batch49_units.py 持仓分组、同名股票与批次归属、未迁移及缺数展示 (8例)
test_batch49_units.py 持仓与指令分组、同名股票及批次归属、撤单账本、未迁移及缺数展示 (14例)
test_batch48_units.py 策略账本隔离、轮换优先级、交易单位、模拟直接启用、读数及微盘50规则换版 (55例)
test_batch47_units.py 账户资金去重、买入额度与账户展示和策略估值分离 (9 例)
test_batch46_units.py 质地排序切换、档位准入、命令分配与白名单优先 (11 例)

View File

@ -1,4 +1,4 @@
"""持仓展示与批次查询的策略隔离。"""
"""持仓、批次及交易指令页面的策略隔离。"""
import unit_test_guard # noqa: F401
import copy
import unittest
@ -84,5 +84,83 @@ class PositionGroupsTests(unittest.TestCase):
read.assert_called_once_with('600000.SH', 'micro30', status=None)
class InstructionBooksTests(unittest.TestCase):
def setUp(self):
from app.web import main
self.api = main
def test_list_scopes_both_books_and_restores_caller(self):
from app.services import dispatcher
def read(**kw):
self.assertEqual(kw, {'statuses': ['DISPATCHED', 'CONFIRMED'],
'limit': 200, 'include_archived': False})
return [{'instruction_id': 'same-stock-'+books.CURRENT.get(),
'ts_code': '600000.SH', 'book_id': books.CURRENT.get(),
'status': 'CONFIRMED', 'qty': 100 if books.CURRENT.get()=='original' else 300}]
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'list_instructions', side_effect=read), \
patch.object(dispatcher, 'mode', return_value='ws'):
with books.scope('micro30'):
rows = [self.api.api_instructions(status='DISPATCHED,CONFIRMED', limit=200,
include_archived=False, book_id=b)['data'][0] for b in ('original','micro30')]
self.assertEqual(books.CURRENT.get(), 'micro30')
self.assertEqual([r['qty'] for r in rows], [100,300])
self.assertEqual([r['book_id'] for r in rows], ['original','micro30'])
def test_unmigrated_micro_never_lists_original(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(self.api.pms_repo, 'list_instructions') as read:
result = self.api.api_instructions(status=None, include_archived=False, book_id='micro30')
self.assertEqual(result, {'ok': True, 'data': []})
read.assert_not_called()
def test_read_failure_is_not_successful_empty_and_restores_scope(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'list_instructions', side_effect=RuntimeError('offline')):
result = self.api.api_instructions(status=None, include_archived=False, book_id='micro30')
self.assertFalse(result['ok'])
self.assertEqual(books.CURRENT.get(), 'original')
def test_cancel_uses_selected_book_and_existing_cancel_flow(self):
from app.services import executor
def cancel(iid, reason):
self.assertEqual(iid, 'ROT_test')
self.assertEqual(reason, '页面人工撤销')
return {'ok': True, 'book': books.CURRENT.get(), 'cancel_pending': True}
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(executor, 'cancel_instruction', side_effect=cancel), \
patch.object(self.api.pms_repo, 'insert_op_log') as log:
for book in ('original','micro30'):
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id=book)
self.assertEqual(result['book'], book)
self.assertTrue(result['cancel_pending'])
self.assertEqual(log.call_args.kwargs['params']['book_id'], book)
self.assertEqual(books.CURRENT.get(), 'original')
def test_wrong_book_does_not_fall_back_or_cancel_other_book(self):
from app.services import dispatcher
seen = []
def read(iid):
seen.append(books.CURRENT.get())
return None # 指令在另一个账本,本范围内不存在。
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
patch.object(self.api.pms_repo, 'get_instruction', side_effect=read), \
patch.object(self.api.pms_repo, 'insert_op_log'), \
patch.object(dispatcher, 'cancel') as cancel:
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id='micro30')
self.assertFalse(result['ok'])
self.assertEqual(seen, ['micro30'])
cancel.assert_not_called()
def test_unmigrated_micro_cannot_cancel_original(self):
from app.services import executor
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(executor, 'cancel_instruction') as cancel, \
patch.object(self.api.pms_repo, 'insert_op_log'):
result = self.api.api_cancel_instruction('ROT_test', payload={}, book_id='micro30')
self.assertFalse(result['ok'])
cancel.assert_not_called()
if __name__ == '__main__':
unittest.main()