Files

358 lines
10 KiB
Markdown
Raw Permalink Normal View History

2026-01-22 00:39:36 +08:00
# Design: 黄金基线监控
## 概述
本设计文档描述如何为黄金商品实现基线监控功能,该功能与白银基线监控完全独立,但遵循相同的实现模式。
## 架构设计
### 数据流
```
1. 获取价格数据("黄金"商品)
↓
2. 检查基线是否存在
↓
3a. 如果不存在 → 初始化基线(使用首次价格)
↓
3b. 如果存在 → 比较当前价格与基线
↓
4. 判断是否超过阈值
↓
5a. 超过阈值 → 触发告警 → 更新基线
↓
5b. 未超过阈值 → 仅记录价格
↓
6. 保存数据到数据库
↓
7. 发送飞书告警(如果触发)
```
### 组件交互
```
┌─────────────────────────────────────────────────────────────┐
│ App │
│ - 创建 GoldBaselineMonitor 实例 │
│ - 设置定时器(每 MONITOR_INTERVAL 毫秒) │
│ - 管理优雅退出 │
└──────────────────────┬──────────────────────────────────────┘
│
↓
┌──────────────────────────────────────────────────────────────┐
│ GoldBaselineMonitor │
│ - processPrice(goldPrice) │
│ - initializeBaseline() │
│ - updateBaseline() │
│ - getStats() │
└──────────────┬────────────────────────────────┬──────────────┘
│ │
↓ ↓
┌──────────────────────────┐ ┌──────────────────────────┐
│ ScraperService │ │ DatabaseService │
│ - fetchGoldPrice() │ │ - loadGoldBaseline() │
│ (从页面提取"黄金"价格) │ │ - saveGoldBaseline() │
└──────────────────────────┘ │ - addGoldPrice() │
│ - updateGoldBaseline() │
└──────────────────────────┘
│
↓ (告警触发时)
┌──────────────────────────┐
│ AlertService │
│ - sendGoldBaselineAlert│
│ (飞书通知) │
└──────────────────────────┘
```
## 技术实现
### 1. 类型定义
在 `src/types/index.ts` 中新增以下接口:
```typescript
export interface GoldBaselineData {
currentPrice: number;
baseline: number;
timestamp: string;
}
export interface GoldBaselineAlert {
type: 'RISE' | 'FALL';
currentPrice: number;
baseline: number;
change: number;
changePercent: number;
timestamp: string;
}
export interface GoldBaselineDatabase {
baseline: number | null;
prices: GoldBaselineData[];
alerts: GoldBaselineAlert[];
}
```
### 2. 数据获取
在 `ScraperService` 中实现 `fetchGoldPrice()` 方法:
```typescript
async fetchGoldPrice(): Promise<MetalPrice | null> {
// 确保页面已加载
await this.ensurePageLoaded();
// 查找"黄金"商品
// 使用与白银相同的页面结构:div.price-table-row
// 商品名称在 span.symbol-name 中
// 价格在 div.el-col 中
}
```
**实现要点**:
- 复用 `ensurePageLoaded()` 方法
- 商品名称精确匹配"黄金"(不含空格)
- 提取回购价、销售价、最高价、最低价
- 返回 `MetalPrice` 对象或 `null`
### 3. 数据存储
在 `DatabaseService` 中新增以下方法:
```typescript
private goldBaselinePath = path.join(DATA_DIR, 'gold-baseline.json');
private goldBaselineData: GoldBaselineDatabase = {
baseline: null,
prices: [],
alerts: []
};
// 加载黄金基线数据
loadGoldBaseline(): void
// 保存黄金基线数据
saveGoldBaseline(): void
// 添加黄金价格记录
addGoldPrice(data: GoldBaselineData): Promise<void>
// 更新黄金基线
updateGoldBaseline(newBaseline: number): Promise<void>
// 获取黄金基线
getGoldBaseline(): number | null
// 获取黄金统计信息
getGoldBaselineStats(): GoldBaselineStats
```
**实现要点**:
- 数据文件:`src/data/gold-baseline.json`
- 结构与白银基线数据完全一致
- 在构造函数中初始化并加载数据
- 确保每次修改后调用 `saveGoldBaseline()` 持久化
### 4. 监控服务
创建 `src/services/gold-baseline-monitor.ts`:
```typescript
export class GoldBaselineMonitor {
constructor(
private db: DatabaseService,
private threshold: number = 0.2,
private alertService?: AlertService,
private webhookUrl?: string
) {}
async processPrice(goldPrice: MetalPrice): Promise<void>
private async initializeBaseline(price: number, timestamp: string): Promise<void>
private async updateBaseline(newBaseline: number, timestamp: string): Promise<void>
private async sendFeishuAlert(alert: GoldBaselineAlert): Promise<void>
getStats(): GoldBaselineStats
}
```
**实现要点**:
- 完全参考 `SilverBaselineMonitor` 的实现
- 唯一区别是商品名称为"黄金"
- 告警消息中显示"黄金"而非"白银"
### 5. 告警功能
在 `AlertService` 中新增 `sendGoldBaselineAlert()` 方法:
```typescript
async sendGoldBaselineAlert(
webhookUrl: string,
alert: GoldBaselineAlert
): Promise<void> {
const card = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: `🔔 黄金价格${alert.type === 'RISE' ? '📈 上涨' : '📉 下跌'}告警`
},
template: alert.type === 'RISE' ? 'green' : 'red'
},
elements: [
{
tag: 'div',
fields: [
{ tag: 'labeled_text', text: { tag: 'plain_text', content: `${alert.currentPrice.toFixed(3)}` }, label: { tag: 'plain_text', content: '当前价格' } },
{ tag: 'labeled_text', text: { tag: 'plain_text', content: `${alert.baseline.toFixed(3)}` }, label: { tag: 'plain_text', content: '基线价格' } },
// ... 更多字段
]
}
]
}
};
}
```
**实现要点**:
- 上涨告警:绿色卡片(`template: 'green'`)
- 下跌告警:红色卡片(`template: 'red'`)
- 显示内容:当前价格、基线价格、价格变化量、变化百分比、时间戳
### 6. 主程序集成
在 `src/index.ts` 的 `App` 类中:
```typescript
export class App {
private goldMonitor?: GoldBaselineMonitor;
async init() {
// 创建黄金基线监控
this.goldMonitor = new GoldBaselineMonitor(
this.db,
Number(process.env.GOLD_BASELINE_THRESHOLD) || 0.2,
this.alertService,
process.env.FEISHU_WEBHOOK_URL
);
// 启动黄金监控定时器
this.goldTimer = setInterval(async () => {
const goldPrice = await this.scraper.fetchGoldPrice();
if (goldPrice) {
await this.goldMonitor!.processPrice(goldPrice);
}
}, MONITOR_INTERVAL);
}
getStats() {
const goldStats = this.goldMonitor?.getStats();
// 显示黄金监控统计
}
}
```
**实现要点**:
- 与白银监控使用相同的监控间隔
- 独立的定时器,互不影响
- 共享 `ScraperService` 实例
- 在统计信息中显示黄金数据
### 7. 配置管理
在 `.env.example` 中添加:
```env
# 黄金基线监控阈值(默认 0.2)
# GOLD_BASELINE_THRESHOLD=0.2
```
## 数据结构
### gold-baseline.json
```json
{
"baseline": 678.90,
"prices": [
{
"currentPrice": 678.90,
"baseline": 678.50,
"timestamp": "2026-01-15T10:00:00.000Z"
}
],
"alerts": [
{
"type": "RISE",
"currentPrice": 678.90,
"baseline": 678.50,
"change": 0.4,
"changePercent": 0.06,
"timestamp": "2026-01-15T10:00:00.000Z"
}
]
}
```
## 与白银监控的关系
黄金监控和白银监控是**完全独立**的两个系统:
| 维度 | 白银监控 | 黄金监控 |
|------|----------|----------|
| 商品名称 | "白银" | "黄金" |
| 数据文件 | `silver-baseline.json` | `gold-baseline.json` |
| 监控类 | `SilverBaselineMonitor` | `GoldBaselineMonitor` |
| 环境变量 | `SILVER_BASELINE_THRESHOLD` | `GOLD_BASELINE_THRESHOLD` |
| 数据库方法 | `getSilverBaseline()` | `getGoldBaseline()` |
**共享资源**:
- `ScraperService` 实例(复用浏览器连接)
- `AlertService` 实例(复用飞书 Webhook)
- 监控间隔(`MONITOR_INTERVAL`)
## 错误处理
### 价格获取失败
- 记录错误日志
- 不影响其他监控(白银、价差)继续运行
- 下一个周期重试
### 数据存储失败
- 记录错误日志
- 尝试重试(最多3次)
- 如果仍失败,继续监控但告警用户
### 告警发送失败
- 记录错误日志
- 基线仍然更新(避免重复告警)
- 不影响后续监控
## 测试策略
### 单元测试
- 测试 `fetchGoldPrice()` 方法
- 测试 `GoldBaselineMonitor` 类的各个方法
- 测试 `AlertService.sendGoldBaselineAlert()` 方法
### 集成测试
- 测试完整的监控流程
- 测试与白银监控并行运行
- 测试优雅退出
### 手动测试
- 使用测试脚本 `test-gold-baseline.ts`
- 验证价格获取
- 验证告警触发(通过修改阈值)
- 验证数据持久化
## 性能考虑
- 与白银监控共享浏览器资源,无额外开销
- 独立的数据文件,避免锁竞争
- 内存占用极小(仅存储基线值和必要的统计数据)
## 未来扩展方向
- 支持多种黄金商品(如"黄金9999"、"黄金T+D"等)
- 支持动态阈值调整
- 支持告警静默时间段
- 提供历史数据查询接口