feat: 实现LLM趋势告警历史上下文判断功能

新增功能:
- 在LLM趋势分析中集成历史告警上下文,提供最近3次已触发告警的记录
- LLM自动判断本次分析是否与历史告警相似,避免重复通知
- 新增shouldNotify和notifyReason字段,支持智能通知决策

技术改进:
- 扩展TrendAnalysisResponse类型,增加通知决策字段
- 数据库服务新增getRecentTriggeredAnalyses()方法
- LLM客户端新增analyzeTrendWithHistory()和相关方法
- 趋势分析服务集成历史上下文获取和通知决策逻辑

测试验证:
- 创建test-db-history-method.ts验证数据库方法
- 创建test-llm-history-context.ts测试历史上下文功能
- 通过TypeScript类型检查和构建验证

这个功能可以有效减少重复告警,提升告警质量,避免通知疲劳。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-15 19:37:28 +08:00
commit ccf523543a
52 files changed
+7763

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
import { DatabaseService } from './services/database.js';
import { ScraperService } from './services/scraper.js';
import { MonitorService } from './services/monitor.js';
import { SilverBaselineMonitor } from './services/silver-baseline-monitor.js';
import { SilverTrendAnalyzer } from './services/silver-trend-analyzer.js';
import { AlertService, createAlertCallback } from './utils/alert.js';
import { LLMClient } from './utils/llm-client.js';
/**
* 主应用类
*/
class App {
private db: DatabaseService;
private scraper: ScraperService;
private monitor: MonitorService;
private silverBaselineMonitor: SilverBaselineMonitor;
private trendAnalyzer?: SilverTrendAnalyzer;
private alertService: AlertService;
private abortController: AbortController;
constructor() {
this.db = new DatabaseService();
this.scraper = new ScraperService();
this.alertService = new AlertService();
this.abortController = new AbortController();
// 配置监控服务
const interval = Number(process.env.MONITOR_INTERVAL) || 60000; // 默认 60 秒
this.monitor = new MonitorService(
this.db,
{
interval,
enableAlert: true,
alertCallback: createAlertCallback(this.alertService)
},
this.alertService // 传递 alertService 用于发送汇总报告
);
// 配置白银基线监控服务
const threshold = Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2; // 默认 0.2
this.silverBaselineMonitor = new SilverBaselineMonitor(
this.db,
threshold,
this.alertService,
process.env.WEBHOOK_URL
);
// 配置 LLM 趋势总结服务(如果配置了 API Key)
if (process.env.LLM_API_KEY) {
const llmConfig = {
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
apiKey: process.env.LLM_API_KEY,
model: process.env.LLM_MODEL || 'gpt-4o-mini',
timeout: 120000
};
const llmClient = new LLMClient(llmConfig);
this.trendAnalyzer = new SilverTrendAnalyzer(
this.db,
this.alertService,
llmClient,
process.env.WEBHOOK_URL
);
}
}
/**
* 初始化应用
*/
async init(): Promise<void> {
try {
console.log('========================================');
console.log('贵金属价格监控系统启动中...');
console.log('========================================\n');
// 初始化数据库
await this.db.init();
// 初始化告警服务
await this.alertService.init();
// 初始化浏览器
await this.scraper.init();
console.log('\n========================================');
console.log('系统初始化完成!');
console.log('========================================\n');
} catch (error) {
console.error('初始化失败:', error);
throw error;
}
}
/**
* 启动监控
*/
start(): void {
console.log('开始监控...\n');
// 价差监控已禁用 - 仅运行白银基线监控
// 如需恢复价差监控,请取消下面的注释
/*
// 启动价差监控
this.monitor.startMonitor(
// 获取价格的函数
() => this.scraper.fetchSilverPrices(),
// 用于停止的 AbortSignal
this.abortController.signal
);
*/
// 启动白银基线监控
const interval = Number(process.env.MONITOR_INTERVAL) || 60000;
const monitorSilverBaseline = async () => {
try {
const silverPrice = await this.scraper.fetchSilverPrice();
if (silverPrice) {
await this.silverBaselineMonitor.processPrice(silverPrice);
} else {
console.error('获取白银价格失败');
}
} catch (error) {
console.error('白银基线监控执行出错:', error);
}
};
// 立即执行一次
monitorSilverBaseline();
// 设置定时执行
const silverIntervalId = setInterval(monitorSilverBaseline, interval);
// 监听退出信号,停止白银基线监控
this.abortController.signal.addEventListener('abort', () => {
clearInterval(silverIntervalId);
console.log('白银基线监控已停止');
});
// 启动 LLM 趋势总结
if (this.trendAnalyzer) {
const trendAnalysisInterval = Number(process.env.TREND_ANALYSIS_INTERVAL) || 300000; // 默认 5 分钟
const analyzeTrend = async () => {
try {
await this.trendAnalyzer!.analyzeTrend();
} catch (error) {
console.error('趋势总结执行出错:', error);
}
};
// 首次延迟 5 分钟执行(等待积累足够数据)
setTimeout(analyzeTrend, 300000);
// 定时执行
const trendIntervalId = setInterval(analyzeTrend, trendAnalysisInterval);
// 监听退出信号,停止趋势分析
this.abortController.signal.addEventListener('abort', () => {
clearInterval(trendIntervalId);
console.log('LLM 趋势总结已停止');
});
console.log(`LLM 趋势总结已启动,分析间隔:${trendAnalysisInterval}ms`);
}
}
/**
* 停止监控
*/
async stop(): Promise<void> {
console.log('\n正在停止监控...');
this.abortController.abort();
await this.scraper.close();
console.log('监控已停止');
}
/**
* 显示统计信息
*/
showStats(): void {
// 价差监控已禁用 - 仅显示白银基线监控统计
/*
// 价差监控统计信息
const stats = this.monitor.getStats();
console.log('\n========================================');
console.log('价差监控统计信息');
console.log('========================================');
console.log(`总价格记录: ${stats.totalPrices}`);
console.log(`总变化次数: ${stats.totalChanges}`);
console.log(`上涨次数: ${stats.riseCount}`);
console.log(`下跌次数: ${stats.fallCount}`);
console.log('========================================\n');
// 显示最近的变化记录
const recentChanges = this.monitor.getRecentChanges(5);
if (recentChanges.length > 0) {
console.log('最近的变化记录:');
recentChanges.forEach((change, index) => {
console.log(`${index + 1}. ${new Date(change.timestamp).toLocaleString('zh-CN')} - ${change.changeType === 'RISE' ? '上涨' : '下跌'} (价差: ${change.currentSpread.toFixed(3)})`);
});
console.log('');
}
*/
// 显示白银基线监控统计信息
const silverStats = this.silverBaselineMonitor.getStats();
console.log('\n========================================');
console.log('白银基线监控统计信息');
console.log('========================================');
console.log(`当前基线: ${silverStats.currentBaseline !== null ? silverStats.currentBaseline.toFixed(3) : '未初始化'}`);
console.log(`总价格记录: ${silverStats.totalPrices}`);
console.log(`总告警次数: ${silverStats.totalAlerts}`);
console.log(`上涨告警: ${silverStats.riseCount}`);
console.log(`下跌告警: ${silverStats.fallCount}`);
console.log('========================================\n');
}
}
/**
* 主函数
*/
async function main(): Promise<void> {
const app = new App();
try {
await app.init();
app.start();
// 处理退出信号
process.on('SIGINT', async () => {
console.log('\n收到退出信号...');
await app.stop();
process.exit(0);
});
process.on('SIGTERM', async () => {
console.log('\n收到终止信号...');
await app.stop();
process.exit(0);
});
// 定期显示统计信息
setInterval(() => {
app.showStats();
}, 300000); // 每 5 分钟显示一次统计信息
} catch (error) {
console.error('应用运行出错:', error);
process.exit(1);
}
}
// 启动应用
main();
+325
View File
@@ -0,0 +1,325 @@
import { promises as fs } from 'fs';
import path from 'path';
import type { Database, SilverPriceData, PriceChangeRecord, SilverBaselineDatabase, SilverBaselineData, SilverBaselineAlert, TrendAnalysisDatabase, TrendAnalysisRecord, PriceDataPoint } from '../types/index.js';
/**
* 文件数据库服务
*/
export class DatabaseService {
private dbPath: string;
private data: Database;
private silverBaselinePath: string;
private silverBaselineData: SilverBaselineDatabase;
private trendAnalysisPath: string;
private trendAnalysisData: TrendAnalysisDatabase;
constructor(dataDir: string = './src/data') {
this.dbPath = path.join(dataDir, 'prices.json');
this.data = { prices: [], changes: [] };
this.silverBaselinePath = path.join(dataDir, 'silver-baseline.json');
this.silverBaselineData = { baseline: null, prices: [], alerts: [] };
this.trendAnalysisPath = path.join(dataDir, 'silver-trends.json');
this.trendAnalysisData = { analyses: [] };
}
/**
* 初始化数据库
*/
async init(): Promise<void> {
try {
// 确保数据目录存在
const dir = path.dirname(this.dbPath);
await fs.mkdir(dir, { recursive: true });
// 尝试读取现有数据
const content = await fs.readFile(this.dbPath, 'utf-8');
this.data = JSON.parse(content);
console.log('数据库加载成功,历史记录数:', this.data.prices.length);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
// 文件不存在,创建新数据库
await this.save();
console.log('数据库初始化成功');
} else {
console.error('数据库初始化失败:', error);
throw error;
}
}
// 初始化白银基线数据库
await this.loadSilverBaseline();
// 初始化趋势分析数据库
await this.loadTrendAnalysis();
}
/**
* 加载白银基线数据
*/
async loadSilverBaseline(): Promise<void> {
try {
const content = await fs.readFile(this.silverBaselinePath, 'utf-8');
this.silverBaselineData = JSON.parse(content);
console.log('白银基线数据加载成功,基线值:', this.silverBaselineData.baseline);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
// 文件不存在,创建新数据库
await this.saveSilverBaseline();
console.log('白银基线数据库初始化成功');
} else {
console.error('白银基线数据加载失败:', error);
throw error;
}
}
}
/**
* 保存白银基线数据到文件
*/
async saveSilverBaseline(): Promise<void> {
try {
await fs.writeFile(this.silverBaselinePath, JSON.stringify(this.silverBaselineData, null, 2), 'utf-8');
} catch (error) {
console.error('白银基线数据保存失败:', error);
throw error;
}
}
/**
* 保存数据到文件
*/
private async save(): Promise<void> {
try {
await fs.writeFile(this.dbPath, JSON.stringify(this.data, null, 2), 'utf-8');
} catch (error) {
console.error('数据库保存失败:', error);
throw error;
}
}
/**
* 添加价格记录
*/
async addPrice(price: SilverPriceData): Promise<void> {
this.data.prices.push(price);
await this.save();
}
/**
* 添加价格变化记录
*/
async addPriceChange(change: PriceChangeRecord): Promise<void> {
this.data.changes.push(change);
await this.save();
}
/**
* 获取最新的一条价格记录
*/
getLatestPrice(): SilverPriceData | null {
if (this.data.prices.length === 0) {
return null;
}
return this.data.prices[this.data.prices.length - 1];
}
/**
* 获取所有价格记录
*/
getAllPrices(): SilverPriceData[] {
return this.data.prices;
}
/**
* 获取所有变化记录
*/
getAllChanges(): PriceChangeRecord[] {
return this.data.changes;
}
/**
* 获取最近的变化记录
*/
getRecentChanges(count: number = 10): PriceChangeRecord[] {
return this.data.changes.slice(-count);
}
/**
* 清理旧数据(保留最近的 N 条记录)
*/
async cleanOldData(keepCount: number = 1000): Promise<void> {
if (this.data.prices.length > keepCount) {
this.data.prices = this.data.prices.slice(-keepCount);
await this.save();
console.log(`已清理旧数据,保留最近 ${keepCount} 条记录`);
}
}
/**
* 获取统计信息
*/
getStats(): { totalPrices: number; totalChanges: number; riseCount: number; fallCount: number } {
const riseCount = this.data.changes.filter(c => c.changeType === 'RISE').length;
const fallCount = this.data.changes.filter(c => c.changeType === 'FALL').length;
return {
totalPrices: this.data.prices.length,
totalChanges: this.data.changes.length,
riseCount,
fallCount
};
}
/**
* 添加白银价格记录
*/
async addSilverPrice(priceData: SilverBaselineData): Promise<void> {
this.silverBaselineData.prices.push(priceData);
await this.saveSilverBaseline();
}
/**
* 更新白银基线值
*/
async updateSilverBaseline(baseline: number): Promise<void> {
this.silverBaselineData.baseline = baseline;
await this.saveSilverBaseline();
}
/**
* 获取当前白银基线值
*/
getSilverBaseline(): number | null {
return this.silverBaselineData.baseline;
}
/**
* 添加白银基线告警记录
*/
async addSilverBaselineAlert(alert: SilverBaselineAlert): Promise<void> {
this.silverBaselineData.alerts.push(alert);
await this.saveSilverBaseline();
}
/**
* 获取白银基线统计信息
*/
getSilverBaselineStats(): { totalPrices: number; totalAlerts: number; riseCount: number; fallCount: number } {
const riseCount = this.silverBaselineData.alerts.filter(a => a.type === 'RISE').length;
const fallCount = this.silverBaselineData.alerts.filter(a => a.type === 'FALL').length;
return {
totalPrices: this.silverBaselineData.prices.length,
totalAlerts: this.silverBaselineData.alerts.length,
riseCount,
fallCount
};
}
/**
* 加载趋势分析数据
*/
async loadTrendAnalysis(): Promise<void> {
try {
const content = await fs.readFile(this.trendAnalysisPath, 'utf-8');
this.trendAnalysisData = JSON.parse(content);
console.log('趋势分析数据加载成功,分析记录数:', this.trendAnalysisData.analyses.length);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
// 文件不存在,创建新数据库
await this.saveTrendAnalysis();
console.log('趋势分析数据库初始化成功');
} else {
console.error('趋势分析数据加载失败:', error);
// 使用空数据结构继续运行
this.trendAnalysisData = { analyses: [] };
}
}
}
/**
* 保存趋势分析数据到文件
*/
async saveTrendAnalysis(): Promise<void> {
try {
await fs.writeFile(this.trendAnalysisPath, JSON.stringify(this.trendAnalysisData, null, 2), 'utf-8');
} catch (error) {
console.error('趋势分析数据保存失败:', error);
throw error;
}
}
/**
* 添加趋势分析记录
*/
async addTrendAnalysis(record: TrendAnalysisRecord): Promise<void> {
this.trendAnalysisData.analyses.push(record);
// 保留最多 1000 条记录
if (this.trendAnalysisData.analyses.length > 1000) {
this.trendAnalysisData.analyses = this.trendAnalysisData.analyses.slice(-1000);
}
await this.saveTrendAnalysis();
}
/**
* 获取最近的价格数据点
* @param count 数据点数量,默认 30 个
* @returns 价格数据点数组
*/
getRecentPricePoints(count: number = 30): PriceDataPoint[] {
// 从白银基线数据中获取最近的价格记录
const recentPrices = this.silverBaselineData.prices.slice(-count);
// 转换为 PriceDataPoint 格式
const dataPoints: PriceDataPoint[] = [];
for (let i = 0; i < recentPrices.length; i++) {
const current = recentPrices[i];
const changeFromPrevious = i > 0
? current.currentPrice - recentPrices[i - 1].currentPrice
: undefined;
// 计算波动率(使用最近5个点)
let volatility: number | undefined;
if (i >= 4) {
const prices = recentPrices.slice(i - 4, i + 1).map(p => p.currentPrice);
const mean = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const variance = prices.reduce((sum, p) => sum + Math.pow(p - mean, 2), 0) / prices.length;
volatility = Math.sqrt(variance) / mean;
}
dataPoints.push({
price: current.currentPrice,
timestamp: current.timestamp,
changeFromPrevious,
volatility
});
}
return dataPoints;
}
/**
* 获取最近一次趋势分析记录
*/
getLatestTrendAnalysis(): TrendAnalysisRecord | null {
if (this.trendAnalysisData.analyses.length === 0) {
return null;
}
return this.trendAnalysisData.analyses[this.trendAnalysisData.analyses.length - 1];
}
/**
* 获取最近 N 次已触发告警的分析记录
* @param count 获取的记录数量
* @returns 已触发告警的分析记录数组(按时间倒序)
*/
getRecentTriggeredAnalyses(count: number): TrendAnalysisRecord[] {
if (count <= 0) {
return [];
}
return this.trendAnalysisData.analyses
.filter(record => record.triggered === true)
.slice(-count)
.reverse();
}
}
+233
View File
@@ -0,0 +1,233 @@
import type { SilverPriceData, MonitorResult, PriceChangeRecord, MonitorConfig } from '../types/index.js';
import { DatabaseService } from './database.js';
import type { AlertService } from '../utils/alert.js';
/**
* 监控服务 - 核心监控逻辑
*/
export class MonitorService {
private db: DatabaseService;
private config: MonitorConfig;
private alertService?: AlertService;
private runCount: number = 0; // 执行次数计数器
private lastSummaryRunCount: number = 0; // 上次发送汇总时的执行次数
constructor(db: DatabaseService, config: MonitorConfig, alertService?: AlertService) {
this.db = db;
this.config = config;
this.alertService = alertService;
}
/**
* 分析价格变化(核心监控逻辑)
*
* 规则:
* - 美白银 < 伦敦银 变成 美白银 > 伦敦银 = 要跌 (价差从负变正)
* - 美白银 > 伦敦银 变成 美白银 < 伦敦银 = 要涨 (价差从正变负)
*/
async analyzePriceChange(currentPrice: SilverPriceData): Promise<MonitorResult> {
const latestPrice = this.db.getLatestPrice();
const result: MonitorResult = {
triggered: false,
currentSpread: currentPrice.spread,
prevSpread: latestPrice?.spread ?? 0,
usSilver: currentPrice.usSilver,
londonSilver: currentPrice.londonSilver,
timestamp: currentPrice.timestamp
};
// 如果没有历史数据,仅保存当前价格
if (!latestPrice) {
console.log('首次获取价格数据,无历史对比');
return result;
}
const wasUsAboveLondon = latestPrice.spread > 0;
const isUsAboveLondon = currentPrice.spread > 0;
// 检查是否发生价差方向变化
if (wasUsAboveLondon !== isUsAboveLondon) {
result.triggered = true;
if (isUsAboveLondon) {
// 美白银从小于变成大于 = 要跌
result.changeType = 'FALL';
console.log(`⚠️ 触发下跌信号: 美白银(${currentPrice.usSilver}) > 伦敦银(${currentPrice.londonSilver})`);
} else {
// 美白银从大于变成小于 = 要涨
result.changeType = 'RISE';
console.log(`⚠️ 触发上涨信号: 美白银(${currentPrice.usSilver}) < 伦敦银(${currentPrice.londonSilver})`);
}
// 保存变化记录
const changeRecord: PriceChangeRecord = {
timestamp: currentPrice.timestamp,
prevSpread: latestPrice.spread,
currentSpread: currentPrice.spread,
changeType: result.changeType,
usSilver: currentPrice.usSilver,
londonSilver: currentPrice.londonSilver
};
await this.db.addPriceChange(changeRecord);
} else {
console.log(`价差未发生方向变化: 当前价差=${currentPrice.spread.toFixed(3)}`);
}
return result;
}
/**
* 处理价格数据并执行监控
*/
async processPrice(price: SilverPriceData): Promise<void> {
try {
// 先分析价格变化(在保存之前)
const result = await this.analyzePriceChange(price);
// 保存价格数据
await this.db.addPrice(price);
// 如果触发规则且启用了告警
if (result.triggered && this.config.enableAlert && this.config.alertCallback) {
await this.config.alertCallback(result);
}
// 增加执行计数
this.runCount++;
// 检查是否需要发送汇总报告(每120次,即每2小时)
if (this.runCount > 0 && this.runCount % 120 === 0) {
await this.sendSummaryReport();
}
} catch (error) {
console.error('处理价格数据失败:', error);
throw error;
}
}
/**
* 发送汇总报告到飞书
*/
private async sendSummaryReport(): Promise<void> {
try {
const stats = this.db.getStats();
const latestPrice = this.db.getLatestPrice();
const recentChanges = this.db.getRecentChanges(10);
console.log('\n========================================');
console.log(`📊 发送每2小时汇总报告 (第 ${this.runCount} 次执行)`);
console.log('========================================\n');
if (this.alertService && process.env.WEBHOOK_URL) {
await this.alertService.sendFeishuSummary(
process.env.WEBHOOK_URL,
{
runCount: this.runCount - this.lastSummaryRunCount,
totalPrices: stats.totalPrices,
totalChanges: stats.totalChanges,
riseCount: stats.riseCount,
fallCount: stats.fallCount,
currentPrice: latestPrice ? {
usSilver: latestPrice.usSilver.toString(),
londonSilver: latestPrice.londonSilver.toString(),
spread: latestPrice.spread
} : undefined,
recentChanges: recentChanges.map(c => ({
timestamp: new Date(c.timestamp).getTime(),
changeType: c.changeType,
currentSpread: c.currentSpread
}))
}
);
this.lastSummaryRunCount = this.runCount;
} else {
console.log('⚠️ 未配置 Webhook,跳过汇总报告发送');
}
} catch (error) {
console.error('发送汇总报告失败:', error);
}
}
/**
* 获取监控统计信息
*/
getStats(): { totalPrices: number; totalChanges: number; riseCount: number; fallCount: number } {
return this.db.getStats();
}
/**
* 获取最近的变化记录
*/
getRecentChanges(count: number = 10): any[] {
return this.db.getRecentChanges(count);
}
/**
* 格式化监控结果为可读消息
*/
formatMonitorResult(result: MonitorResult): string {
if (!result.triggered || !result.changeType) {
return `价格更新: 美白银=${result.usSilver}, 伦敦银=${result.londonSilver}, 价差=${result.currentSpread.toFixed(3)}`;
}
const direction = result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌';
const changeDesc = result.changeType === 'RISE'
? '美白银从大于伦敦银变为小于伦敦银'
: '美白银从小于伦敦银变为大于伦敦银';
return `
${direction}信号触发!
时间: ${new Date(result.timestamp).toLocaleString('zh-CN')}
${changeDesc}
美白银: ${result.usSilver}
伦敦银: ${result.londonSilver}
当前价差: ${result.currentSpread.toFixed(3)}
前次价差: ${result.prevSpread.toFixed(3)}
`.trim();
}
/**
* 启动监控(定时执行)
*/
startMonitor(
fetchFn: () => Promise<SilverPriceData | null>,
signal?: AbortSignal
): void {
const monitor = async () => {
try {
console.log(`\n${new Date().toLocaleString('zh-CN')} - 开始监控...`);
const price = await fetchFn();
if (price) {
console.log(`获取价格成功: 美白银=${price.usSilver}, 伦敦银=${price.londonSilver}, 价差=${price.spread.toFixed(3)}`);
await this.processPrice(price);
} else {
console.error('获取价格失败');
}
// 显示统计信息
const stats = this.getStats();
console.log(`统计: 总价格记录=${stats.totalPrices}, 总变化=${stats.totalChanges}, 上涨=${stats.riseCount}, 下跌=${stats.fallCount}`);
} catch (error) {
console.error('监控执行出错:', error);
}
};
// 立即执行一次
monitor();
// 设置定时执行
const intervalId = setInterval(monitor, this.config.interval);
// 如果提供了 AbortSignal,在取消时停止监控
if (signal) {
signal.addEventListener('abort', () => {
clearInterval(intervalId);
console.log('监控已停止');
});
}
}
}
+317
View File
@@ -0,0 +1,317 @@
import { chromium, type Browser, type Page } from 'playwright';
import type { MetalPrice, SilverPriceData } from '../types/index.js';
const TARGET_URL = 'https://i.jzj9999.com/quoteh5/';
/**
* 爬虫服务 - 获取贵金属价格数据
*/
export class ScraperService {
private browser: Browser | null = null;
private page: Page | null = null;
private isNavigating: boolean = false; // 导航锁
/**
* 初始化浏览器
*/
async init(): Promise<void> {
try {
this.browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
this.page = await this.browser.newPage();
console.log('浏览器初始化成功');
} catch (error) {
console.error('浏览器初始化失败:', error);
throw error;
}
}
/**
* 获取页面快照并提取价格数据
*/
async fetchPrices(): Promise<Map<string, MetalPrice>> {
if (!this.page) {
throw new Error('浏览器未初始化');
}
try {
// 导航到目标页面
await this.page.goto(TARGET_URL, { waitUntil: 'networkidle', timeout: 30000 });
// 获取当前时间
const timestamp = new Date().toISOString();
// 使用 Playwright 的 locator API 提取价格数据
// 页面结构:所有商品行都在 e19 下
const priceRows = await this.page.locator('div.e19 > div.generic').all();
const prices = new Map<string, MetalPrice>();
for (const row of priceRows) {
try {
// 获取商品名称(第一个generic元素)
const nameEl = row.locator('> div > div').nth(0);
const name = await nameEl.textContent();
const trimmedName = name?.trim();
if (!trimmedName) continue;
// 获取回购价格(第二个generic元素)
const buyPriceEl = row.locator('> div > div').nth(1);
const buyPriceStr = await buyPriceEl.textContent();
const buyPrice = buyPriceStr ? parseFloat(buyPriceStr.trim().replace(/,/g, '')) : 0;
// 获取销售价格(第三个generic元素)
const sellPriceEl = row.locator('> div > div').nth(2);
const sellPriceStr = await sellPriceEl.textContent();
const sellPrice = sellPriceStr ? parseFloat(sellPriceStr.trim().replace(/,/g, '')) : 0;
// 获取最高价和最低价(在第二列中)
const highPriceEl = row.locator('> div').nth(1).locator('> div').nth(0);
const highPriceStr = await highPriceEl.textContent();
const high = highPriceStr ? parseFloat(highPriceStr.trim().replace(/,/g, '')) : 0;
const lowPriceEl = row.locator('> div').nth(1).locator('> div').nth(1);
const lowPriceStr = await lowPriceEl.textContent();
const low = lowPriceStr ? parseFloat(lowPriceStr.trim().replace(/,/g, '')) : 0;
if (trimmedName && !isNaN(buyPrice)) {
prices.set(trimmedName, {
name: trimmedName,
buyPrice,
sellPrice,
high,
low,
timestamp
});
}
} catch (err) {
// 跳过无法解析的行
continue;
}
}
return prices;
} catch (error) {
console.error('获取价格数据失败:', error);
throw error;
}
}
/**
* 导航到目标页面(如果尚未导航)
*/
private async ensurePageLoaded(): Promise<void> {
if (!this.page) {
throw new Error('浏览器未初始化');
}
// 如果正在导航,等待完成
if (this.isNavigating) {
// 等待导航完成(最多等待5秒)
let waitCount = 0;
while (this.isNavigating && waitCount < 50) {
await new Promise(resolve => setTimeout(resolve, 100));
waitCount++;
}
return;
}
try {
this.isNavigating = true;
const currentUrl = this.page.url();
// 如果页面未加载或URL不匹配,则导航
if (currentUrl === 'about:blank' || !currentUrl.includes('jzj9999.com')) {
await this.page.goto(TARGET_URL, { waitUntil: 'networkidle', timeout: 30000 });
} else {
// 页面已加载,刷新数据
await this.page.reload({ waitUntil: 'networkidle', timeout: 30000 });
}
} catch (error) {
console.error('页面加载失败:', error);
throw error;
} finally {
this.isNavigating = false;
}
}
/**
* 获取白银价格数据(美白银和伦敦银)
*/
async fetchSilverPrices(): Promise<SilverPriceData | null> {
if (!this.page) {
throw new Error('浏览器未初始化');
}
try {
// 确保页面已加载
await this.ensurePageLoaded();
// 使用 JavaScript 直接提取价格数据
const prices = await this.page.evaluate(`
(() => {
function getSellPrice(symbolName) {
const xpath = "//span[contains(text(), '" + symbolName + "')]";
const span = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!span) return null;
let container = span.parentElement;
for (let i = 0; i < 10; i++) {
if (!container) break;
const allElements = container.querySelectorAll('*');
const prices = [];
for (let j = 0; j < allElements.length; j++) {
const el = allElements[j];
const text = el.textContent ? el.textContent.trim() : '';
if (text && /^\\d+\\.?\\d*$/.test(text.replace(/,/g, ''))) {
const num = parseFloat(text.replace(/,/g, ''));
if (!isNaN(num) && num > 0 && num < 100000) {
prices.push(num);
}
}
}
if (prices.length >= 2) {
const uniquePrices = Array.from(new Set(prices)).sort((a, b) => a - b);
return uniquePrices.length >= 2 ? uniquePrices[1] : uniquePrices[0];
}
container = container.parentElement;
}
return null;
}
return {
usSilver: getSellPrice('美白银'),
londonSilver: getSellPrice('伦敦银')
};
})()
`);
const usSilver = (prices as any).usSilver;
const londonSilver = (prices as any).londonSilver;
if (!usSilver || !londonSilver) {
console.error('未能获取到白银价格数据');
console.log('获取到的价格: 美白银=', usSilver, ', 伦敦银=', londonSilver);
return null;
}
// 计算价差
const spread = usSilver - londonSilver;
return {
usSilver,
londonSilver,
spread,
timestamp: new Date().toISOString()
};
} catch (error) {
console.error('获取白银价格失败:', error);
return null;
}
}
/**
* 获取白银价格数据(用于基线监控)
*/
async fetchSilverPrice(): Promise<MetalPrice | null> {
if (!this.page) {
throw new Error('浏览器未初始化');
}
try {
// 确保页面已加载
await this.ensurePageLoaded();
// 获取当前时间
const timestamp = new Date().toISOString();
// 使用新的页面结构:div.price-table-row
const priceRows = await this.page.locator('div.price-table-row').all();
for (const row of priceRows) {
try {
// 获取商品名称(在 span.symbol-name 中)
const nameEl = row.locator('span.symbol-name');
const name = await nameEl.textContent();
const trimmedName = name?.trim().replace(/\s+/g, ''); // 移除所有空格
// 查找"白银"商品(注意页面上可能是"白 银")
if (trimmedName === '白银') {
// 获取所有价格列(在 el-col 中)
const priceCols = await row.locator('div.el-col').all();
if (priceCols.length >= 4) {
// 第2列:回购价格
const buyPriceStr = await priceCols[1].textContent();
const buyPrice = buyPriceStr ? parseFloat(buyPriceStr.trim().replace(/,/g, '')) : 0;
// 第3列:销售价格
const sellPriceStr = await priceCols[2].textContent();
const sellPrice = sellPriceStr ? parseFloat(sellPriceStr.trim().replace(/,/g, '')) : 0;
// 第4列:最高价
const highPriceStr = await priceCols[3].textContent();
const high = highPriceStr ? parseFloat(highPriceStr.trim().replace(/,/g, '')) : 0;
// 第5列:最低价(如果有)
const low = priceCols.length >= 5 ? parseFloat((await priceCols[4].textContent())?.trim().replace(/,/g, '') || '0') : 0;
if (!isNaN(sellPrice) && sellPrice > 0) {
console.log(`✅ 找到白银价格: 销售=${sellPrice}, 回购=${buyPrice}, 高=${high}, 低=${low}`);
return {
name: '白银',
buyPrice,
sellPrice,
high,
low,
timestamp
};
}
}
}
} catch (err) {
// 跳过无法解析的行
continue;
}
}
console.error('未能找到"白银"商品');
return null;
} catch (error) {
console.error('获取白银价格失败:', error);
return null;
}
}
/**
* 关闭浏览器
*/
async close(): Promise<void> {
if (this.browser) {
await this.browser.close();
this.browser = null;
this.page = null;
console.log('浏览器已关闭');
}
}
/**
* 获取所有贵金属价格(用于调试)
*/
async debugFetchAllPrices(): Promise<void> {
const prices = await this.fetchPrices();
console.log('\n========== 所有贵金属价格 ==========');
for (const [name, price] of prices.entries()) {
console.log(`${name}: 回购=${price.buyPrice}, 销售=${price.sellPrice}, 高=${price.high}, 低=${price.low}`);
}
console.log('====================================\n');
}
}
+138
View File
@@ -0,0 +1,138 @@
import type { MetalPrice, SilverBaselineData, SilverBaselineAlert } from '../types/index.js';
import { DatabaseService } from './database.js';
import type { AlertService } from '../utils/alert.js';
/**
* 白银基线监控服务
*/
export class SilverBaselineMonitor {
private db: DatabaseService;
private alertService?: AlertService;
private threshold: number;
private webhookUrl?: string;
constructor(db: DatabaseService, threshold: number = 0.2, alertService?: AlertService, webhookUrl?: string) {
this.db = db;
this.threshold = threshold;
this.alertService = alertService;
this.webhookUrl = webhookUrl;
}
/**
* 处理白银价格并执行监控
*/
async processPrice(silverPrice: MetalPrice): Promise<void> {
try {
const currentPrice = silverPrice.sellPrice;
const timestamp = silverPrice.timestamp;
// 获取当前基线
let baseline = this.db.getSilverBaseline();
// 如果没有基线,初始化基线
if (baseline === null) {
await this.initializeBaseline(currentPrice, timestamp);
return;
}
// 保存价格记录
const priceData: SilverBaselineData = {
currentPrice,
baseline,
timestamp
};
await this.db.addSilverPrice(priceData);
// 检查是否触发告警
const priceDiff = currentPrice - baseline;
const absDiff = Math.abs(priceDiff);
if (absDiff >= this.threshold) {
// 触发告警
const alertType = priceDiff > 0 ? 'RISE' : 'FALL';
const changePercent = (priceDiff / baseline) * 100;
const alert: SilverBaselineAlert = {
type: alertType,
currentPrice,
baseline,
change: priceDiff,
changePercent,
timestamp
};
console.log(`\n⚠️ 白银价格${alertType === 'RISE' ? '上涨' : '下跌'}告警触发!`);
console.log(`当前价格: ${currentPrice}`);
console.log(`基线价格: ${baseline}`);
console.log(`价格变化: ${priceDiff > 0 ? '+' : ''}${priceDiff.toFixed(3)} (${changePercent > 0 ? '+' : ''}${changePercent.toFixed(2)}%)`);
// 保存告警记录
await this.db.addSilverBaselineAlert(alert);
// 发送飞书告警
if (this.alertService && this.webhookUrl) {
await this.sendFeishuAlert(alert);
}
// 立即更新基线
await this.updateBaseline(currentPrice, timestamp);
} else {
console.log(`白银价格监控: 当前=${currentPrice}, 基线=${baseline}, 差值=${priceDiff.toFixed(3)} (未超过阈值 ${this.threshold})`);
}
} catch (error) {
console.error('白银基线监控处理失败:', error);
throw error;
}
}
/**
* 初始化基线
*/
private async initializeBaseline(price: number, timestamp: string): Promise<void> {
console.log(`\n📊 初始化白银价格基线: ${price}`);
await this.db.updateSilverBaseline(price);
// 保存初始价格记录
const priceData: SilverBaselineData = {
currentPrice: price,
baseline: price,
timestamp
};
await this.db.addSilverPrice(priceData);
}
/**
* 更新基线
*/
private async updateBaseline(newBaseline: number, timestamp: string): Promise<void> {
console.log(`\n🔄 更新白银价格基线: ${this.db.getSilverBaseline()} -> ${newBaseline}`);
await this.db.updateSilverBaseline(newBaseline);
}
/**
* 发送飞书告警
*/
private async sendFeishuAlert(alert: SilverBaselineAlert): Promise<void> {
if (!this.alertService || !this.webhookUrl) {
return;
}
try {
await this.alertService.sendSilverBaselineAlert(this.webhookUrl, alert);
console.log('✅ 飞书告警发送成功');
} catch (error) {
console.error('❌ 飞书告警发送失败:', error);
}
}
/**
* 获取统计信息
*/
getStats(): { totalPrices: number; totalAlerts: number; riseCount: number; fallCount: number; currentBaseline: number | null } {
const stats = this.db.getSilverBaselineStats();
return {
...stats,
currentBaseline: this.db.getSilverBaseline()
};
}
}
+281
View File
@@ -0,0 +1,281 @@
import { v4 as uuidv4 } from 'uuid';
import type { DatabaseService } from './database.js';
import type { AlertService } from '../utils/alert.js';
import type { LLMClient } from '../utils/llm-client.js';
import type { TrendAnalysisResponse, TrendAnalysisRecord, PriceDataPoint } from '../types/index.js';
/**
* 白银趋势分析服务
* 使用 LLM 总结价格趋势并触发告警
*/
export class SilverTrendAnalyzer {
private db: DatabaseService;
private alertService?: AlertService;
private llmClient: LLMClient;
private webhookUrl?: string;
constructor(
db: DatabaseService,
alertService: AlertService | undefined,
llmClient: LLMClient,
webhookUrl?: string
) {
this.db = db;
this.alertService = alertService;
this.llmClient = llmClient;
this.webhookUrl = webhookUrl;
}
/**
* 分析价格趋势
*/
async analyzeTrend(): Promise<TrendAnalysisRecord | null> {
try {
console.log('\n========================================');
console.log('开始 LLM 趋势总结');
// 准备分析数据
const dataPoints = this.prepareAnalysisData();
if (dataPoints.length < 5) {
console.log(`历史数据不足(${dataPoints.length} 个数据点),跳过趋势总结`);
return null;
}
console.log(`使用 ${dataPoints.length} 个数据点进行趋势分析`);
// 获取历史告警记录
const historyAlerts = this.db.getRecentTriggeredAnalyses(3);
console.log(`获取到 ${historyAlerts.length} 条历史告警记录`);
// 调用 LLM API(包含历史上下文)
console.log('调用 LLM API(包含历史告警上下文)');
const llmResponse = await this.llmClient.analyzeTrendWithHistory(dataPoints, historyAlerts);
console.log(`LLM 响应成功`);
console.log(` 趋势: ${llmResponse.trend}`);
console.log(` 置信度: ${(llmResponse.confidence * 100).toFixed(0)}%`);
console.log(` 风险: ${llmResponse.risk}`);
console.log(` 通知决策: ${llmResponse.shouldNotify ? '发送' : '跳过'}`);
console.log(` 决策原因: ${llmResponse.notifyReason}`);
// 判断是否需要告警(现有逻辑)
const previousAnalysis = this.db.getLatestTrendAnalysis();
const shouldAlert = this.shouldTriggerAlert(llmResponse, previousAnalysis, dataPoints);
// 创建分析记录
const record: TrendAnalysisRecord = {
id: uuidv4(),
timestamp: new Date().toISOString(),
dataPoints,
trend: llmResponse.trend,
confidence: llmResponse.confidence,
summary: llmResponse.summary,
signals: llmResponse.signals,
risk: llmResponse.risk,
triggered: shouldAlert && llmResponse.shouldNotify, // 同时满足两个条件
llmResponseRaw: JSON.stringify(llmResponse),
shouldNotify: llmResponse.shouldNotify,
notifyReason: llmResponse.notifyReason
};
// 保存分析记录
await this.db.addTrendAnalysis(record);
// 发送告警(需要同时满足触发条件和通知决策)
if (shouldAlert) {
if (llmResponse.shouldNotify) {
console.log('⚠️ 触发趋势告警!');
await this.sendTrendAlert(record);
} else {
console.log(`⏭️ 满足告警条件但跳过通知: ${llmResponse.notifyReason}`);
}
} else {
console.log(`趋势总结完成: ${llmResponse.trend},置信度 ${(llmResponse.confidence * 100).toFixed(0)}%,风险 ${llmResponse.risk}`);
}
console.log('========================================\n');
return record;
} catch (error) {
console.error('趋势总结执行出错:', error);
return null;
}
}
/**
* 准备分析数据
*/
private prepareAnalysisData(): PriceDataPoint[] {
return this.db.getRecentPricePoints(30);
}
/**
* 计算最近 N 个数据点的价格波动幅度
* @param dataPoints 价格数据点
* @param count 计算最近的几个点(默认10个,即10分钟)
* @returns 最大波动幅度
*/
private calculatePriceRange(dataPoints: PriceDataPoint[], count: number = 10): number {
const recentPoints = dataPoints.slice(-count);
if (recentPoints.length < 2) return 0;
const prices = recentPoints.map(p => p.price);
const maxPrice = Math.max(...prices);
const minPrice = Math.min(...prices);
return maxPrice - minPrice;
}
/**
* 判断是否应该触发告警
*/
private shouldTriggerAlert(
current: TrendAnalysisResponse,
previous?: TrendAnalysisRecord | null,
dataPoints?: PriceDataPoint[]
): boolean {
// 条件 1:趋势反转
if (previous) {
const trendReversals = [
{ from: 'uptrend', to: 'downtrend' },
{ from: 'downtrend', to: 'uptrend' }
];
if (trendReversals.some(tr => tr.from === previous.trend && tr.to === current.trend)) {
if (previous.confidence > 0.6 && current.confidence > 0.6) {
console.log(' → 检测到趋势反转');
return true;
}
}
}
// 条件 2:剧烈波动(需要同时满足:LLM判断为volatile 且 实际波动幅度 > 0.2)
if (current.trend === 'volatile' && current.confidence > 0.7) {
if (dataPoints) {
const priceRange = this.calculatePriceRange(dataPoints, 10); // 计算最近10分钟的波动
console.log(` → 最近10分钟价格波动幅度: ${priceRange.toFixed(3)}`);
if (priceRange > 0.2) {
console.log(' → 检测到价格剧烈波动(幅度 > 0.2)');
return true;
} else {
console.log(' → 波动幅度未达到阈值(0.2),不触发告警');
}
} else {
// 如果没有dataPoints,则只依赖LLM判断
console.log(' → 检测到价格剧烈波动(基于LLM判断)');
return true;
}
}
// 条件 3:高风险 + 高置信度
if (current.risk === 'high' && current.confidence > 0.8) {
console.log(' → 检测到高风险信号');
return true;
}
return false;
}
/**
* 发送趋势告警
*/
private async sendTrendAlert(record: TrendAnalysisRecord): Promise<void> {
if (!this.alertService || !this.webhookUrl) {
console.log('未配置 Webhook URL,跳过飞书告警');
return;
}
try {
// 构建飞书卡片消息
const card = this.buildFeishuCard(record);
// 发送 Webhook
const response = await fetch(this.webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(card)
});
if (!response.ok) {
throw new Error(`Webhook 调用失败: ${response.status} ${response.statusText}`);
}
console.log('✅ 飞书告警发送成功');
} catch (error) {
console.error('飞书告警发送失败:', error);
}
}
/**
* 构建飞书卡片消息
*/
private buildFeishuCard(record: TrendAnalysisRecord): any {
// 趋势标签映射
const trendLabels = {
uptrend: '📈 上涨趋势',
downtrend: '📉 下跌趋势',
sideways: '➡️ 平稳波动',
volatile: '📊 剧烈波动'
};
// 风险标签映射
const riskConfig = {
low: { label: '低风险', color: 'green' },
medium: { label: '中等风险', color: 'yellow' },
high: { label: '高风险', color: 'red' }
};
const riskInfo = riskConfig[record.risk];
const confidencePercent = Math.round(record.confidence * 100);
return {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: '🤖 LLM 趋势总结告警'
},
template: record.risk === 'high' ? 'red' : 'yellow'
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**趋势类型**:${trendLabels[record.trend]}\n`
}
},
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**趋势总结**:${record.summary}\n`
}
},
{
tag: 'div',
text: {
tag: 'lark_md',
content: '**关键信号**:\n' + record.signals.map(s => `- ${s}`).join('\n')
}
},
{
tag: 'hr'
},
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**风险评估**:<font color='${riskInfo.color}'>${riskInfo.label}</font>\n**置信度**:${confidencePercent}%\n**分析时间**:${new Date(record.timestamp).toLocaleString('zh-CN')}`
}
}
]
}
};
}
}
+221
View File
@@ -0,0 +1,221 @@
/**
* 贵金属价格数据
*/
export interface MetalPrice {
/** 商品名称 */
name: string;
/** 回购价格 */
buyPrice: number;
/** 销售价格 */
sellPrice: number;
/** 最高价 */
high: number;
/** 最低价 */
low: number;
/** 更新时间 */
timestamp: string;
}
/**
* 白银价格数据(用于监控)
*/
export interface SilverPriceData {
/** 美白银价格 */
usSilver: number;
/** 伦敦银价格 */
londonSilver: number;
/** 价差 (美白银 - 伦敦银) */
spread: number;
/** 更新时间 */
timestamp: string;
}
/**
* 价格变化记录
*/
export interface PriceChangeRecord {
/** 时间戳 */
timestamp: string;
/** 变化前的价差 */
prevSpread: number;
/** 变化后的价差 */
currentSpread: number;
/** 变化类型: RISE(涨) 或 FALL(跌) */
changeType: 'RISE' | 'FALL';
/** 美白银价格 */
usSilver: number;
/** 伦敦银价格 */
londonSilver: number;
}
/**
* 监控规则结果
*/
export interface MonitorResult {
/** 是否触发规则 */
triggered: boolean;
/** 变化类型 */
changeType?: 'RISE' | 'FALL';
/** 当前价差 */
currentSpread: number;
/** 前一次价差 */
prevSpread: number;
/** 美白银价格 */
usSilver: number;
/** 伦敦银价格 */
londonSilver: number;
/** 时间 */
timestamp: string;
}
/**
* 数据库结构
*/
export interface Database {
/** 历史价格数据 */
prices: SilverPriceData[];
/** 变化记录 */
changes: PriceChangeRecord[];
}
/**
* 监控配置
*/
export interface MonitorConfig {
/** 监控间隔(毫秒) */
interval: number;
/** 是否启用告警 */
enableAlert: boolean;
/** 告警回调函数 */
alertCallback?: (result: MonitorResult) => void | Promise<void>;
}
/**
* 白银基线数据
*/
export interface SilverBaselineData {
/** 当前价格 */
currentPrice: number;
/** 基线价格 */
baseline: number;
/** 更新时间 */
timestamp: string;
}
/**
* 白银基线告警信息
*/
export interface SilverBaselineAlert {
/** 告警类型: RISE(上涨) 或 FALL(下跌) */
type: 'RISE' | 'FALL';
/** 当前价格 */
currentPrice: number;
/** 基线价格 */
baseline: number;
/** 价格变化量 */
change: number;
/** 变化百分比 */
changePercent: number;
/** 时间戳 */
timestamp: string;
}
/**
* 白银基线数据库结构
*/
export interface SilverBaselineDatabase {
/** 当前基线值 */
baseline: number | null;
/** 历史价格记录 */
prices: SilverBaselineData[];
/** 告警记录 */
alerts: SilverBaselineAlert[];
}
/**
* 价格数据点(用于 LLM 分析)
*/
export interface PriceDataPoint {
/** 价格 */
price: number;
/** 时间戳 */
timestamp: string;
/** 相对于前一个点的变化(可选) */
changeFromPrevious?: number;
/** 波动率(可选) */
volatility?: number;
}
/**
* LLM 趋势分析记录
*/
export interface TrendAnalysisRecord {
/** 唯一标识符 */
id: string;
/** 分析时间戳 */
timestamp: string;
/** 使用的价格数据点 */
dataPoints: PriceDataPoint[];
/** 趋势类型 */
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
/** 置信度 (0-1) */
confidence: number;
/** 趋势总结 */
summary: string;
/** 关键信号列表 */
signals: string[];
/** 风险评估 */
risk: 'low' | 'medium' | 'high';
/** 是否触发了告警 */
triggered: boolean;
/** LLM 原始响应(用于调试) */
llmResponseRaw: string;
/** LLM 的通知决策(可选) */
shouldNotify?: boolean;
/** 通知决策原因(可选) */
notifyReason?: string;
}
/**
* 趋势分析数据库
*/
export interface TrendAnalysisDatabase {
/** 分析记录 */
analyses: TrendAnalysisRecord[];
}
/**
* LLM 配置
*/
export interface LLMConfig {
/** API 基础 URL */
apiBase: string;
/** API 密钥 */
apiKey: string;
/** 模型名称 */
model: string;
/** 超时时间(毫秒) */
timeout?: number;
/** 最大重试次数 */
maxRetries?: number;
}
/**
* LLM 趋势分析响应
*/
export interface TrendAnalysisResponse {
/** 趋势类型 */
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
/** 置信度 (0-1) */
confidence: number;
/** 趋势总结 */
summary: string;
/** 关键信号 */
signals: string[];
/** 风险评估 */
risk: 'low' | 'medium' | 'high';
/** 是否应该发送通知 */
shouldNotify: boolean;
/** 通知或跳过的原因 */
notifyReason: string;
}
+329
View File
@@ -0,0 +1,329 @@
import { promises as fs } from 'fs';
import path from 'path';
import type { MonitorResult, SilverBaselineAlert } from '../types/index.js';
// 加载环境变量
import 'dotenv/config';
/**
* 告警服务 - 提供多种告警方式
*/
export class AlertService {
private logFilePath: string;
constructor(logDir: string = './logs') {
this.logFilePath = path.join(logDir, 'alerts.log');
}
/**
* 初始化日志目录
*/
async init(): Promise<void> {
try {
await fs.mkdir(path.dirname(this.logFilePath), { recursive: true });
} catch (error) {
console.error('创建日志目录失败:', error);
throw error;
}
}
/**
* 控制台告警
*/
consoleAlert(result: MonitorResult): void {
console.log('\n' + '='.repeat(60));
console.log('🚨 价格变化告警!');
console.log('='.repeat(60));
console.log(`时间: ${new Date(result.timestamp).toLocaleString('zh-CN')}`);
console.log(`变化类型: ${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}`);
console.log(`美白银: ${result.usSilver}`);
console.log(`伦敦银: ${result.londonSilver}`);
console.log(`当前价差: ${result.currentSpread.toFixed(3)}`);
console.log(`前次价差: ${result.prevSpread.toFixed(3)}`);
console.log('='.repeat(60) + '\n');
}
/**
* 文件日志告警
*/
async fileAlert(result: MonitorResult): Promise<void> {
try {
const logEntry = {
timestamp: result.timestamp,
changeType: result.changeType,
usSilver: result.usSilver,
londonSilver: result.londonSilver,
currentSpread: result.currentSpread,
prevSpread: result.prevSpread
};
const logLine = JSON.stringify(logEntry) + '\n';
await fs.appendFile(this.logFilePath, logLine, 'utf-8');
console.log('告警已记录到文件:', this.logFilePath);
} catch (error) {
console.error('写入告警日志失败:', error);
}
}
/**
* Webhook 告警(可扩展用于企业微信、钉钉等)
*/
async webhookAlert(result: MonitorResult, webhookUrl: string): Promise<void> {
try {
const message = {
msg_type: 'text',
content: {
text: `🔔 价格变化告警\n⏰ 时间: ${new Date(result.timestamp).toLocaleString('zh-CN')}\n📊 变化类型: ${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}\n💰 美白银: ${result.usSilver}\n💷 伦敦银: ${result.londonSilver}\n📉 价差: ${result.currentSpread.toFixed(3)}`
}
};
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});
const responseText = await response.text();
if (response.ok) {
console.log('Webhook 告警发送成功');
} else {
console.error('Webhook 告警发送失败:');
console.error(' 状态码:', response.status, response.statusText);
console.error(' 响应:', responseText);
}
} catch (error: any) {
console.error('Webhook 告警出错:', error.message);
}
}
/**
* 飞书告警 - 使用飞书卡片消息格式
*/
async feishuAlert(result: MonitorResult, webhookUrl: string): Promise<void> {
try {
const message = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: '🔔 价格变化告警'
},
template: 'red'
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**⏰ 时间**\n${new Date(result.timestamp).toLocaleString('zh-CN')}\n\n`
+ `**📊 变化类型**\n${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}\n\n`
+ `**💰 价格信息**\n`
+ `• 美白银: ${result.usSilver}\n`
+ `• 伦敦银: ${result.londonSilver}\n`
+ `• 当前价差: ${result.currentSpread.toFixed(3)}\n`
+ `• 前次价差: ${result.prevSpread.toFixed(3)}`
}
}
]
}
};
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});
const responseText = await response.text();
if (response.ok) {
console.log('飞书告警发送成功');
} else {
console.error('飞书告警发送失败:');
console.error(' 状态码:', response.status, response.statusText);
console.error(' 响应:', responseText);
}
} catch (error: any) {
console.error('飞书告警出错:', error.message);
}
}
/**
* 发送飞书执行情况汇总(每2小时)
*/
async sendFeishuSummary(webhookUrl: string, summary: {
runCount: number;
totalPrices: number;
totalChanges: number;
riseCount: number;
fallCount: number;
currentPrice?: { usSilver: string; londonSilver: string; spread: number };
recentChanges: Array<{ timestamp: number; changeType: string; currentSpread: number }>;
}): Promise<void> {
try {
const now = new Date();
const timeRange = `${now.getHours() - 2}:00 - ${now.getHours()}:00`;
let recentChangesText = '暂无变化';
if (summary.recentChanges.length > 0) {
recentChangesText = summary.recentChanges.map(change => {
const time = new Date(change.timestamp).toLocaleTimeString('zh-CN');
const icon = change.changeType === 'RISE' ? '📈' : '📉';
return `${icon} ${time} - 价差: ${change.currentSpread.toFixed(3)}`;
}).join('\n');
}
const message = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: '📊 每2小时监控报告'
},
template: 'blue'
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**⏰ 统计时段**\n${timeRange}\n\n`
+ `**📈 运行统计**\n`
+ `• 运行次数: ${summary.runCount} 次\n`
+ `• 价格记录: ${summary.totalPrices} 条\n`
+ `• 变化次数: ${summary.totalChanges} 次\n`
+ `• 上涨信号: ${summary.riseCount} 次\n`
+ `• 下跌信号: ${summary.fallCount} 次\n\n`
+ (summary.currentPrice ? `**💰 当前价格**\n`
+ `• 美白银: ${summary.currentPrice.usSilver}\n`
+ `• 伦敦银: ${summary.currentPrice.londonSilver}\n`
+ `• 当前价差: ${summary.currentPrice.spread.toFixed(3)}\n\n` : '')
+ `**📋 最近变化**\n${recentChangesText}`
}
}
]
}
};
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});
const responseText = await response.text();
if (response.ok) {
console.log('飞书汇总报告发送成功');
} else {
console.error('飞书汇总报告发送失败:');
console.error(' 状态码:', response.status, response.statusText);
console.error(' 响应:', responseText);
}
} catch (error: any) {
console.error('发送飞书汇总报告出错:', error.message);
}
}
/**
* 发送白银基线告警到飞书
*/
async sendSilverBaselineAlert(webhookUrl: string, alert: SilverBaselineAlert): Promise<void> {
try {
const alertTypeText = alert.type === 'RISE' ? '📈 上涨' : '📉 下跌';
const alertColor = alert.type === 'RISE' ? 'green' : 'red';
const message = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: `🔔 白银价格${alertTypeText}告警`
},
template: alertColor
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: `**⏰ 时间**\n${new Date(alert.timestamp).toLocaleString('zh-CN')}\n\n`
+ `**💰 价格信息**\n`
+ `• 当前价格: ${alert.currentPrice.toFixed(3)}\n`
+ `• 基线价格: ${alert.baseline.toFixed(3)}\n`
+ `• 价格变化: ${alert.change > 0 ? '+' : ''}${alert.change.toFixed(3)}\n`
+ `• 变化百分比: ${alert.changePercent > 0 ? '+' : ''}${alert.changePercent.toFixed(2)}%\n\n`
+ `**📊 告警说明**\n`
+ `价格${alert.type === 'RISE' ? '上涨' : '下跌'}超过阈值,基线已自动更新为当前价格`
}
}
]
}
};
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});
const responseText = await response.text();
if (response.ok) {
console.log('白银基线告警发送成功');
} else {
console.error('白银基线告警发送失败:');
console.error(' 状态码:', response.status, response.statusText);
console.error(' 响应:', responseText);
}
} catch (error: any) {
console.error('发送白银基线告警出错:', error.message);
}
}
/**
* 综合告警(同时使用多种方式)
*/
async alert(result: MonitorResult, options: {
console?: boolean;
file?: boolean;
webhook?: string;
feishu?: string;
} = {}): Promise<void> {
const { console: enableConsole = true, file: enableFile = true, webhook, feishu } = options;
if (enableConsole) {
this.consoleAlert(result);
}
if (enableFile) {
await this.fileAlert(result);
}
if (webhook) {
await this.webhookAlert(result, webhook);
}
if (feishu) {
await this.feishuAlert(result, feishu);
}
}
}
/**
* 创建默认的告警回调函数
*/
export function createAlertCallback(alertService: AlertService): (result: MonitorResult) => Promise<void> {
return async (result: MonitorResult) => {
await alertService.alert(result, {
console: true,
file: true,
webhook: process.env.WEBHOOK_URL // 从环境变量读取 webhook 地址
});
};
}
+447
View File
@@ -0,0 +1,447 @@
import type { LLMConfig, TrendAnalysisResponse, PriceDataPoint, TrendAnalysisRecord } from '../types/index.js';
/**
* LLM API 客户端
* 用于调用 OpenAI 兼容的 API 进行趋势分析
*/
export class LLMClient {
private config: LLMConfig;
constructor(config: LLMConfig) {
this.config = {
timeout: 120000, // 增加到 120 秒以适应智谱AI的推理时间
maxRetries: 2,
...config
};
}
/**
* 分析价格趋势
* @param data 价格数据点
* @returns 趋势分析结果
*/
async analyzeTrend(data: PriceDataPoint[]): Promise<TrendAnalysisResponse> {
const prompt = this.buildPrompt(data);
const response = await this.callAPI(prompt);
return this.parseResponse(response);
}
/**
* 分析价格趋势(包含历史告警上下文)
* @param data 价格数据点
* @param history 历史告警记录
* @returns 趋势分析结果(包含通知决策)
*/
async analyzeTrendWithHistory(
data: PriceDataPoint[],
history: TrendAnalysisRecord[]
): Promise<TrendAnalysisResponse> {
const prompt = this.buildPromptWithHistory(data, history);
const response = await this.callAPI(prompt);
return this.parseResponseWithNotify(response);
}
/**
* 构建分析提示词
* @param data 价格数据点
* @returns Prompt 文本
*/
private buildPrompt(data: PriceDataPoint[]): string {
// 将数据格式化为文本表格
const dataText = this.formatDataPoints(data);
return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。
**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**
以下是白银最近 30 分钟的价格数据(每分钟一次):
${dataText}
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
2. 置信度:0-1 之间的数值
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势,**必须包含**:
- 当前价格(单位:元)
- 总价差(所有 30 分钟数据的最高价 - 最低价,单位:元)
- 如果是上涨趋势,说明上涨了多少元
- 如果是下跌趋势,说明下跌了多少元
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
5. 风险评估:low/medium/high
**分析要求**:
- 专注于总结已经发生的趋势,不要预测未来走势
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
- **剧烈波动判定标准**:只有当最近 10 分钟内的价格波动幅度(最高价 - 最低价)大于 0.2 时,才将 trend 设为 volatile
- 计算方法:找出最近 10 分钟内的最高价格和最低价格,计算差值
- 例如:最高 22.6,最低 22.3,波动幅度 = 0.3(> 0.2,可判定为 volatile)
- 例如:最高 22.5,最低 22.4,波动幅度 = 0.1(< 0.2,应判定为 sideways 或其他趋势)
- 如果波动幅度小于 0.2,即使价格有所波动,也应优先考虑 uptrend、downtrend 或 sideways,而非 volatile
- 关注价格变化的幅度、速度和持续性
**风险评估标准(必须严格按照以下标准判断)**:
**high(高风险)**:满足以下**任意一个**条件即可判定为 high
- 最近 10 分钟价格波动幅度 > 0.3 元
- 出现急剧反转(单分钟价格变化 > 0.3 元)
- trend = volatile 且置信度 > 0.8
- 最近 10 分钟内有 3 次或更多次波动率 > 0.8%
- 价格在创出新高/新低后立即出现大幅回调(幅度 > 0.25 元)
**medium(中等风险)**:满足以下**任意一个**条件即可判定为 medium
- 最近 10 分钟价格波动幅度在 0.15-0.3 元之间
- 出现趋势反转信号(从上涨转为下跌或反之)
- 检测到明显的阻力位或支撑位测试(价格多次触及同一价位后回调)
- 波动率在 0.4%-0.8% 之间,但未达到高风险标准
- trend = volatile 但置信度 ≤ 0.8
**low(低风险)**:同时满足以下条件才可判定为 low
- 最近 10 分钟价格波动幅度 < 0.15 元
- 趋势明确(uptrend 或 downtrend)且持续,无明显反转
- 波动率普遍 < 0.4%
- 价格走势平稳,没有异常的急剧变化
**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
{
"trend": "uptrend|downtrend|sideways|volatile",
"confidence": 0.85,
"summary": "...",
"signals": ["...", "...", "..."],
"risk": "low|medium|high"
}`;
}
/**
* 构建分析提示词(包含历史告警上下文)
* @param data 价格数据点
* @param history 历史告警记录
* @returns Prompt 文本
*/
private buildPromptWithHistory(data: PriceDataPoint[], history: TrendAnalysisRecord[]): string {
// 将数据格式化为文本表格
const dataText = this.formatDataPoints(data);
// 格式化历史告警上下文
const historyText = this.formatHistoryContext(history);
return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。
**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**
以下是白银最近 30 分钟的价格数据(每分钟一次):
${dataText}
${historyText}
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
2. 置信度:0-1 之间的数值
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势,**必须包含**:
- 当前价格(单位:元)
- 总价差(所有 30 分钟数据的最高价 - 最低价,单位:元)
- 如果是上涨趋势,说明上涨了多少元
- 如果是下跌趋势,说明下跌了多少元
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
5. 风险评估:low/medium/high
6. **通知决策**:判断是否应该发送通知(shouldNotify: true/false)
7. **通知原因**:说明为什么应该或不应该发送通知(notifyReason)
**分析要求**:
- 专注于总结已经发生的趋势,不要预测未来走势
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
- **剧烈波动判定标准**:只有当最近 10 分钟内的价格波动幅度(最高价 - 最低价)大于 0.2 时,才将 trend 设为 volatile
- 计算方法:找出最近 10 分钟内的最高价格和最低价格,计算差值
- 例如:最高 22.6,最低 22.3,波动幅度 = 0.3(> 0.2,可判定为 volatile)
- 例如:最高 22.5,最低 22.4,波动幅度 = 0.1(< 0.2,应判定为 sideways 或其他趋势)
- 如果波动幅度小于 0.2,即使价格有所波动,也应优先考虑 uptrend、downtrend 或 sideways,而非 volatile
- 关注价格变化的幅度、速度和持续性
**风险评估标准(必须严格按照以下标准判断)**:
**high(高风险)**:满足以下**任意一个**条件即可判定为 high
- 最近 10 分钟价格波动幅度 > 0.3 元
- 出现急剧反转(单分钟价格变化 > 0.3 元)
- trend = volatile 且置信度 > 0.8
- 最近 10 分钟内有 3 次或更多次波动率 > 0.8%
- 价格在创出新高/新低后立即出现大幅回调(幅度 > 0.25 元)
**medium(中等风险)**:满足以下**任意一个**条件即可判定为 medium
- 最近 10 分钟价格波动幅度在 0.15-0.3 元之间
- 出现趋势反转信号(从上涨转为下跌或反之)
- 检测到明显的阻力位或支撑位测试(价格多次触及同一价位后回调)
- 波动率在 0.4%-0.8% 之间,但未达到高风险标准
- trend = volatile 但置信度 ≤ 0.8
**low(低风险)**:同时满足以下条件才可判定为 low
- 最近 10 分钟价格波动幅度 < 0.15 元
- 趋势明确(uptrend 或 downtrend)且持续,无明显反转
- 波动率普遍 < 0.4%
- 价格走势平稳,没有异常的急剧变化
**通知决策标准**:
- 如果本次分析与最近的历史告警**高度相似**(趋势类型相同、总结内容大部分重复、信号列表高度重叠),则 shouldNotify 应为 false
- 如果出现**新的重要变化**(趋势反转、新的风险信号、波动幅度显著变化),则 shouldNotify 应为 true
- 如果没有历史告警记录,则 shouldNotify 应为 true
- 相似度判断应综合考虑:趋势类型、总结内容、信号列表、风险评估
**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
{
"trend": "uptrend|downtrend|sideways|volatile",
"confidence": 0.85,
"summary": "...",
"signals": ["...", "...", "..."],
"risk": "low|medium|high",
"shouldNotify": true,
"notifyReason": "..."
}`;
}
/**
* 格式化数据点为文本表格
* @param data 价格数据点
* @returns 格式化后的文本
*/
private formatDataPoints(data: PriceDataPoint[]): string {
const header = '时间 价格 变化 波动率';
const rows = data.map(point => {
const time = new Date(point.timestamp).toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
const price = point.price.toFixed(3);
const change = point.changeFromPrevious !== undefined
? (point.changeFromPrevious > 0 ? '+' : '') + point.changeFromPrevious.toFixed(3)
: 'N/A';
const volatility = point.volatility !== undefined
? (point.volatility * 100).toFixed(1) + '%'
: 'N/A';
return `${time} ${price} ${change} ${volatility}`;
});
return [header, ...rows].join('\n');
}
/**
* 格式化历史告警上下文为文本
* @param history 历史告警记录
* @returns 格式化后的文本
*/
private formatHistoryContext(history: TrendAnalysisRecord[]): string {
if (history.length === 0) {
return '**历史告警记录**:无(这是首次分析或首次触发告警)';
}
const historyLines = history.map((record, index) => {
const time = new Date(record.timestamp).toLocaleString('zh-CN');
return `
**历史告警 ${index + 1}**(${time}):
- 趋势:${record.trend}
- 总结:${record.summary}
- 信号:${record.signals.join('; ')}
- 风险:${record.risk}
- 置信度:${(record.confidence * 100).toFixed(0)}%`;
}).join('\n');
return `**最近 ${history.length} 次历史告警记录**:
${historyLines}
请比较本次分析与上述历史告警的相似度,判断是否需要再次发送通知。`;
}
/**
* 调用 LLM API
* @param prompt 提示词
* @returns API 响应文本
*/
private async callAPI(prompt: string): Promise<string> {
const maxRetries = this.config.maxRetries || 2;
let lastError: Error | null = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
const response = await fetch(`${this.config.apiBase}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.config.apiKey}`
},
body: JSON.stringify({
model: this.config.model,
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.1,
max_tokens: 20000
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API 请求失败: ${response.status} ${response.statusText} - ${errorText}`);
}
const result = await response.json();
// 尝试多种可能的响应格式
// 优先检查标准的 content 字段
let content = result.choices?.[0]?.message?.content;
// 如果没有 content,检查 reasoning_content 字段(智谱AI推理模型)
if (!content) {
content = result.choices?.[0]?.message?.reasoning_content;
// 如果还没有,尝试其他可能的格式
if (!content) {
if (result.data?.choices?.[0]?.message?.content) {
content = result.data.choices[0].message.content;
} else if (result.data?.choices?.[0]?.message?.reasoning_content) {
content = result.data.choices[0].message.reasoning_content;
} else if (result.message?.content) {
content = result.message.content;
} else if (result.message?.reasoning_content) {
content = result.message.reasoning_content;
} else if (typeof result === 'string') {
content = result;
}
}
}
if (!content) {
console.error('API 响应原始数据:', JSON.stringify(result, null, 2));
throw new Error('API 响应格式错误:未找到 content 字段');
}
return content;
} catch (error) {
lastError = error as Error;
// 如果是超时或非重试错误,直接抛出
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`API 请求超时(${this.config.timeout}ms)`);
}
// 最后一次尝试失败,抛出错误
if (attempt === maxRetries) {
throw new Error(`API 调用失败(已重试 ${maxRetries} 次): ${lastError.message}`);
}
// 等待后重试
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
throw lastError || new Error('未知错误');
}
/**
* 解析 LLM 响应
* @param response API 响应文本
* @returns 解析后的趋势分析结果
*/
private parseResponse(response: string): TrendAnalysisResponse {
// 向后兼容:调用新的解析方法,但使用默认值
return this.parseResponseWithNotify(response);
}
/**
* 解析 LLM 响应(包含通知决策)
* @param response API 响应文本
* @returns 解析后的趋势分析结果
*/
private parseResponseWithNotify(response: string): TrendAnalysisResponse {
try {
// 尝试提取 JSON(可能包含在 markdown 代码块中)
let jsonStr = response.trim();
// 尝试查找 JSON 对象的模式(以 { 开头,以 } 结尾)
const jsonMatch = response.match(/\{[\s\S]*\}/);
if (jsonMatch) {
jsonStr = jsonMatch[0];
} else if (jsonStr.startsWith('```')) {
// 移除可能的 markdown 代码块标记
const lines = jsonStr.split('\n');
// 移除第一行(```json 或 ```)和最后一行(```)
if (lines.length > 2) {
jsonStr = lines.slice(1, -1).join('\n').trim();
} else {
jsonStr = lines[lines.length - 1].trim();
}
}
const parsed = JSON.parse(jsonStr);
// 验证必需字段
const requiredFields = ['trend', 'confidence', 'summary', 'signals', 'risk'];
for (const field of requiredFields) {
if (!(field in parsed)) {
throw new Error(`响应缺少必需字段: ${field}`);
}
}
// 验证趋势类型
const validTrends = ['uptrend', 'downtrend', 'sideways', 'volatile'];
if (!validTrends.includes(parsed.trend)) {
throw new Error(`无效的 trend 值: ${parsed.trend}`);
}
// 验证置信度范围
if (typeof parsed.confidence !== 'number' || parsed.confidence < 0 || parsed.confidence > 1) {
throw new Error(`无效的 confidence 值: ${parsed.confidence}`);
}
// 验证风险评估
const validRisks = ['low', 'medium', 'high'];
if (!validRisks.includes(parsed.risk)) {
throw new Error(`无效的 risk 值: ${parsed.risk}`);
}
// 验证信号数组
if (!Array.isArray(parsed.signals)) {
throw new Error('signals 必须是数组');
}
// 处理 shouldNotify 和 notifyReason 字段(可能不存在)
let shouldNotify = true;
let notifyReason = '未提供通知决策,默认发送通知';
if ('shouldNotify' in parsed && typeof parsed.shouldNotify === 'boolean') {
shouldNotify = parsed.shouldNotify;
if ('notifyReason' in parsed && typeof parsed.notifyReason === 'string') {
notifyReason = parsed.notifyReason;
} else {
console.warn('LLM 响应缺少 notifyReason 字段,使用默认值');
}
} else {
console.warn('LLM 响应缺少 shouldNotify 字段,使用默认值 true');
}
return {
trend: parsed.trend,
confidence: parsed.confidence,
summary: parsed.summary,
signals: parsed.signals,
risk: parsed.risk,
shouldNotify,
notifyReason
};
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`JSON 解析失败: ${error.message}\n原始响应: ${response}`);
}
throw error;
}
}
}