feat: 初始版本
This commit is contained in:
+881
@@ -0,0 +1,881 @@
|
||||
/**
|
||||
* 监控引擎:
|
||||
* 1. 为每个「监控品种」按各自的刷新频率(更新频率)定时抓取行情;
|
||||
* 2. 每次拿到新价格后,评估阈值提醒、涨跌幅提醒、价差提醒;
|
||||
* 3. 命中规则时通过桌面通知 / 邮件发出提醒,并做冷却去重、静默时段处理;
|
||||
* 4. 保存最近提醒记录与规则的触发状态,重启后不会重复轰炸。
|
||||
*/
|
||||
|
||||
const path = require('node:path');
|
||||
const {
|
||||
log, nowText, uid, fmtPrice, fmtPercent, inTimeRange, readJson, writeJson, appendJsonLine,
|
||||
} = require('./util');
|
||||
const sources = require('./sources');
|
||||
const notify = require('./notify');
|
||||
|
||||
/** 最多保留的提醒条数(内存 + 前端展示) */
|
||||
const MAX_ALERTS = 200;
|
||||
/** 每个品种保留的行情点数量(迷你走势 + 滚动窗口涨跌幅都靠它) */
|
||||
const MAX_HISTORY = 2400;
|
||||
/** 行情点最多保留多久(毫秒),超过即裁剪 */
|
||||
const HISTORY_KEEP_MS = 72 * 60 * 60 * 1000;
|
||||
/** 行情历史落盘周期(毫秒) */
|
||||
const HISTORY_FLUSH_MS = 10 * 60 * 1000;
|
||||
|
||||
class Monitor {
|
||||
/**
|
||||
* @param {{store: object}} deps 依赖注入,store 提供配置读写
|
||||
*/
|
||||
constructor({ store }) {
|
||||
this.store = store;
|
||||
/** @type {Map<string, NodeJS.Timeout>} 品种定时器 */
|
||||
this.timers = new Map();
|
||||
/** @type {Map<string, object>} 品种行情状态 */
|
||||
this.quotes = new Map();
|
||||
/** @type {Map<string, {met: boolean|null, lastTriggerAt: number}>} 规则触发状态 */
|
||||
this.ruleStates = new Map();
|
||||
/** @type {object[]} 最近提醒 */
|
||||
this.alerts = [];
|
||||
/** 正在抓取的品种,避免同一品种并发请求 */
|
||||
this.inflight = new Set();
|
||||
/** 已经提示过「单位不一致」的规则,避免日志刷屏 */
|
||||
this.warnedRules = new Set();
|
||||
this.running = false;
|
||||
this.startedAt = null;
|
||||
this.alertFile = path.join(store.ROOT, 'data', 'alerts.jsonl');
|
||||
this.stateFile = path.join(store.ROOT, 'data', 'rule-state.json');
|
||||
this.historyFile = path.join(store.ROOT, 'data', 'history.json');
|
||||
this.saveTimer = null;
|
||||
/** 行情历史定期落盘的定时器 */
|
||||
this.historyTimer = null;
|
||||
/** 定时提醒的巡检定时器(每 15 秒检查一次到点没到) */
|
||||
this.scheduleTimer = null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 生命周期
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** 启动监控 */
|
||||
start() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.startedAt = new Date().toISOString();
|
||||
this.loadRuleStates();
|
||||
this.loadAlerts();
|
||||
this.loadHistory();
|
||||
|
||||
const cfg = this.store.get();
|
||||
this.pruneMissing(cfg);
|
||||
for (const inst of cfg.instruments) {
|
||||
this.ensureQuoteState(inst);
|
||||
if (inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(inst.id);
|
||||
}
|
||||
// 定时把行情历史落盘,重启后「近 N 分钟涨跌幅」还能接着算
|
||||
if (this.historyTimer) clearInterval(this.historyTimer);
|
||||
this.historyTimer = setInterval(() => this.saveHistory(), HISTORY_FLUSH_MS);
|
||||
// 定时提醒巡检:独立于行情抓取节奏,避免某些品种 60 秒一刷导致整分钟被错过
|
||||
if (this.scheduleTimer) clearInterval(this.scheduleTimer);
|
||||
this.scheduleTimer = setInterval(() => {
|
||||
this.evaluateSchedules().catch((err) => log.error(`定时提醒巡检异常:${err.message}`));
|
||||
}, 15000);
|
||||
this.evaluateSchedules().catch(() => {});
|
||||
log.info(`监控已启动,共 ${cfg.instruments.filter((i) => i.enabled && i.intervalSec > 0).length} 个品种在轮询`);
|
||||
}
|
||||
|
||||
/** 停止监控(清空所有定时器) */
|
||||
stop() {
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
if (this.historyTimer) {
|
||||
clearInterval(this.historyTimer);
|
||||
this.historyTimer = null;
|
||||
}
|
||||
if (this.scheduleTimer) {
|
||||
clearInterval(this.scheduleTimer);
|
||||
this.scheduleTimer = null;
|
||||
}
|
||||
this.saveHistory();
|
||||
this.running = false;
|
||||
log.info('监控已暂停');
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置变化后重新编排定时器(增删品种、改频率、启用停用都走这里)
|
||||
*/
|
||||
reschedule() {
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
const cfg = this.store.get();
|
||||
this.pruneMissing(cfg);
|
||||
for (const inst of cfg.instruments) {
|
||||
this.ensureQuoteState(inst);
|
||||
if (this.running && inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(inst.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** 清掉配置里已删除的品种行情 */
|
||||
pruneMissing(cfg) {
|
||||
const ids = new Set(cfg.instruments.map((i) => i.id));
|
||||
for (const key of [...this.quotes.keys()]) {
|
||||
if (!ids.has(key)) this.quotes.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为单个品种编排循环定时器(用递归 setTimeout 避免请求堆叠)
|
||||
* @param {string} id 品种 id
|
||||
*/
|
||||
scheduleInstrument(id) {
|
||||
const old = this.timers.get(id);
|
||||
if (old) clearTimeout(old);
|
||||
|
||||
const inst0 = this.store.get().instruments.find((i) => i.id === id);
|
||||
if (!inst0 || inst0.intervalSec <= 0) return; // 手动类品种不自动轮询
|
||||
|
||||
const loop = async () => {
|
||||
if (!this.running) return;
|
||||
await this.tick(id);
|
||||
if (!this.running) return;
|
||||
const inst = this.store.get().instruments.find((i) => i.id === id);
|
||||
if (!inst || !inst.enabled) return;
|
||||
const baseMs = Math.max(5, inst.intervalSec || 30) * 1000;
|
||||
// 加 0~15% 抖动,避免多个品种同一秒打接口
|
||||
const jitter = Math.floor(baseMs * 0.15 * Math.random());
|
||||
this.timers.set(id, setTimeout(() => { loop().catch(() => {}); }, baseMs + jitter));
|
||||
};
|
||||
|
||||
// 首次抓取稍微错开,避免同时起跑
|
||||
this.timers.set(id, setTimeout(() => { loop().catch(() => {}); }, 200 + Math.random() * 800));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 抓取与状态维护
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 抓取一个品种并更新状态
|
||||
* @param {string} id 品种 id
|
||||
* @param {{force?: boolean}} options force=true 时忽略「已暂停」状态(手动刷新用)
|
||||
*/
|
||||
async tick(id, options = {}) {
|
||||
const force = !!options.force;
|
||||
if (this.inflight.has(id)) return this.quotes.get(id);
|
||||
const inst = this.store.get().instruments.find((i) => i.id === id);
|
||||
if (!inst) return null;
|
||||
if (!inst.enabled && !force) return this.quotes.get(id);
|
||||
|
||||
const state = this.ensureQuoteState(inst);
|
||||
this.inflight.add(id);
|
||||
try {
|
||||
const quote = await sources.fetchQuote(inst, {
|
||||
getManualPrice: (instId) => this.getManualPrice(instId),
|
||||
});
|
||||
const now = Date.now();
|
||||
state.price = quote.price;
|
||||
state.prevClose = quote.prevClose;
|
||||
state.change = quote.change;
|
||||
state.changePercent = quote.changePercent;
|
||||
state.high = quote.high;
|
||||
state.low = quote.low;
|
||||
state.open = quote.open;
|
||||
state.volume = quote.volume;
|
||||
state.sourceTime = quote.sourceTime || '';
|
||||
state.status = quote.extra?.manual ? 'manual' : 'ok';
|
||||
state.error = null;
|
||||
state.errorCount = 0;
|
||||
state.updatedAt = nowText();
|
||||
state.updatedAtMs = now;
|
||||
this.pushHistory(state, now, quote.price);
|
||||
|
||||
// 评估与该品种相关的规则
|
||||
await this.evaluateRules(inst);
|
||||
return state;
|
||||
} catch (err) {
|
||||
state.errorCount += 1;
|
||||
state.error = err.message;
|
||||
state.status = 'error';
|
||||
// 连续失败才提示日志,避免休市期刷屏
|
||||
if (state.errorCount <= 3 || state.errorCount % 20 === 0) {
|
||||
log.warn(`【${inst.name}】抓取失败(第 ${state.errorCount} 次):${err.message}`);
|
||||
}
|
||||
return state;
|
||||
} finally {
|
||||
this.inflight.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
/** 立即刷新所有启用的品种 */
|
||||
async refreshAll() {
|
||||
const cfg = this.store.get();
|
||||
await Promise.all(cfg.instruments.filter((i) => i.enabled).map((i) => this.tick(i.id, { force: true })));
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保品种有行情状态对象
|
||||
* @param {object} inst 品种
|
||||
* @returns {object}
|
||||
*/
|
||||
ensureQuoteState(inst) {
|
||||
let state = this.quotes.get(inst.id);
|
||||
if (!state) {
|
||||
state = {
|
||||
id: inst.id,
|
||||
price: null,
|
||||
prevClose: null,
|
||||
change: null,
|
||||
changePercent: null,
|
||||
high: null,
|
||||
low: null,
|
||||
open: null,
|
||||
volume: null,
|
||||
sourceTime: '',
|
||||
status: inst.enabled ? 'pending' : 'disabled',
|
||||
error: null,
|
||||
errorCount: 0,
|
||||
updatedAt: '',
|
||||
updatedAtMs: 0,
|
||||
history: [],
|
||||
};
|
||||
this.quotes.set(inst.id, state);
|
||||
}
|
||||
if (!inst.enabled) state.status = 'disabled';
|
||||
else if (state.status === 'disabled') state.status = 'pending';
|
||||
return state;
|
||||
}
|
||||
|
||||
/** 取手动录入的价格 */
|
||||
getManualPrice(instId) {
|
||||
const cfg = this.store.get();
|
||||
return cfg.manualPrices?.[instId] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动更新某个品种的价格(会立刻重新评估规则)
|
||||
* @param {string} instId 品种 id
|
||||
* @param {number} price 价格
|
||||
* @param {number|null} prevClose 昨收(可选)
|
||||
* @returns {Promise<object|null>} 更新后的行情状态
|
||||
*/
|
||||
async setManualPrice(instId, price, prevClose = null) {
|
||||
const inst = this.store.get().instruments.find((i) => i.id === instId);
|
||||
if (!inst) throw new Error('品种不存在');
|
||||
this.store.patch({ manualPrices: { [instId]: { price, prevClose, at: nowText() } } });
|
||||
const old = this.timers.get(instId);
|
||||
if (old) clearTimeout(old);
|
||||
if (this.running && inst.enabled && inst.intervalSec > 0) this.scheduleInstrument(instId);
|
||||
return this.tick(instId, { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录一个行情点,并按「条数 + 时间」两个维度裁剪
|
||||
* @param {object} state 行情状态
|
||||
* @param {number} t 时间戳
|
||||
* @param {number} price 价格
|
||||
*/
|
||||
pushHistory(state, t, price) {
|
||||
state.history.push({ t, p: price });
|
||||
if (state.history.length > MAX_HISTORY) state.history.splice(0, state.history.length - MAX_HISTORY);
|
||||
// 砍掉超过 72 小时的老数据(正常一轮只移动很少几个点)
|
||||
const cutoff = t - HISTORY_KEEP_MS;
|
||||
let drop = 0;
|
||||
while (drop < state.history.length && state.history[drop].t < cutoff) drop += 1;
|
||||
if (drop > 0) state.history.splice(0, drop);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算「近 windowSec 秒」的涨跌幅
|
||||
* @param {object} state 行情状态
|
||||
* @param {number} windowSec 统计区间(秒)
|
||||
* @returns {{pct: number, ref: number, refAt: number}|null} 数据不足时返回 null
|
||||
*/
|
||||
computeWindowChange(state, windowSec) {
|
||||
const hist = state.history || [];
|
||||
if (hist.length < 2 || !state.price) return null;
|
||||
const target = Date.now() - windowSec * 1000;
|
||||
// 历史还没覆盖到目标时刻,说明数据不够,先不评估
|
||||
if (hist[0].t > target + 1500) return null;
|
||||
|
||||
let ref = null;
|
||||
for (const point of hist) {
|
||||
if (point.t <= target) ref = point;
|
||||
else break;
|
||||
}
|
||||
if (!ref || !ref.p) return null;
|
||||
return {
|
||||
ref: ref.p,
|
||||
refAt: ref.t,
|
||||
pct: ((state.price - ref.p) / ref.p) * 100,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计区间的人类可读文案
|
||||
* @param {number} windowSec 秒
|
||||
* @returns {string}
|
||||
*/
|
||||
static windowLabel(windowSec) {
|
||||
if (windowSec <= 0) return '日内';
|
||||
if (windowSec < 60) return `近 ${windowSec} 秒`;
|
||||
if (windowSec % 3600 === 0) return `近 ${windowSec / 3600} 小时`;
|
||||
return `近 ${Math.round(windowSec / 60)} 分钟`;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 规则评估
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 评估某个品种相关的全部规则
|
||||
* @param {object} inst 刚更新的品种
|
||||
*/
|
||||
async evaluateRules(inst) {
|
||||
const cfg = this.store.get();
|
||||
for (const rule of cfg.rules) {
|
||||
if (!rule.enabled) continue;
|
||||
// 生效时段之外直接跳过("22:00-02:00" 这类跨零点区间也支持)
|
||||
if (rule.activeRange && !inTimeRange(rule.activeRange)) {
|
||||
// 时段外不评估,但把状态压成「不满足」:这样进入时段后条件一旦成立,
|
||||
// 仍会按边沿触发正常提醒,而不是被当成「首次评估」静默掉。
|
||||
const key = rule.type === 'spread' ? `${rule.id}::spread` : `${rule.id}::${inst.id}`;
|
||||
const st = this.ruleStates.get(key);
|
||||
if (!st) {
|
||||
this.ruleStates.set(key, { met: false, lastTriggerAt: 0 });
|
||||
this.persistRuleStates();
|
||||
} else if (st.met !== false) {
|
||||
st.met = false;
|
||||
this.persistRuleStates();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (rule.type === 'spread') {
|
||||
if (rule.instrumentId === inst.id || rule.compareInstrumentId === inst.id) {
|
||||
await this.evaluateSpread(rule, cfg);
|
||||
}
|
||||
} else if (rule.instrumentId === inst.id) {
|
||||
await this.evaluateSingle(rule, inst, cfg);
|
||||
}
|
||||
} catch (err) {
|
||||
log.error(`规则「${rule.name}」评估异常:${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 阈值 / 涨跌幅规则
|
||||
* @param {object} rule 规则
|
||||
* @param {object} inst 品种
|
||||
* @param {object} cfg 配置
|
||||
*/
|
||||
async evaluateSingle(rule, inst, cfg) {
|
||||
const state = this.quotes.get(inst.id);
|
||||
if (!state || !state.price) return;
|
||||
|
||||
const price = state.price;
|
||||
/** 数据源自带的日内涨跌幅(相对昨收),窗口模式会用它兜底 */
|
||||
const pct0 = state.changePercent;
|
||||
|
||||
if (rule.type === 'threshold') {
|
||||
const met = rule.direction === 'below' ? price <= rule.value : price >= rule.value;
|
||||
const key = `${rule.id}::${inst.id}`;
|
||||
if (!this.markAndCheck(rule, key, met, cfg)) return;
|
||||
|
||||
const word = rule.direction === 'below' ? '下破' : '上破';
|
||||
const title = `${inst.name} ${word} ${fmtPrice(rule.value, inst.digits)} ${inst.unit}`;
|
||||
const message = `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},已${word}阈值 ${fmtPrice(rule.value, inst.digits)} ${inst.unit};日内 ${fmtPercent(pct0)}。`;
|
||||
await this.raise(rule, {
|
||||
title,
|
||||
message,
|
||||
lines: [
|
||||
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
|
||||
`触发条件:价格${word} ${fmtPrice(rule.value, inst.digits)} ${inst.unit}`,
|
||||
`日内涨跌幅:${fmtPercent(pct0)}(昨收 ${fmtPrice(state.prevClose, inst.digits)})`,
|
||||
`触发时间:${nowText()}`,
|
||||
],
|
||||
snapshot: this.snapshot(),
|
||||
}, cfg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rule.type === 'change') {
|
||||
const windowSec = rule.windowSec || 0;
|
||||
const label = Monitor.windowLabel(windowSec);
|
||||
/** 阈值口径:percent = 涨跌幅百分比;amount = 具体价格变动值(元/克等) */
|
||||
const basis = rule.changeBasis === 'amount' ? 'amount' : 'percent';
|
||||
/** 当前区间内的变动幅度(percent 为百分数,amount 为价格差) */
|
||||
let metric = null;
|
||||
let refPrice = state.prevClose;
|
||||
|
||||
if (windowSec > 0) {
|
||||
// 滚动窗口:拿「近 N 分钟」的起算价重新算涨跌幅
|
||||
const win = this.computeWindowChange(state, windowSec);
|
||||
if (!win) {
|
||||
// 历史数据还没攒够:先把状态记成「不满足」,等数据齐了再由边沿触发正常判断,
|
||||
// 否则第一次能算出窗口涨跌幅时会被当成「首次评估」而静默掉。
|
||||
this.markAndCheck(rule, `${rule.id}::${inst.id}`, false, cfg);
|
||||
// 只提示一次,避免日志刷屏
|
||||
const warnKey = `${rule.id}::${inst.id}::window`;
|
||||
if (!this.warnedRules.has(warnKey)) {
|
||||
this.warnedRules.add(warnKey);
|
||||
log.warn(`规则「${rule.name}」需要${label}的历史行情,数据还没攒够,稍后再评估`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
metric = basis === 'amount' ? price - win.ref : win.pct;
|
||||
refPrice = win.ref;
|
||||
} else if (basis === 'amount') {
|
||||
// 日内口径:优先用数据源给的涨跌额,没有就用「现价 - 昨收」兜底
|
||||
if (typeof state.change === 'number') metric = state.change;
|
||||
else if (typeof state.prevClose === 'number' && state.prevClose > 0) metric = price - state.prevClose;
|
||||
} else {
|
||||
metric = pct0;
|
||||
}
|
||||
|
||||
if (metric === null || metric === undefined) {
|
||||
// 数据不足(比如缺昨收):先压成不满足,等数据齐了再正常触发
|
||||
this.markAndCheck(rule, `${rule.id}::${inst.id}`, false, cfg);
|
||||
return;
|
||||
}
|
||||
const threshold = Math.abs(rule.value);
|
||||
let met = false;
|
||||
if (rule.direction === 'up') met = metric >= threshold;
|
||||
else if (rule.direction === 'down') met = metric <= -threshold;
|
||||
else met = Math.abs(metric) >= threshold;
|
||||
|
||||
const key = `${rule.id}::${inst.id}`;
|
||||
if (!this.markAndCheck(rule, key, met, cfg)) return;
|
||||
|
||||
const word = metric >= 0 ? '涨幅' : '跌幅';
|
||||
// 幅度的展示文案:百分比用 xx.xx%,具体值用「数字 + 单位」
|
||||
const metricText = basis === 'amount'
|
||||
? `${fmtPrice(Math.abs(metric), inst.digits)} ${inst.unit}`
|
||||
: `${Math.abs(metric).toFixed(2)}%`;
|
||||
const signedText = basis === 'amount'
|
||||
? `${fmtPrice(metric, inst.digits)} ${inst.unit}`
|
||||
: fmtPercent(metric);
|
||||
const thresholdText = basis === 'amount'
|
||||
? `${fmtPrice(threshold, inst.digits)} ${inst.unit}`
|
||||
: `${threshold.toFixed(2)}%`;
|
||||
const title = `${inst.name} ${label}${word}达 ${metricText}`;
|
||||
const message = `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},${label}${word} ${signedText},已超过 ${thresholdText}的提醒线。`;
|
||||
const refLine = windowSec > 0
|
||||
? `${label}变动:${signedText}(${label}起算价 ${fmtPrice(refPrice, inst.digits)} ${inst.unit})`
|
||||
: basis === 'amount'
|
||||
? `日内变动:${signedText}(昨收 ${fmtPrice(state.prevClose, inst.digits)} ${inst.unit})`
|
||||
: `${label}涨跌幅:${fmtPercent(pct0)}(昨收 ${fmtPrice(state.prevClose, inst.digits)})`;
|
||||
|
||||
await this.raise(rule, {
|
||||
title,
|
||||
message,
|
||||
lines: [
|
||||
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
|
||||
refLine,
|
||||
`触发条件:${word} ≥ ${thresholdText}(${label})`,
|
||||
`触发时间:${nowText()}`,
|
||||
],
|
||||
snapshot: this.snapshot(),
|
||||
}, cfg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 价差规则:两个品种价差超过阈值
|
||||
* @param {object} rule 规则
|
||||
* @param {object} cfg 配置
|
||||
*/
|
||||
async evaluateSpread(rule, cfg) {
|
||||
const leftInst = cfg.instruments.find((i) => i.id === rule.instrumentId);
|
||||
const rightInst = cfg.instruments.find((i) => i.id === rule.compareInstrumentId);
|
||||
if (!leftInst || !rightInst) return;
|
||||
const left = this.quotes.get(rule.instrumentId);
|
||||
const right = this.quotes.get(rule.compareInstrumentId);
|
||||
if (!left?.price || !right?.price) return;
|
||||
// 单位不一致时无法比较价差
|
||||
if (leftInst.unit !== rightInst.unit) {
|
||||
if (!this.warnedRules.has(rule.id)) {
|
||||
this.warnedRules.add(rule.id);
|
||||
log.warn(`规则「${rule.name}」两个品种单位不一致(${leftInst.unit} / ${rightInst.unit}),已跳过`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const diff = left.price - right.price;
|
||||
const value = rule.mode === 'percent' ? (diff / right.price) * 100 : diff;
|
||||
const absThreshold = Math.abs(rule.value);
|
||||
|
||||
let met = false;
|
||||
if (rule.direction === 'above') met = value >= absThreshold;
|
||||
else if (rule.direction === 'below') met = value <= -absThreshold;
|
||||
else met = Math.abs(value) >= absThreshold;
|
||||
|
||||
const key = `${rule.id}::spread`;
|
||||
if (!this.markAndCheck(rule, key, met, cfg)) return;
|
||||
|
||||
const unitText = rule.mode === 'percent' ? '%' : leftInst.unit;
|
||||
const valText = value.toFixed(rule.mode === 'percent' ? 2 : leftInst.digits);
|
||||
const title = `${leftInst.name} 与 ${rightInst.name} 价差 ${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}`;
|
||||
const message = `当前 ${leftInst.name} ${fmtPrice(left.price, leftInst.digits)} ${leftInst.unit},`
|
||||
+ `${rightInst.name} ${fmtPrice(right.price, rightInst.digits)} ${rightInst.unit},`
|
||||
+ `价差 ${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}(阈值 ${absThreshold})。`;
|
||||
await this.raise(rule, {
|
||||
title,
|
||||
message,
|
||||
lines: [
|
||||
`${leftInst.name}:<b>${fmtPrice(left.price, leftInst.digits)} ${leftInst.unit}</b>`,
|
||||
`${rightInst.name}:<b>${fmtPrice(right.price, rightInst.digits)} ${rightInst.unit}</b>`,
|
||||
`价差:${valText}${rule.mode === 'percent' ? '%' : ` ${unitText}`}(触发阈值 ${absThreshold}${rule.mode === 'percent' ? '%' : ` ${unitText}`})`,
|
||||
`触发时间:${nowText()}`,
|
||||
],
|
||||
snapshot: this.snapshot(),
|
||||
}, cfg);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 定时提醒
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 判断某天是否命中定时规则的重复方式
|
||||
* @param {object} rule 规则
|
||||
* @param {Date} date 当前时间
|
||||
* @returns {boolean} 当天是否需要提醒
|
||||
*/
|
||||
matchScheduleDay(rule, date) {
|
||||
const repeat = rule.scheduleRepeat || 'daily';
|
||||
/** getDay() 里周日是 0,这里换成 ISO 口径:周一=1 … 周日=7 */
|
||||
const iso = date.getDay() === 0 ? 7 : date.getDay();
|
||||
if (repeat === 'weekday') return iso <= 5;
|
||||
if (repeat === 'weekly') return (rule.scheduleWeekdays || []).includes(iso);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 巡检所有定时提醒规则:到点了就发一条提醒。
|
||||
* 容错窗口 2 分钟(巡检 15 秒一次,加上抓取抖动也不会漏掉整分钟);
|
||||
* 同一档时刻(同一天同一时刻)只响一次,去重状态写进 data/rule-state.json,重启也不会重复提醒。
|
||||
*/
|
||||
async evaluateSchedules() {
|
||||
if (!this.running) return;
|
||||
const cfg = this.store.get();
|
||||
const now = new Date();
|
||||
const nowMs = now.getTime();
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const dateKey = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
||||
|
||||
for (const rule of cfg.rules) {
|
||||
if (rule.type !== 'schedule' || !rule.enabled) continue;
|
||||
if (!this.matchScheduleDay(rule, now)) continue;
|
||||
for (const time of rule.scheduleTimes || []) {
|
||||
const [hh, mm] = time.split(':').map(Number);
|
||||
const slotMs = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0, 0).getTime();
|
||||
const diff = nowMs - slotMs;
|
||||
if (diff < 0 || diff > 120000) continue; // 还没到点,或者已经错过 2 分钟以上
|
||||
const stateKey = `${rule.id}::schedule::${dateKey} ${time}`;
|
||||
if (this.ruleStates.has(stateKey)) continue; // 这一档今天已经响过
|
||||
this.ruleStates.set(stateKey, { met: true, lastTriggerAt: nowMs });
|
||||
this.persistRuleStates();
|
||||
await this.fireSchedule(rule, time, cfg);
|
||||
}
|
||||
}
|
||||
this.pruneScheduleStates();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送一条定时提醒,正文带上该品种的最新行情,方便一眼看到当时的价格
|
||||
* @param {object} rule 定时规则
|
||||
* @param {string} time 命中的时刻,如 "09:00"
|
||||
* @param {object} cfg 配置
|
||||
*/
|
||||
async fireSchedule(rule, time, cfg) {
|
||||
const inst = cfg.instruments.find((i) => i.id === rule.instrumentId);
|
||||
const state = inst ? this.quotes.get(inst.id) : null;
|
||||
const hasPrice = !!(inst && state && state.price);
|
||||
|
||||
const repeatText = rule.scheduleRepeat === 'weekday' ? '工作日' : rule.scheduleRepeat === 'weekly' ? '每周' : '每天';
|
||||
const title = `${inst?.name || '定时提醒'} ${time} 定时提醒`;
|
||||
const message = hasPrice
|
||||
? `${repeatText} ${time} 定时提醒:${inst.name} 最新价 ${fmtPrice(state.price, inst.digits)} ${inst.unit},日内 ${fmtPercent(state.changePercent)}。`
|
||||
: `${repeatText} ${time} 定时提醒:${inst?.name || '未绑定品种'}${state?.status === 'error' ? `,当前抓取失败(${state.error || '未知原因'})` : ',暂无行情数据'}。`;
|
||||
|
||||
await this.raise(rule, {
|
||||
title,
|
||||
message,
|
||||
lines: [
|
||||
hasPrice
|
||||
? `${inst.name} 最新价:<b>${fmtPrice(state.price, inst.digits)} ${inst.unit}</b>`
|
||||
: `${inst?.name || '未绑定品种'}:暂无行情`,
|
||||
hasPrice
|
||||
? `日内涨跌:${fmtPercent(state.changePercent)}(昨收 ${fmtPrice(state.prevClose, inst.digits)} ${inst.unit})`
|
||||
: `数据状态:${state?.status === 'error' ? (state.error || '抓取失败') : '暂无行情'}`,
|
||||
`提醒时刻:${repeatText} ${(rule.scheduleTimes || []).join('、')}`,
|
||||
`触发时间:${nowText()}`,
|
||||
],
|
||||
snapshot: this.snapshot(),
|
||||
}, cfg);
|
||||
}
|
||||
|
||||
/** 清掉 3 天前的定时提醒去重记录,避免 rule-state.json 越攒越大 */
|
||||
pruneScheduleStates() {
|
||||
const cutoff = Date.now() - 3 * 24 * 60 * 60 * 1000;
|
||||
let changed = false;
|
||||
for (const [key, value] of [...this.ruleStates.entries()]) {
|
||||
if (!key.includes('::schedule::')) continue;
|
||||
if (!value || Number(value.lastTriggerAt) < cutoff) {
|
||||
this.ruleStates.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) this.persistRuleStates();
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录规则当前是否满足,并判断此刻是否应该发提醒。
|
||||
* 采用「边沿触发」:只有从「不满足」变成「满足」才提醒(可选按 repeatIntervalSec 重复)。
|
||||
* @param {object} rule 规则
|
||||
* @param {string} key 状态键
|
||||
* @param {boolean} met 当前是否满足
|
||||
* @param {object} cfg 配置
|
||||
* @returns {boolean} 是否触发
|
||||
*/
|
||||
markAndCheck(rule, key, met, cfg) {
|
||||
const now = Date.now();
|
||||
let state = this.ruleStates.get(key);
|
||||
const isFirst = !state;
|
||||
if (!state) state = { met: null, lastTriggerAt: 0 };
|
||||
|
||||
const cooldownMs = (rule.cooldownSec || 0) * 1000;
|
||||
let trigger = false;
|
||||
|
||||
if (met) {
|
||||
if (isFirst) {
|
||||
// 首次评估:默认不打扰(可配置成也提醒),但把状态记下来
|
||||
trigger = cfg.monitor?.alertOnFirstCheck === true;
|
||||
} else if (state.met !== true) {
|
||||
trigger = true;
|
||||
} else if (rule.repeatIntervalSec > 0 && now - state.lastTriggerAt >= rule.repeatIntervalSec * 1000) {
|
||||
trigger = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (trigger && cooldownMs > 0 && now - state.lastTriggerAt < cooldownMs) trigger = false;
|
||||
|
||||
state.met = met;
|
||||
if (trigger) state.lastTriggerAt = now;
|
||||
this.ruleStates.set(key, state);
|
||||
this.persistRuleStates();
|
||||
return trigger;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装一条提醒并分发到各通知渠道
|
||||
* @param {object} rule 规则
|
||||
* @param {{title: string, message: string, lines: string[], snapshot: object[]}} content 内容
|
||||
* @param {object} cfg 配置
|
||||
*/
|
||||
async raise(rule, content, cfg) {
|
||||
const channels = Array.isArray(rule.channels) && rule.channels.length ? rule.channels : cfg.channels.onTrigger;
|
||||
const quietCfg = cfg.monitor?.quietHours || {};
|
||||
const quietActive = !!quietCfg.enabled
|
||||
&& inTimeRange(quietCfg.range)
|
||||
&& quietCfg.desktopOnly !== false;
|
||||
|
||||
const alert = {
|
||||
id: uid('alert'),
|
||||
at: nowText(),
|
||||
atMs: Date.now(),
|
||||
ruleId: rule.id,
|
||||
ruleName: rule.name,
|
||||
title: content.title,
|
||||
message: content.message,
|
||||
lines: content.lines,
|
||||
channels,
|
||||
quietActive,
|
||||
};
|
||||
|
||||
log.info(`🔔 触发提醒:${content.title}`);
|
||||
const delivered = await notify.dispatch(alert, channels, { config: cfg, quietActive });
|
||||
alert.delivered = delivered;
|
||||
|
||||
this.alerts.unshift(alert);
|
||||
if (this.alerts.length > MAX_ALERTS) this.alerts.length = MAX_ALERTS;
|
||||
|
||||
try {
|
||||
appendJsonLine(this.alertFile, {
|
||||
at: alert.at,
|
||||
ruleId: alert.ruleId,
|
||||
ruleName: alert.ruleName,
|
||||
title: alert.title,
|
||||
message: alert.message,
|
||||
channels,
|
||||
delivered,
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn(`提醒日志写入失败:${err.message}`);
|
||||
}
|
||||
return alert;
|
||||
}
|
||||
|
||||
/** 当前所有品种的行情快照(供邮件正文使用) */
|
||||
snapshot() {
|
||||
const cfg = this.store.get();
|
||||
return cfg.instruments
|
||||
.filter((i) => i.enabled)
|
||||
.map((i) => {
|
||||
const q = this.quotes.get(i.id);
|
||||
return {
|
||||
name: i.name,
|
||||
price: q?.price ?? null,
|
||||
unit: i.unit,
|
||||
digits: i.digits,
|
||||
changePercent: q?.changePercent ?? null,
|
||||
};
|
||||
})
|
||||
.filter((i) => i.price);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 状态持久化
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** 读取历史提醒(保留最近 MAX_ALERTS 条用于页面展示) */
|
||||
loadAlerts() {
|
||||
if (this.alerts.length) return;
|
||||
try {
|
||||
const fs = require('node:fs');
|
||||
if (!fs.existsSync(this.alertFile)) return;
|
||||
const lines = fs.readFileSync(this.alertFile, 'utf8').trim().split('\n').slice(-MAX_ALERTS);
|
||||
this.alerts = lines
|
||||
.map((line) => {
|
||||
try { return JSON.parse(line); } catch { return null; }
|
||||
})
|
||||
.filter(Boolean)
|
||||
.map((item) => ({ ...item, lines: item.lines || [] }))
|
||||
.reverse();
|
||||
} catch (err) {
|
||||
log.warn(`读取历史提醒失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空提醒记录:内存数组和 data/alerts.jsonl 一起清掉,
|
||||
* 否则重启后旧记录又会从文件里读回来
|
||||
*/
|
||||
clearAlerts() {
|
||||
this.alerts.length = 0;
|
||||
try {
|
||||
const fs = require('node:fs');
|
||||
fs.writeFileSync(this.alertFile, '');
|
||||
} catch (err) {
|
||||
log.warn(`清空提醒记录文件失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取规则触发状态 */
|
||||
loadRuleStates() {
|
||||
const saved = readJson(this.stateFile, null);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 延迟落盘规则状态,避免频繁写文件 */
|
||||
persistRuleStates() {
|
||||
if (this.saveTimer) return;
|
||||
this.saveTimer = setTimeout(() => {
|
||||
this.saveTimer = null;
|
||||
const plain = {};
|
||||
for (const [key, value] of this.ruleStates) plain[key] = value;
|
||||
try {
|
||||
writeJson(this.stateFile, plain);
|
||||
} catch (err) {
|
||||
log.warn(`规则状态保存失败:${err.message}`);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取落盘的行情历史,让「近 N 分钟涨跌幅」在重启后也能立刻算
|
||||
* (只恢复价格点,不恢复涨跌额等展示字段)
|
||||
*/
|
||||
loadHistory() {
|
||||
const saved = readJson(this.historyFile, null);
|
||||
if (!saved || typeof saved !== 'object') return;
|
||||
const cutoff = Date.now() - HISTORY_KEEP_MS;
|
||||
for (const [instId, points] of Object.entries(saved)) {
|
||||
if (!Array.isArray(points) || points.length === 0) continue;
|
||||
const state = this.ensureQuoteState({ id: instId, enabled: true });
|
||||
const clean = points
|
||||
.filter((p) => p && Number.isFinite(Number(p.t)) && Number.isFinite(Number(p.p)))
|
||||
.map((p) => ({ t: Number(p.t), p: Number(p.p) }))
|
||||
.filter((p) => p.t >= cutoff);
|
||||
if (clean.length) {
|
||||
state.history = clean.slice(-MAX_HISTORY);
|
||||
const last = state.history[state.history.length - 1];
|
||||
// 用最后一个点兜底填充展示价格,避免刚启动时卡片空着
|
||||
if (!state.price) {
|
||||
state.price = last.p;
|
||||
state.updatedAtMs = last.t;
|
||||
state.updatedAt = nowText(new Date(last.t));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 把各品种的行情历史落盘(体积很小,10 分钟一次即可) */
|
||||
saveHistory() {
|
||||
const plain = {};
|
||||
for (const [instId, state] of this.quotes) {
|
||||
if (state.history && state.history.length) plain[instId] = state.history;
|
||||
}
|
||||
try {
|
||||
writeJson(this.historyFile, plain);
|
||||
} catch (err) {
|
||||
log.warn(`行情历史保存失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 对前端输出
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** 汇总给网页的状态 */
|
||||
getState() {
|
||||
const cfg = this.store.get();
|
||||
const quietCfg = cfg.monitor?.quietHours || {};
|
||||
const quietActive = !!quietCfg.enabled && inTimeRange(quietCfg.range);
|
||||
return {
|
||||
running: this.running,
|
||||
startedAt: this.startedAt,
|
||||
serverTime: nowText(),
|
||||
quietActive,
|
||||
rules: cfg.rules,
|
||||
instruments: cfg.instruments.map((inst) => {
|
||||
const q = this.quotes.get(inst.id) || {};
|
||||
return {
|
||||
...inst,
|
||||
price: q.price ?? null,
|
||||
prevClose: q.prevClose ?? null,
|
||||
change: q.change ?? null,
|
||||
changePercent: q.changePercent ?? null,
|
||||
high: q.high ?? null,
|
||||
low: q.low ?? null,
|
||||
open: q.open ?? null,
|
||||
sourceTime: q.sourceTime || '',
|
||||
status: inst.enabled ? (q.status || 'pending') : 'disabled',
|
||||
error: q.error || null,
|
||||
errorCount: q.errorCount || 0,
|
||||
updatedAt: q.updatedAt || '',
|
||||
history: (q.history || []).slice(-60),
|
||||
manualPrice: cfg.manualPrices?.[inst.id] || null,
|
||||
};
|
||||
}),
|
||||
alerts: this.alerts.slice(0, 50),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Monitor };
|
||||
Reference in New Issue
Block a user