feat(strategy_manager): 添加策略自动启动的白名单管理

实现全面的白名单管理系统,支持策略自动启动:

- 添加 WhitelistManager 类用于持久化白名单配置存储
- 将白名单功能集成到 StrategyManager 核心模块
- 添加用于白名单 CRUD 操作的 REST API 端点
- 通过 start.py 创建用于白名单管理的 CLI 命令
- 更新前端 UI,添加白名单状态指示器和批量操作功能
- 实现每日 08:58 的自动启动调度
- 为白名单操作添加配置验证和日志记录

同时添加项目文档:
- 代码格式规则(缩进、行长度、导入、命名)
- 文件、变量、常量、函数、类的命名规范
- 受限制文件和目录的保护规则
This commit is contained in:
2026-01-26 01:21:46 +08:00
parent 1b5021d640
commit c0d996f39b
11 changed files with 1952 additions and 99 deletions

View File

@@ -14,10 +14,23 @@
<style>
body { font-family: 'Inter', sans-serif; background-color: #f5f7fa; margin: 0; }
#app { padding: 20px; max-width: 1200px; margin: 0 auto; }
#app { padding: 20px; max-width: 1400px; margin: 0 auto; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.log-container { background: #1e1e1e; padding: 15px; border-radius: 4px; height: 400px; overflow: auto; font-family: monospace; font-size: 12px; color: #ddd; }
.log-line { margin: 2px 0; border-bottom: 1px solid #333; padding-bottom: 2px; }
/* 白名单状态标签 */
.whitelist-tag { cursor: pointer; }
.whitelist-tag:hover { opacity: 0.8; }
/* 统计卡片 */
.stats-row { display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; }
.stat-card { flex: 1; min-width: 150px; background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
.stat-card h4 { margin: 0 0 8px 0; font-size: 13px; color: #666; font-weight: normal; }
.stat-card .value { font-size: 28px; font-weight: bold; color: #333; }
.stat-card.running .value { color: #27ae60; }
.stat-card.stopped .value { color: #e74c3c; }
.stat-card.whitelist .value { color: #9b59b6; }
</style>
</head>
<body>
@@ -33,89 +46,173 @@
</div>
<script>
const { createApp, ref, onMounted, onUnmounted, watch } = Vue;
const { createApp, ref, onMounted, onUnmounted, watch, computed } = Vue;
const naive = window.naive;
// --- 主组件逻辑 ---
const MainLayout = {
template: `
<div class="header">
<h2 style="margin:0; color: #333;">📈 量化策略控制台</h2>
<n-space align="center">
<!-- [核心修改] 1. 显示 Git 版本信息 -->
<n-tag :bordered="false" type="default" size="small">
📦 Version: {{ gitInfo }}
</n-tag>
<div>
<div class="header">
<h2 style="margin:0; color: #333;">📈 量化策略控制台</h2>
<n-space align="center">
<!-- Git 版本信息 -->
<n-tag :bordered="false" type="default" size="small">
📦 Version: {{ gitInfo }}
</n-tag>
<!-- 刷新频率选择器 -->
<n-select
v-model:value="refreshInterval"
:options="intervalOptions"
size="small"
style="width: 130px"
></n-select>
<!-- 刷新频率选择器 -->
<n-select
v-model:value="refreshInterval"
:options="intervalOptions"
size="small"
style="width: 130px"
></n-select>
<!-- 手动刷新按钮 -->
<n-button type="primary" size="small" @click="fetchStatus" :loading="loading">
刷新状态
</n-button>
<!-- 手动刷新按钮 -->
<n-button type="primary" size="small" @click="fetchStatus" :loading="loading">
刷新状态
</n-button>
<n-tag type="info" size="small">更新于: {{ lastUpdated }}</n-tag>
</n-space>
</div>
<n-card title="策略列表" hoverable>
<n-table :single-line="false" striped>
<thead>
<tr>
<th>策略标识</th>
<th>策略名称</th>
<th>运行状态</th>
<th>PID</th>
<th>运行时长</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(info, key) in strategies" :key="key">
<td><strong>{{ key }}</strong></td>
<td>{{ info.config.strategy_name }} <br><small style="color:#999">{{ info.symbol }}</small></td>
<td>
<n-tag :type="info.status === 'running' ? 'success' : 'error'" size="small">
{{ info.status === 'running' ? '运行中' : '已停止' }}
</n-tag>
</td>
<td>{{ info.pid || '-' }}</td>
<td>{{ info.uptime || '-' }}</td>
<td>
<n-space>
<n-button v-if="info.status === 'stopped'" type="success" size="small" ghost @click="handleAction(key, 'start')">启动</n-button>
<n-button v-if="info.status === 'running'" type="error" size="small" ghost @click="handleAction(key, 'stop')">停止</n-button>
<n-button v-if="info.status === 'running'" type="warning" size="small" ghost @click="handleAction(key, 'restart')">重启</n-button>
<n-button size="small" @click="viewLogs(key)">日志</n-button>
</n-space>
</td>
</tr>
<tr v-if="Object.keys(strategies).length === 0">
<td colspan="6" style="text-align: center; padding: 30px; color: #999;">暂无策略</td>
</tr>
</tbody>
</n-table>
</n-card>
<!-- 日志弹窗 -->
<n-modal v-model:show="showLogModal" style="width: 800px;" preset="card" :title="'📜 实时日志: ' + currentLogKey">
<div class="log-container" id="logBox">
<div v-if="logLoading" style="text-align:center; padding:20px;"><n-spin size="medium" /></div>
<div v-else v-for="(line, index) in logLines" :key="index" class="log-line">{{ line }}</div>
</div>
<template #footer>
<n-space justify="end">
<n-button size="small" @click="fetchLogs(currentLogKey)">刷新</n-button>
<n-button size="small" @click="showLogModal = false">关闭</n-button>
<n-tag type="info" size="small">更新于: {{ lastUpdated }}</n-tag>
</n-space>
</template>
</n-modal>
</div>
<!-- 统计卡片 -->
<div class="stats-row">
<div class="stat-card">
<h4>策略总数</h4>
<div class="value">{{ Object.keys(strategies).length }}</div>
</div>
<div class="stat-card running">
<h4>运行中</h4>
<div class="value">{{ runningCount }}</div>
</div>
<div class="stat-card stopped">
<h4>已停止</h4>
<div class="value">{{ stoppedCount }}</div>
</div>
<div class="stat-card whitelist">
<h4>白名单策略</h4>
<div class="value">{{ whitelistCount }}</div>
</div>
</div>
<!-- 白名单管理工具栏 -->
<n-card title="🛠️ 批量操作" hoverable style="margin-bottom: 20px;">
<n-space wrap>
<n-button type="success" size="small" @click="batchStart" :disabled="selectedKeys.length === 0">
启动选中
</n-button>
<n-button type="error" size="small" @click="batchStop" :disabled="selectedKeys.length === 0">
停止选中
</n-button>
<n-button type="warning" size="small" @click="batchRestart" :disabled="selectedKeys.length === 0">
重启选中
</n-button>
<n-divider vertical />
<n-button type="primary" size="small" @click="batchAddToWhitelist" :disabled="selectedKeys.length === 0">
添加到白名单
</n-button>
<n-button type="info" size="small" @click="batchRemoveFromWhitelist" :disabled="selectedKeys.length === 0">
从白名单移除
</n-button>
<n-button type="success" size="small" @click="batchEnableInWhitelist" :disabled="selectedKeys.length === 0">
启用白名单
</n-button>
<n-button type="warning" size="small" @click="batchDisableInWhitelist" :disabled="selectedKeys.length === 0">
禁用白名单
</n-button>
<n-divider vertical />
<n-button type="warning" size="small" @click="triggerAutoStart">
🚀 手动触发自动启动
</n-button>
<n-tag type="info" size="small">
今日已自动启动: {{ whitelistAutoStarted ? '是' : '否' }}
</n-tag>
</n-space>
</n-card>
<!-- 策略列表 -->
<n-card title="📋 策略列表" hoverable>
<template #header-extra>
<n-space>
<n-button text @click="selectAll" size="small">全选</n-button>
<n-button text @click="clearSelection" size="small">清空</n-button>
</n-space>
</template>
<n-table :single-line="false" striped>
<thead>
<tr>
<th style="width: 40px;">
<n-checkbox :checked="allSelected" :indeterminate="partialSelected" @update:checked="toggleSelectAll" />
</th>
<th>策略标识</th>
<th>策略名称</th>
<th>运行状态</th>
<th>白名单</th>
<th>白名单状态</th>
<th>PID</th>
<th>运行时长</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(info, key) in strategies" :key="key" :class="{ 'n-data-table-tr--selected': selectedKeys.includes(key) }">
<td>
<n-checkbox :checked="selectedKeys.includes(key)" @update:checked="toggleSelect(key)" />
</td>
<td><strong>{{ key }}</strong></td>
<td>{{ info.config.name }} <br><small style="color:#999">{{ info.symbol }}</small></td>
<td>
<n-tag :type="info.status === 'running' ? 'success' : 'error'" size="small">
{{ info.status === 'running' ? '运行中' : '已停止' }}
</n-tag>
</td>
<td>
<n-tag :type="info.in_whitelist ? 'success' : 'default'" size="small" class="whitelist-tag"
@click="toggleWhitelist(key)">
{{ info.in_whitelist ? '✓ 在白名单' : '✗ 不在' }}
</n-tag>
</td>
<td>
<n-tag v-if="info.in_whitelist" :type="info.whitelist_enabled ? 'success' : 'warning'" size="small">
{{ info.whitelist_enabled ? '启用' : '禁用' }}
</n-tag>
<span v-else style="color: #999;">-</span>
</td>
<td>{{ info.pid || '-' }}</td>
<td>{{ info.uptime || '-' }}</td>
<td>
<n-space>
<n-button v-if="info.status === 'stopped'" type="success" size="small" ghost @click="handleAction(key, 'start')">启动</n-button>
<n-button v-if="info.status === 'running'" type="error" size="small" ghost @click="handleAction(key, 'stop')">停止</n-button>
<n-button v-if="info.status === 'running'" type="warning" size="small" ghost @click="handleAction(key, 'restart')">重启</n-button>
<n-button size="small" @click="viewLogs(key)">日志</n-button>
</n-space>
</td>
</tr>
<tr v-if="Object.keys(strategies).length === 0">
<td colspan="9" style="text-align: center; padding: 30px; color: #999;">暂无策略</td>
</tr>
</tbody>
</n-table>
</n-card>
<!-- 日志弹窗 -->
<n-modal v-model:show="showLogModal" style="width: 900px;" preset="card" :title="'📜 实时日志: ' + currentLogKey">
<div class="log-container" id="logBox">
<div v-if="logLoading" style="text-align:center; padding:20px;"><n-spin size="medium" /></div>
<div v-else v-for="(line, index) in logLines" :key="index" class="log-line" :class="getLogClass(line)">{{ line }}</div>
</div>
<template #footer>
<n-space justify="end">
<n-button size="small" @click="fetchLogs(currentLogKey)">刷新</n-button>
<n-button size="small" @click="showLogModal = false">关闭</n-button>
</n-space>
</template>
</n-modal>
</div>
`,
setup() {
const message = naive.useMessage();
@@ -124,10 +221,12 @@
const strategies = ref({});
const loading = ref(false);
const lastUpdated = ref('-');
// [核心修改] 2. 为 Git 信息创建一个 ref
const gitInfo = ref('Loading...');
// 白名单相关
const whitelistAutoStarted = ref(false);
const selectedKeys = ref([]);
const refreshInterval = ref(0);
const intervalOptions = [
{ label: '✋ 仅手动', value: 0 },
@@ -137,6 +236,14 @@
];
let timer = null;
// 计算属性
const runningCount = computed(() => Object.values(strategies.value).filter(s => s.status === 'running').length);
const stoppedCount = computed(() => Object.values(strategies.value).filter(s => s.status === 'stopped').length);
const whitelistCount = computed(() => Object.values(strategies.value).filter(s => s.in_whitelist).length);
const allSelected = computed(() => selectedKeys.value.length > 0 && selectedKeys.value.length === Object.keys(strategies.value).length);
const partialSelected = computed(() => selectedKeys.value.length > 0 && selectedKeys.value.length < Object.keys(strategies.value).length);
const fetchStatus = async () => {
if (loading.value) return;
loading.value = true;
@@ -145,11 +252,12 @@
if (!res.ok) throw new Error("Error");
const data = await res.json();
strategies.value = data.strategies;
// [核心修改] 3. 更新 Git 信息
gitInfo.value = data.git_info || 'N/A';
whitelistAutoStarted.value = !data.whitelist_auto_start_today;
lastUpdated.value = new Date().toLocaleTimeString();
// 清理已删除策略的选中状态
selectedKeys.value = selectedKeys.value.filter(k => k in strategies.value);
} catch (e) {
message.error("连接服务器失败");
} finally {
@@ -174,6 +282,33 @@
}
});
// 选择操作
const toggleSelect = (key) => {
const idx = selectedKeys.value.indexOf(key);
if (idx >= 0) {
selectedKeys.value.splice(idx, 1);
} else {
selectedKeys.value.push(key);
}
};
const toggleSelectAll = (checked) => {
if (checked) {
selectedKeys.value = Object.keys(strategies.value);
} else {
selectedKeys.value = [];
}
};
const selectAll = () => {
selectedKeys.value = Object.keys(strategies.value);
};
const clearSelection = () => {
selectedKeys.value = [];
};
// 策略操作
const handleAction = (name, action) => {
const map = { start: '启动', stop: '停止', restart: '重启' };
dialog.warning({
@@ -195,24 +330,179 @@
});
};
// 批量操作
const batchAction = async (action, apiEndpoint) => {
const results = [];
for (const name of selectedKeys.value) {
try {
const res = await fetch(`/api/${apiEndpoint}/${name}/${action}`, { method: 'POST' });
if (res.ok) {
results.push(name);
}
} catch (e) {
console.error(`操作失败: ${name}`, e);
}
}
if (results.length > 0) {
message.success(`成功操作 ${results.length} 个策略`);
fetchStatus();
} else {
message.warning("没有成功的操作");
}
};
const batchStart = () => batchAction('start', 'api/strategy');
const batchStop = () => batchAction('stop', 'api/strategy');
const batchRestart = () => batchAction('restart', 'api/strategy');
// 白名单操作
const batchAddToWhitelist = async () => {
const results = [];
for (const name of selectedKeys.value) {
try {
const res = await fetch(`/api/whitelist/${name}/add`, { method: 'POST' });
if (res.ok) results.push(name);
} catch (e) { console.error(e); }
}
if (results.length > 0) {
message.success(`已添加到白名单: ${results.join(', ')}`);
fetchStatus();
} else {
message.warning("没有成功的操作");
}
};
const batchRemoveFromWhitelist = async () => {
const results = [];
for (const name of selectedKeys.value) {
try {
const res = await fetch(`/api/whitelist/${name}/remove`, { method: 'POST' });
if (res.ok) results.push(name);
} catch (e) { console.error(e); }
}
if (results.length > 0) {
message.success(`已从白名单移除: ${results.join(', ')}`);
fetchStatus();
} else {
message.warning("没有成功的操作");
}
};
const batchEnableInWhitelist = async () => {
const results = [];
for (const name of selectedKeys.value) {
try {
const res = await fetch(`/api/whitelist/${name}/enable`, { method: 'POST' });
if (res.ok) results.push(name);
} catch (e) { console.error(e); }
}
if (results.length > 0) {
message.success(`已启用: ${results.join(', ')}`);
fetchStatus();
} else {
message.warning("没有成功的操作");
}
};
const batchDisableInWhitelist = async () => {
const results = [];
for (const name of selectedKeys.value) {
try {
const res = await fetch(`/api/whitelist/${name}/disable`, { method: 'POST' });
if (res.ok) results.push(name);
} catch (e) { console.error(e); }
}
if (results.length > 0) {
message.success(`已禁用: ${results.join(', ')}`);
fetchStatus();
} else {
message.warning("没有成功的操作");
}
};
const toggleWhitelist = async (name) => {
const info = strategies.value[name];
if (!info) return;
try {
if (info.in_whitelist) {
// 在白名单中,询问是否移除
dialog.warning({
title: '白名单操作',
content: `${name} 已在白名单中,是否移除?`,
positiveText: '移除',
negativeText: '取消',
onPositiveClick: async () => {
const res = await fetch(`/api/whitelist/${name}/remove`, { method: 'POST' });
if (res.ok) {
message.success("已从白名单移除");
fetchStatus();
}
}
});
} else {
// 不在白名单中,询问是否添加
dialog.info({
title: '白名单操作',
content: `${name} 添加到白名单?`,
positiveText: '添加',
negativeText: '取消',
onPositiveClick: async () => {
const res = await fetch(`/api/whitelist/${name}/add`, { method: 'POST' });
if (res.ok) {
message.success("已添加到白名单");
fetchStatus();
}
}
});
}
} catch (e) {
message.error("操作失败");
}
};
const triggerAutoStart = async () => {
try {
const res = await fetch('/api/whitelist/auto-start', { method: 'POST' });
const data = await res.json();
if (data.success) {
message.success(`自动启动完成: 成功 ${data.success_count}, 失败 ${data.fail_count}`);
fetchStatus();
} else {
message.warning("今天已执行过或无需启动");
}
} catch (e) {
message.error("自动启动失败");
}
};
// 日志相关
const showLogModal = ref(false);
const currentLogKey = ref('');
const logLines = ref([]);
const logLoading = ref(false);
const getLogClass = (line) => {
if (line.includes('[ERROR]') || line.includes('❌')) return 'error';
if (line.includes('[WARNING]') || line.includes('⚠️')) return 'warning';
if (line.includes('[INFO]') || line.includes('✅')) return 'info';
if (line.includes('成功') || line.includes('success')) return 'success';
return '';
};
const fetchLogs = async (name) => {
logLoading.value = true;
try {
const res = await fetch(`/api/logs/${name}?lines=100`);
const data = await res.json();
logLines.value = data.lines;
logLines.value = data.lines || [];
setTimeout(() => {
const el = document.getElementById('logBox');
if(el) el.scrollTop = el.scrollHeight;
}, 100);
} catch(e) { message.error("日志获取失败"); }
finally { logLoading.value = false; }
}
};
const viewLogs = (name) => {
currentLogKey.value = name;
@@ -230,11 +520,21 @@
});
return {
strategies, loading, lastUpdated,
gitInfo, // [核心修改] 4. 将 gitInfo 暴露给模板
strategies, loading, lastUpdated, gitInfo,
refreshInterval, intervalOptions,
showLogModal, currentLogKey, logLines, logLoading,
fetchStatus, handleAction, viewLogs, fetchLogs
fetchStatus, handleAction, viewLogs, fetchLogs, getLogClass,
// 白名单
whitelistAutoStarted,
selectedKeys,
runningCount, stoppedCount, whitelistCount,
allSelected, partialSelected,
toggleSelect, toggleSelectAll, selectAll, clearSelection,
batchStart, batchStop, batchRestart,
batchAddToWhitelist, batchRemoveFromWhitelist,
batchEnableInWhitelist, batchDisableInWhitelist,
toggleWhitelist, triggerAutoStart
};
}
};
@@ -256,4 +556,4 @@
</script>
</body>
</html>
</html>