feat: 新增阶梯提醒与请求失败告警规则

- 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长提醒一次并更新基准;
  方向支持每上涨/每下跌/双向,步长可填具体变动值或百分比,基准落盘 rule-state.json
- 请求失败告警:某品种连续抓取失败达到设定次数时提醒一次;抓取成功即清零,
  下一波连续失败可重新触发;支持「持续失败每 N 秒重复提醒」与生效时段
- 配置归一化接受 ladder / failure 类型,失败告警的 value 按次数取整、冷却固定为 0
- 规则弹窗补充两类规则的字段显隐、方向文案、预览与说明;重复间隔标签按类型切换
- 规则列表新增橙色「阶梯」、红色「失败告警」标签,失败告警不展示冷却
- README 补阶梯提醒与请求失败告警章节,规则类型更新为六类
This commit is contained in:
2026-11-24 18:01:49 +08:00
parent eb9b6d534f
commit 9e88456f73
7 changed files with 309 additions and 34 deletions
+13 -1
View File
@@ -69,7 +69,7 @@ npm start
## 4. 提醒规则怎么写
四种类型:
六种类型:
- **价格阈值**:`价格 ≥ 阈值`(上破)或 `价格 ≤ 阈值`(下破)。
- **涨跌幅**:涨幅 / 跌幅 / 涨跌幅绝对值 ≥ 阈值,**阈值可以按百分比,也可以直接写具体变动值**:
@@ -82,11 +82,23 @@ npm start
本机按品种保留最近 72 小时、最多 2400 个点,并定期写入 `data/history.json`,重启后接着算。
- **价差提醒**:两个同单位品种的价差 —— 绝对价差(元/克)或相对价差(%),
方向可选「绝对差」「前者高于后者」「后者高于前者」。典型用法:浙商积存金与黄金T+D 的价差走阔。
- **阶梯提醒**:以「上次提醒时的价格」为基准,每偏离一个步长就提醒一次,随后基准更新为当前价。
- 步长口径:「具体变动值(元/克)」填 2 就是「每涨/跌 2 元/克提醒一次」;也可按百分比(填 0.5 即 0.5%);
- 方向:「每上涨一个步长」「每下跌一个步长」「每涨/跌一个步长」;
- 例(步长 2 元、每上涨):780 建基准(不提醒)→ 782.5 提醒一次(基准变 782.5)→ 784.7 再提醒;
- 价格回落不提醒、也不重置基准;冷却时间依然生效(默认切到阶梯时提示改成 60 秒),避免来回震荡刷屏;
- 基准价会写进 `data/rule-state.json`,重启后接着用;第一次见到该品种只用当前价建基准,不打扰。
- **定时提醒**:到点按当时的行情发一条通知,不看价格条件。适合「每天 09:00 报一下开盘价」「工作日 15:30 收盘播报」。
- 提醒时刻:`09:00, 15:30`(24 小时制,逗号分隔,最多 12 个,会自动去重排序);
- 重复方式:「每天」「工作日(周一至周五)」「每周指定几天」(勾选周一~周日,至少选一天);
- 同一时刻每天只响一次(去重状态存在 `data/rule-state.json`,重启后不会重复);
- 程序当时没运行的时刻不会补发;到点时刻有 2 分钟容错窗口,抓取抖动不会漏掉整分钟。
- **请求失败告警**:盯的是「数据源还能不能取到价」,和价格高低无关。
- 「连续失败次数」填 3,就是该品种连着 3 次抓取失败时提醒一次(默认 3 次,最小 1 次);
- 失败计数在抓取成功时清零:恢复后的下一波连续失败,还会重新提醒;
- 「持续失败时每 N 秒重复提醒」填 600,则数据源一直挂着一整天时每 10 分钟再提醒一次;填 0 只在达到次数时响一次;
- 这条规则没有「冷却时间」,节流完全交给上面的重复间隔;
- 提醒正文带品种、数据源、连续失败次数、最近一次报错、最后一次成功时间,方便判断是断网还是接口变了。
每条规则还可以限定**生效时段**(如 `09:00-11:30`、`21:00-23:00`,支持跨零点写 `22:00-02:00`,留空表示全天)。
时段外不评估、不发提醒;进入时段后若条件成立,会正常提醒一次。
+98 -18
View File
@@ -439,6 +439,15 @@ function ruleConditionText(rule) {
const absText = rule.direction === 'both' ? '绝对值' : '';
return `${left.name} ${scope}${dirText} ${absText} ≥ ${valueText}${rangeSuffix}`.replace(' ', ' ');
}
if (rule.type === 'ladder') {
// 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长提醒一次
const isAmount = rule.changeBasis === 'amount';
const valueText = isAmount
? `${fmt(Math.abs(rule.value), left.digits)} ${left.unit}`
: `${Math.abs(rule.value).toFixed(2)}%`;
const dirText = rule.direction === 'down' ? '每下跌' : rule.direction === 'both' ? '每涨/跌' : '每上涨';
return `${left.name} ${dirText} ${valueText} 提醒一次(基价随提醒更新)${rangeSuffix}`;
}
if (rule.type === 'schedule') {
// 定时提醒:重复方式 + 时刻,必要时带上每周哪几天
const repeatText = rule.scheduleRepeat === 'weekday' ? '工作日' : rule.scheduleRepeat === 'weekly' ? '每周' : '每天';
@@ -448,6 +457,12 @@ function ruleConditionText(rule) {
const times = (rule.scheduleTimes || []).join('、') || '未设置时刻';
return `${left.name} ${repeatText}${weekText} ${times} 定时提醒${rangeSuffix}`;
}
if (rule.type === 'failure') {
// 请求失败告警:连续查询失败多少次就提醒
const times = Math.max(1, Math.round(Number(rule.value) || 3));
const repeat = rule.repeatIntervalSec > 0 ? `,持续失败每 ${rule.repeatIntervalSec} 秒重复提醒` : '';
return `${left.name} 连续查询失败 ${times} 次 提醒一次${repeat}${rangeSuffix}`;
}
if (!right) return '对比品种已删除';
const unitText = rule.mode === 'percent' ? '%' : left.unit;
const dirText = rule.direction === 'above' ? `${left.name} 高于 ${right.name}` : rule.direction === 'below' ? `${right.name} 高于 ${left.name}` : '两者价差';
@@ -475,10 +490,17 @@ function renderRules() {
box.innerHTML = list.map((rule) => {
const channels = (rule.channels || []).map(channelName).join(' + ');
const typeText = rule.type === 'threshold' ? '价格阈值' : rule.type === 'change' ? '涨跌幅' : rule.type === 'schedule' ? '定时' : '价差';
// 定时提醒按时刻去重,没有冷却/重复的概念,列表里不展示这两项
const typeText = rule.type === 'threshold' ? '价格阈值'
: rule.type === 'change' ? '涨跌幅'
: rule.type === 'schedule' ? '定时'
: rule.type === 'ladder' ? '阶梯'
: rule.type === 'failure' ? '失败告警'
: '价差';
// 定时提醒按时刻去重、失败告警按次数触发,都没有「冷却」概念,列表里只展示重复间隔
const extraText = rule.type === 'schedule'
? ''
: rule.type === 'failure'
? `${rule.repeatIntervalSec > 0 ? ` · 持续失败每 ${rule.repeatIntervalSec}s 重复` : ''}`
: ` · 冷却 ${rule.cooldownSec}s${rule.repeatIntervalSec > 0 ? ` · 每 ${rule.repeatIntervalSec}s 重复` : ''}`;
return `
<div class="rule-item ${rule.enabled ? '' : 'disabled'}" data-id="${esc(rule.id)}">
@@ -876,8 +898,12 @@ async function saveInstrument() {
function syncRuleFields() {
const type = document.getElementById('ruleType').value;
const isSchedule = type === 'schedule';
/** 请求失败告警按「连续失败次数」触发,不看价格也不看方向 */
const isFailure = type === 'failure';
/** 需要「口径」下拉的类型:涨跌幅看百分比/具体值;阶梯看步长的单位 */
const hasBasis = type === 'change' || type === 'ladder';
const dirSelect = document.getElementById('ruleDirection');
// 涨跌幅的阈值口径:percent 按百分比,amount 按具体价格变动值
// 涨跌幅 / 阶梯的阈值口径:percent 按百分比,amount 按具体价格变动值
const isAmount = document.getElementById('ruleBasis').value === 'amount';
const unit = unitOf(document.getElementById('ruleInstrument').value);
const changeUnitText = isAmount ? unit : '%';
@@ -885,6 +911,10 @@ function syncRuleFields() {
? [['above', '上破(价格 ≥ 阈值)'], ['below', '下破(价格 ≤ 阈值)']]
: type === 'change'
? [['up', `涨幅 ≥ 阈值(${changeUnitText})`], ['down', `跌幅 ≥ 阈值(${changeUnitText})`], ['both', `涨跌幅绝对值 ≥ 阈值(${changeUnitText})`]]
: type === 'ladder'
? [['up', '每上涨一个步长 提醒一次'], ['down', '每下跌一个步长 提醒一次'], ['both', '每涨/跌一个步长 提醒一次']]
: type === 'failure'
? [['abs', '连续查询失败达到次数即提醒']]
: [['abs', '绝对价差 ≥ 阈值'], ['above', '前者高于后者 ≥ 阈值'], ['below', '后者高于前者 ≥ 阈值']];
const current = dirSelect.value;
@@ -893,14 +923,20 @@ function syncRuleFields() {
document.getElementById('ruleCompareField').hidden = type !== 'spread';
document.getElementById('ruleModeField').hidden = type !== 'spread';
document.getElementById('ruleBasisField').hidden = type !== 'change';
document.getElementById('ruleBasisField').hidden = !hasBasis;
document.getElementById('ruleWindowField').hidden = type !== 'change';
// 定时提醒不看价格条件:方向和阈值、统计区间、生效时段、冷却/重复都收起
document.getElementById('ruleDirectionField').hidden = isSchedule;
// 定时提醒 / 请求失败告警都不看价格方向
document.getElementById('ruleDirectionField').hidden = isSchedule || isFailure;
document.getElementById('ruleValueField').hidden = isSchedule;
document.getElementById('ruleActiveRangeField').hidden = isSchedule;
document.getElementById('ruleCooldownField').hidden = isSchedule;
document.getElementById('ruleRepeatField').hidden = isSchedule;
// 请求失败告警没有「冷却」概念(次数本身就是节流),冷却字段收起
document.getElementById('ruleCooldownField').hidden = isSchedule || isFailure;
// 阶梯提醒按步长计算,没有「持续满足重复提醒」的概念(重复字段收起)
document.getElementById('ruleRepeatField').hidden = isSchedule || type === 'ladder';
// 重复间隔文案:价格类规则是「持续满足」,失败告警是「持续失败」
document.getElementById('ruleRepeatLabel').textContent = isFailure
? '持续失败时每 N 秒重复提醒(0 只提醒一次)'
: '持续满足时每 N 秒重复提醒(0 不重复)';
// 定时提醒自己的字段:时刻、重复方式、每周星期
document.getElementById('ruleScheduleTimesField').hidden = !isSchedule;
document.getElementById('ruleScheduleRepeatField').hidden = !isSchedule;
@@ -908,15 +944,23 @@ function syncRuleFields() {
syncWindowCustom();
document.getElementById('ruleValueLabel').textContent = type === 'threshold'
? '阈值(价格)'
: type === 'change' ? (isAmount ? `阈值(${unit})` : '阈值(百分比 %)') : '阈值(价差)';
// 阈值输入框的示例值按当前口径切换,避免涨跌幅里还显示价格的 800
document.getElementById('ruleValue').placeholder = type === 'threshold'
: type === 'change' ? (isAmount ? `阈值(${unit})` : '阈值(百分比 %)')
: type === 'ladder' ? (isAmount ? `阶梯步长(${unit})` : '阶梯步长(%)')
: type === 'failure' ? '连续失败次数(次)'
: '阈值(价差)';
// 阈值输入框的示例值、步长按当前口径切换(次数是整数,价格类允许 3 位小数)
const valueInput = document.getElementById('ruleValue');
valueInput.step = isFailure ? '1' : '0.001';
valueInput.placeholder = type === 'threshold'
? '800'
: type === 'change' ? (isAmount ? '3' : '0.5')
: hasBasis ? (isAmount ? '2' : '0.5')
: isFailure ? '3'
: (document.getElementById('ruleMode').value === 'percent' ? '1' : '100');
// 统计区间 / 定时提醒的说明各管各的
// 各类型的说明文案各管各的
document.getElementById('ruleWindowHint').hidden = type !== 'change';
document.getElementById('ruleScheduleHint').hidden = !isSchedule;
document.getElementById('ruleLadderHint').hidden = type !== 'ladder';
document.getElementById('ruleFailureHint').hidden = !isFailure;
updateRuleSummary();
}
@@ -1000,6 +1044,8 @@ function updateRuleSummary() {
direction: document.getElementById('ruleDirection').value,
value: Number(document.getElementById('ruleValue').value) || 0,
cooldownSec: Number(document.getElementById('ruleCooldown').value) || 0,
// 失败告警的重复间隔也进预览文案
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
windowSec: readWindowSec(),
activeRange: readActiveRange(),
scheduleTimes: readScheduleTimes(),
@@ -1013,6 +1059,14 @@ function updateRuleSummary() {
: '预览:填写提醒时刻后显示条件预览';
return;
}
// 失败告警没有阈值,按「次数」生成预览
if (type === 'failure') {
const times = Math.round(Number(document.getElementById('ruleValue').value));
document.getElementById('ruleSummary').textContent = Number.isFinite(times) && times >= 1
? `预览:${ruleConditionText(draft)}`
: '预览:填写连续失败次数后显示条件预览';
return;
}
const value = Number(document.getElementById('ruleValue').value);
if (!Number.isFinite(value) || value === 0) {
document.getElementById('ruleSummary').textContent = '预览:填写阈值后显示条件预览';
@@ -1119,6 +1173,12 @@ async function saveRule() {
setResult('ruleResult', '请至少勾选一个星期几', false);
return;
}
} else if (type === 'failure') {
// 失败次数必须是 ≥1 的整数
if (!Number.isFinite(value) || value < 1) {
setResult('ruleResult', '请填写连续失败次数(至少 1 次,常用 3 次)', false);
return;
}
} else if (!Number.isFinite(value) || (type !== 'threshold' && value === 0)) {
setResult('ruleResult', '请填写有效的阈值', false);
return;
@@ -1156,6 +1216,8 @@ async function saveRule() {
mode: document.getElementById('ruleMode').value,
changeBasis: document.getElementById('ruleBasis').value,
windowSec, activeRange,
// 失败告警的名称里也带上重复间隔,避免多条同类规则名字撞车
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
scheduleTimes,
scheduleRepeat: document.getElementById('ruleScheduleRepeat').value,
scheduleWeekdays: readScheduleWeekdays(),
@@ -1164,11 +1226,12 @@ async function saveRule() {
instrumentId,
compareInstrumentId: type === 'spread' ? compareInstrumentId : '',
mode: document.getElementById('ruleMode').value,
// 涨跌幅阈值口径:percent(百分比)/ amount(具体变动值)
changeBasis: type === 'change' ? document.getElementById('ruleBasis').value : 'percent',
// 涨跌幅 / 阶梯的阈值口径:percent(百分比)/ amount(具体变动值)
changeBasis: (type === 'change' || type === 'ladder') ? document.getElementById('ruleBasis').value : 'percent',
direction: type === 'schedule' ? 'abs' : direction,
value: type === 'schedule' ? 0 : value,
cooldownSec: Number(document.getElementById('ruleCooldown').value) || 1800,
// 失败告警不用冷却,冷却置 0,节流交给「持续失败重复间隔」
cooldownSec: type === 'failure' ? 0 : (Number(document.getElementById('ruleCooldown').value) || 1800),
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
windowSec,
activeRange,
@@ -1283,7 +1346,22 @@ function bindEvents() {
// 规则
document.getElementById('btnAddRule').addEventListener('click', () => openRuleModal(null));
document.getElementById('ruleType').addEventListener('change', syncRuleFields);
document.getElementById('ruleType').addEventListener('change', () => {
const type = document.getElementById('ruleType').value;
// 切到阶梯提醒且步长还空着时,默认按「具体值(元/克)」口径,符合「每涨 2 元提醒」的直觉
if (type === 'ladder' && !document.getElementById('ruleValue').value) {
document.getElementById('ruleBasis').value = 'amount';
}
// 阶梯提醒本来就按步长逐档提醒,默认的 30 分钟冷却太长,切过去时改回 60 秒
if (type === 'ladder' && document.getElementById('ruleCooldown').value === '1800') {
document.getElementById('ruleCooldown').value = '60';
}
// 切到请求失败告警且次数还空着时,先给个常见的「连续 3 次」占位
if (type === 'failure' && !document.getElementById('ruleValue').value) {
document.getElementById('ruleValue').value = '3';
}
syncRuleFields();
});
document.getElementById('ruleInstrument').addEventListener('change', syncRuleFields);
document.getElementById('ruleCompare').addEventListener('change', updateRuleSummary);
document.getElementById('ruleMode').addEventListener('change', syncRuleFields);
@@ -1291,6 +1369,8 @@ function bindEvents() {
document.getElementById('ruleDirection').addEventListener('change', updateRuleSummary);
document.getElementById('ruleValue').addEventListener('input', updateRuleSummary);
document.getElementById('ruleCooldown').addEventListener('input', updateRuleSummary);
// 失败告警的重复间隔改动也要立刻反映到预览文案
document.getElementById('ruleRepeat').addEventListener('input', updateRuleSummary);
// 统计区间与生效时段:改动后同步字段显隐和预览
document.getElementById('ruleWindow').addEventListener('change', () => {
syncWindowCustom();
@@ -1444,7 +1524,7 @@ const TABS = ['market', 'rules', 'channels', 'alerts'];
function buildImportSummary(data, file) {
const instruments = Array.isArray(data.instruments) ? data.instruments : [];
const rules = Array.isArray(data.rules) ? data.rules : [];
const typeNames = { threshold: '价格阈值', change: '涨跌幅', spread: '价差', schedule: '定时' };
const typeNames = { threshold: '价格阈值', change: '涨跌幅', ladder: '阶梯', spread: '价差', schedule: '定时', failure: '失败告警' };
const ruleCounts = {};
rules.forEach((r) => {
const key = typeNames[r.type] || String(r.type || '未知');
+8 -4
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>金价提醒 · Gold Price Watcher</title>
<link rel="stylesheet" href="/styles.css?v=20261124s" />
<link rel="stylesheet" href="/styles.css?v=20261124w" />
</head>
<body>
<header class="topbar">
@@ -50,7 +50,7 @@
<div class="section-head">
<div>
<h2>提醒规则</h2>
<p class="hint">支持价格阈值、涨跌幅(可指定统计区间,如「近 10 分钟涨 0.5%」)、两个品种之间的价差、定时提醒四类规则;价格类规则还能限定生效时段并按冷却时间防轰炸,定时提醒按时刻去重。</p>
<p class="hint">支持价格阈值、涨跌幅(可指定统计区间,如「近 10 分钟涨 0.5%」)、阶梯提醒(每涨/跌一个步长提醒一次)、两个品种之间的价差、定时提醒、请求失败告警(连续查询失败 N 次)六类规则;价格类规则还能限定生效时段并按冷却时间防轰炸,定时提醒按时刻去重。</p>
</div>
<button class="btn primary" id="btnAddRule">+ 新建规则</button>
</div>
@@ -281,8 +281,10 @@
<select id="ruleType">
<option value="threshold">价格阈值</option>
<option value="change">涨跌幅</option>
<option value="ladder">阶梯提醒</option>
<option value="spread">价差提醒</option>
<option value="schedule">定时提醒</option>
<option value="failure">请求失败告警</option>
</select>
</label>
<label class="field"><span>监控品种</span><select id="ruleInstrument"></select></label>
@@ -333,7 +335,7 @@
</div>
</label>
<label class="field" id="ruleCooldownField"><span>冷却时间(秒)</span><input type="number" id="ruleCooldown" min="30" step="30" value="1800" /></label>
<label class="field" id="ruleRepeatField"><span>持续满足时每 N 秒重复提醒(0 不重复)</span><input type="number" id="ruleRepeat" min="0" step="60" value="0" /></label>
<label class="field" id="ruleRepeatField"><span id="ruleRepeatLabel">持续满足时每 N 秒重复提醒(0 不重复)</span><input type="number" id="ruleRepeat" min="0" step="60" value="0" /></label>
<!-- 定时提醒专用:到点时刻 + 重复方式 -->
<label class="field wide" id="ruleScheduleTimesField" hidden><span>提醒时刻(24 小时制,多个用逗号分隔,最多 12 个)</span>
<input type="text" id="ruleScheduleTimes" placeholder="09:00, 15:30, 21:00" />
@@ -370,6 +372,8 @@
<p class="hint" id="ruleSummary"></p>
<p class="hint" id="ruleWindowHint">提示:统计区间选「日内」时,涨跌幅相对昨收计算;选「近 N 分钟」时,用本机缓存的行情点回算滚动区间,重启后会接着用已保存的历史。</p>
<p class="hint" id="ruleScheduleHint" hidden>提示:定时提醒会在指定时刻按当时的行情发一条通知,不受价格条件影响;同一时刻每天只响一次,程序当时没运行则不会补发。</p>
<p class="hint" id="ruleLadderHint" hidden>提示:阶梯提醒以「上次提醒时的价格」为基准,价格每偏离一个步长就提醒一次,随后基准更新为当前价。例如步长 2 元/克:782 提醒后基准变 782,涨到 784 再提醒;价格回落不会提醒,也不会重置基准。</p>
<p class="hint" id="ruleFailureHint" hidden>提示:请求失败告警盯的是「数据源还能不能取到价」,与价格高低无关。连续查询失败达到设定次数时提醒一次;一旦某次抓取成功,失败计数清零,下次再连续失败达到次数还会重新提醒。数据源长时间不可用时,可在「持续失败时每 N 秒重复提醒」里填间隔,避免只响一次被忽略。</p>
</div>
<div class="modal-foot">
<span class="test-result" id="ruleResult"></span>
@@ -399,7 +403,7 @@
</div>
<div class="toast-wrap" id="toastWrap"></div>
<script src="/app.js?v=20261124s"></script>
<script src="/app.js?v=20261124w"></script>
</body>
</html>
+4
View File
@@ -349,6 +349,10 @@ main { padding: 22px 28px 60px; max-width: 1320px; margin: 0 auto; }
.tag.spread { color: #6a4b9a; border-color: #e0d4f0; background: #f7f3fc; }
/* 定时提醒:用偏绿的色,和三种价格条件规则区分开 */
.tag.schedule { color: #1f7a5c; border-color: #cfe8dd; background: #f1faf6; }
/* 阶梯提醒:橙色系,和阈值/涨跌幅区分 */
.tag.ladder { color: #a35a12; border-color: #f2ddc4; background: #fdf6ec; }
/* 请求失败告警:红色系,属于异常提示 */
.tag.failure { color: #b23b3b; border-color: #f0cccc; background: #fdf2f2; }
/* 导入配置前的摘要区块 */
.import-summary {
+11 -5
View File
@@ -2,7 +2,7 @@
* 配置存取层。
* 配置全部落在 config/config.json:
* - instruments 监控品种(数据源、刷新频率、单位等)
* - rules 提醒规则(阈值 / 涨跌幅 / 价差)
* - rules 提醒规则(阈值 / 涨跌幅 / 阶梯 / 价差 / 定时 / 请求失败告警)
* - email 邮箱 SMTP 配置
* - desktop Windows 桌面通知开关
* - monitor 全局轮询与静默时段
@@ -181,13 +181,18 @@ function normalizeScheduleTimes(raw) {
}
function normalizeRule(raw, index) {
const type = ['threshold', 'change', 'spread', 'schedule'].includes(raw?.type) ? raw.type : 'threshold';
const type = ['threshold', 'change', 'spread', 'schedule', 'ladder', 'failure'].includes(raw?.type) ? raw.type : 'threshold';
const channels = Array.isArray(raw?.channels)
? raw.channels.filter((c) => CHANNEL_KEYS.includes(c))
: ['desktop'];
const direction = ['above', 'below', 'abs', 'up', 'down', 'both'].includes(raw?.direction)
? raw.direction
: (type === 'threshold' ? 'above' : 'abs');
: (type === 'threshold' ? 'above' : type === 'ladder' ? 'up' : 'abs');
// 请求失败告警的 value 是「连续失败次数」,必须是 1 以上的整数,默认 3 次
const value = type === 'failure'
? Math.round(clampNumber(raw?.value, 3, 1, 500))
: clampNumber(raw?.value, 0, -1e9, 1e9);
return {
id: raw?.id ? String(raw.id) : uid('rule'),
@@ -198,8 +203,9 @@ function normalizeRule(raw, index) {
compareInstrumentId: raw?.compareInstrumentId ? String(raw.compareInstrumentId) : '',
mode: raw?.mode === 'percent' ? 'percent' : 'abs',
direction,
value: clampNumber(raw?.value, 0, -1e9, 1e9),
cooldownSec: Math.round(clampNumber(raw?.cooldownSec, 1800, 30, 86400 * 7)),
value,
// 请求失败告警不看「次数」以外的条件,冷却固定为 0(重复频率交给 repeatIntervalSec)
cooldownSec: type === 'failure' ? 0 : Math.round(clampNumber(raw?.cooldownSec, 1800, 30, 86400 * 7)),
repeatIntervalSec: Math.round(clampNumber(raw?.repeatIntervalSec, 0, 0, 86400)),
// 涨跌幅的统计区间(秒):0 = 日内(相对昨收),>0 = 近 N 秒的滚动窗口
windowSec: Math.round(clampNumber(raw?.windowSec, 0, 0, 43200)),
+168 -3
View File
@@ -120,6 +120,31 @@ class Monitor {
for (const key of [...this.quotes.keys()]) {
if (!ids.has(key)) this.quotes.delete(key);
}
this.pruneRuleStates(cfg);
}
/**
* 清掉已删除规则 / 品种残留的触发状态,避免 rule-state.json 无限增长
* @param {object} cfg 配置
*/
pruneRuleStates(cfg) {
const ruleIds = new Set(cfg.rules.map((r) => r.id));
const instIds = new Set(cfg.instruments.map((i) => i.id));
let changed = false;
for (const key of [...this.ruleStates.keys()]) {
// 定时提醒的去重键由 pruneScheduleStates 按时间清理
if (key.includes('::schedule::')) continue;
const parts = key.split('::');
const ruleId = parts[0];
const instId = parts[parts.length - 1];
// 价差规则的 key 是「规则::spread」,没有品种部分
const keepInst = key.endsWith('::spread') || !instId ? true : instIds.has(instId);
if (!ruleIds.has(ruleId) || !keepInst) {
this.ruleStates.delete(key);
changed = true;
}
}
if (changed) this.persistRuleStates();
}
/**
@@ -187,6 +212,9 @@ class Monitor {
state.updatedAt = nowText();
state.updatedAtMs = now;
this.pushHistory(state, now, quote.price);
// 抓取成功说明「请求失败告警」的条件已经不成立了,把状态归零,
// 这样下一波连续失败还能重新触发提醒
this.resetFailureStates(inst.id);
// 评估与该品种相关的规则
await this.evaluateRules(inst);
@@ -199,6 +227,8 @@ class Monitor {
if (state.errorCount <= 3 || state.errorCount % 20 === 0) {
log.warn(`【${inst.name}】抓取失败(第 ${state.errorCount} 次):${err.message}`);
}
// 抓取失败也要评估「请求失败告警」规则,否则这条规则永远不会响
await this.evaluateFailureRules(inst, state, err);
return state;
} finally {
this.inflight.delete(id);
@@ -333,10 +363,14 @@ class Monitor {
const cfg = this.store.get();
for (const rule of cfg.rules) {
if (!rule.enabled) continue;
// 「请求失败告警」只在抓取失败时评估(见 tick 的 catch 分支),这里跳过
if (rule.type === 'failure') continue;
// 生效时段之外直接跳过("22:00-02:00" 这类跨零点区间也支持)
if (rule.activeRange && !inTimeRange(rule.activeRange)) {
// 时段外不评估,但把状态压成「不满足」:这样进入时段后条件一旦成立,
// 仍会按边沿触发正常提醒,而不是被当成「首次评估」静默掉。
// 阶梯提醒不使用 met 状态(它记录的是基准价),时段外直接跳过即可
if (rule.type === 'ladder') continue;
const key = rule.type === 'spread' ? `${rule.id}::spread` : `${rule.id}::${inst.id}`;
const st = this.ruleStates.get(key);
if (!st) {
@@ -353,6 +387,8 @@ class Monitor {
if (rule.instrumentId === inst.id || rule.compareInstrumentId === inst.id) {
await this.evaluateSpread(rule, cfg);
}
} else if (rule.type === 'ladder') {
if (rule.instrumentId === inst.id) await this.evaluateLadder(rule, inst, cfg);
} else if (rule.instrumentId === inst.id) {
await this.evaluateSingle(rule, inst, cfg);
}
@@ -629,6 +665,129 @@ class Monitor {
if (changed) this.persistRuleStates();
}
/**
* 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长就提醒一次,然后把基准更新到当前价。
* 例:步长 2 元、方向「每上涨」;780 建基准 → 782 提醒(基准变 782)→ 784 再提醒。
* 基价与上次提醒时间存在 ruleStates 里(key = 规则::ladder::品种),会随 rule-state.json 一起落盘。
* @param {object} rule 规则
* @param {object} inst 品种
* @param {object} cfg 配置
*/
async evaluateLadder(rule, inst, cfg) {
const state = this.quotes.get(inst.id);
if (!state || !state.price) return;
const price = state.price;
const key = `${rule.id}::ladder::${inst.id}`;
let saved = this.ruleStates.get(key);
// 第一次见到这个品种:先把当前价记成基准,不打扰
if (!saved || typeof saved.anchor !== 'number') {
this.ruleStates.set(key, { anchor: price, lastTriggerAt: 0 });
this.persistRuleStates();
return;
}
/** 步长口径:amount = 具体价格变动(元/克等);percent = 百分比 */
const basis = rule.changeBasis === 'amount' ? 'amount' : 'percent';
const step = Math.abs(rule.value);
/** 相对基准的变动量(amount 为价格差,percent 为百分数) */
const delta = basis === 'amount' ? price - saved.anchor : ((price - saved.anchor) / saved.anchor) * 100;
let hit = false;
if (rule.direction === 'down') hit = delta <= -step;
else if (rule.direction === 'both') hit = Math.abs(delta) >= step;
else hit = delta >= step; // 默认「每上涨」
if (!hit) return;
// 冷却期内先不提醒、也不移动基准,等冷却过了再判断
const cooldownMs = (rule.cooldownSec || 0) * 1000;
if (cooldownMs > 0 && Date.now() - Number(saved.lastTriggerAt || 0) < cooldownMs) return;
const anchor = saved.anchor;
this.ruleStates.set(key, { anchor: price, lastTriggerAt: Date.now() });
this.persistRuleStates();
const word = delta >= 0 ? '上涨' : '下跌';
const moveText = basis === 'amount'
? `${fmtPrice(Math.abs(delta), inst.digits)} ${inst.unit}`
: `${Math.abs(delta).toFixed(2)}%`;
const stepText = basis === 'amount'
? `${fmtPrice(step, inst.digits)} ${inst.unit}`
: `${step.toFixed(2)}%`;
const anchorText = `${fmtPrice(anchor, inst.digits)} ${inst.unit}`;
await this.raise(rule, {
title: `${inst.name} 阶梯提醒:较上次提醒${word} ${moveText}`,
message: `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},较上次提醒基准 ${anchorText} ${word} ${moveText},已达到步长 ${stepText}。基准已更新,下次再偏离 ${stepText} 时再提醒。`,
lines: [
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
`上次提醒基准:${anchorText}`,
`本次${word}:${moveText}(步长 ${stepText})`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
/**
* 请求失败告警:某个品种连续抓取失败达到指定次数时提醒一次。
* 失败次数用 state.errorCount 计(抓取成功会归零),因此「连续」的语义天然成立;
* 状态键 = 规则::failure::品种,成功抓取时由 resetFailureStates 归零,便于下一波失败重新提醒。
* @param {object} inst 品种
* @param {object} state 该品种的行情状态(errorCount 已自增)
* @param {Error} err 本次失败的错误
*/
async evaluateFailureRules(inst, state, err) {
const cfg = this.store.get();
const count = state.errorCount || 0;
for (const rule of cfg.rules) {
if (!rule.enabled || rule.type !== 'failure') continue;
if (rule.instrumentId !== inst.id) continue;
// 生效时段之外不评估(比如只在盘中盯数据源)
if (rule.activeRange && !inTimeRange(rule.activeRange)) continue;
/** 连续失败多少次算异常(至少 1 次) */
const limit = Math.max(1, Math.round(Number(rule.value) || 3));
const met = count >= limit;
const key = `${rule.id}::failure::${inst.id}`;
// 失败告警属于「异常即提醒」,第一次评估就满足也应该响,不受 alertOnFirstCheck 限制
if (!this.markAndCheck(rule, key, met, cfg, { alertOnFirst: true })) continue;
const lastOkText = state.updatedAt || '尚未成功抓取过';
const sourceText = `${inst.source}${inst.sourceOptions?.code ? ` / ${inst.sourceOptions.code}` : ''}`
+ `${inst.sourceOptions?.key ? ` / ${inst.sourceOptions.key}` : ''}`
+ `${inst.sourceOptions?.url ? ` / ${inst.sourceOptions.url}` : ''}`;
await this.raise(rule, {
title: `${inst.name} 连续抓取失败 ${count} 次`,
message: `${inst.name} 已连续 ${count} 次查询行情失败(阈值 ${limit} 次),最近一次报错:${err?.message || state.error || '未知原因'}。最后一次成功:${lastOkText}。请检查网络或数据源是否变更。`,
lines: [
`品种:<b>${inst.name}</b>(数据源 ${sourceText})`,
`连续失败:<b>${count} 次</b>(告警阈值 ${limit} 次)`,
`最近错误:${err?.message || state.error || '未知原因'}`,
`最后一次成功:${lastOkText}`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
}
/**
* 抓取成功后把该品种所有「请求失败告警」规则的状态压回不满足,
* 这样下一次连续失败还能重新触发(否则一直停在已触发状态,只会按重复间隔响)
* @param {string} instId 品种 id
*/
resetFailureStates(instId) {
const suffix = `::failure::${instId}`;
let changed = false;
for (const [key, value] of this.ruleStates) {
if (!key.endsWith(suffix)) continue;
if (value && value.met === false) continue;
this.ruleStates.set(key, { ...value, met: false });
changed = true;
}
if (changed) this.persistRuleStates();
}
/**
* 记录规则当前是否满足,并判断此刻是否应该发提醒。
* 采用「边沿触发」:只有从「不满足」变成「满足」才提醒(可选按 repeatIntervalSec 重复)。
@@ -636,9 +795,10 @@ class Monitor {
* @param {string} key 状态键
* @param {boolean} met 当前是否满足
* @param {object} cfg 配置
* @param {{alertOnFirst?: boolean}} [opts] alertOnFirst=true 时首次评估就满足也提醒
* @returns {boolean} 是否触发
*/
markAndCheck(rule, key, met, cfg) {
markAndCheck(rule, key, met, cfg, opts = {}) {
const now = Date.now();
let state = this.ruleStates.get(key);
const isFirst = !state;
@@ -650,7 +810,7 @@ class Monitor {
if (met) {
if (isFirst) {
// 首次评估:默认不打扰(可配置成也提醒),但把状态记下来
trigger = cfg.monitor?.alertOnFirstCheck === true;
trigger = opts.alertOnFirst === true ? true : cfg.monitor?.alertOnFirstCheck === true;
} else if (state.met !== true) {
trigger = true;
} else if (rule.repeatIntervalSec > 0 && now - state.lastTriggerAt >= rule.repeatIntervalSec * 1000) {
@@ -777,7 +937,12 @@ class Monitor {
if (!saved) return;
for (const [key, value] of Object.entries(saved)) {
if (value && typeof value === 'object') {
this.ruleStates.set(key, { met: value.met === true ? true : (value.met === false ? false : null), lastTriggerAt: Number(value.lastTriggerAt) || 0 });
// 保留各类型自己的附加字段(阶梯提醒要保住 anchor 基准价)
this.ruleStates.set(key, {
...value,
met: value.met === true ? true : (value.met === false ? false : null),
lastTriggerAt: Number(value.lastTriggerAt) || 0,
});
}
}
}
+4
View File
@@ -219,6 +219,10 @@ function createApp({ monitor }) {
if (body.type === 'spread' && !cfg.instruments.some((i) => i.id === body.compareInstrumentId)) {
throw new Error('价差提醒需要选择对比品种');
}
// 请求失败告警:次数至少 1 次
if (body.type === 'failure' && !(toNum(body.value) >= 1)) {
throw new Error('请填写有效的连续失败次数(至少 1 次)');
}
const rule = {
id: uid('rule'),
name: body.name || '未命名规则',