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:
commit
ccf523543a
52 files changed
+7763
No files matched your search
@@ -0,0 +1,23 @@
|
|||||||
|
---
|
||||||
|
name: OpenSpec: Apply
|
||||||
|
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||||
|
category: OpenSpec
|
||||||
|
tags: [openspec, apply]
|
||||||
|
---
|
||||||
|
<!-- OPENSPEC:START -->
|
||||||
|
**Guardrails**
|
||||||
|
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||||
|
- Keep changes tightly scoped to the requested outcome.
|
||||||
|
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
Track these steps as TODOs and complete them one by one.
|
||||||
|
1. Read `changes/<id>/proposal.md`, `design.md` (if present), and `tasks.md` to confirm scope and acceptance criteria.
|
||||||
|
2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
|
||||||
|
3. Confirm completion before updating statuses—make sure every item in `tasks.md` is finished.
|
||||||
|
4. Update the checklist after all work is done so each task is marked `- [x]` and reflects reality.
|
||||||
|
5. Reference `openspec list` or `openspec show <item>` when additional context is required.
|
||||||
|
|
||||||
|
**Reference**
|
||||||
|
- Use `openspec show <id> --json --deltas-only` if you need additional context from the proposal while implementing.
|
||||||
|
<!-- OPENSPEC:END -->
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
---
|
||||||
|
name: OpenSpec: Archive
|
||||||
|
description: Archive a deployed OpenSpec change and update specs.
|
||||||
|
category: OpenSpec
|
||||||
|
tags: [openspec, archive]
|
||||||
|
---
|
||||||
|
<!-- OPENSPEC:START -->
|
||||||
|
**Guardrails**
|
||||||
|
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||||
|
- Keep changes tightly scoped to the requested outcome.
|
||||||
|
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
1. Determine the change ID to archive:
|
||||||
|
- If this prompt already includes a specific change ID (for example inside a `<ChangeId>` block populated by slash-command arguments), use that value after trimming whitespace.
|
||||||
|
- If the conversation references a change loosely (for example by title or summary), run `openspec list` to surface likely IDs, share the relevant candidates, and confirm which one the user intends.
|
||||||
|
- Otherwise, review the conversation, run `openspec list`, and ask the user which change to archive; wait for a confirmed change ID before proceeding.
|
||||||
|
- If you still cannot identify a single change ID, stop and tell the user you cannot archive anything yet.
|
||||||
|
2. Validate the change ID by running `openspec list` (or `openspec show <id>`) and stop if the change is missing, already archived, or otherwise not ready to archive.
|
||||||
|
3. Run `openspec archive <id> --yes` so the CLI moves the change and applies spec updates without prompts (use `--skip-specs` only for tooling-only work).
|
||||||
|
4. Review the command output to confirm the target specs were updated and the change landed in `changes/archive/`.
|
||||||
|
5. Validate with `openspec validate --strict --no-interactive` and inspect with `openspec show <id>` if anything looks off.
|
||||||
|
|
||||||
|
**Reference**
|
||||||
|
- Use `openspec list` to confirm change IDs before archiving.
|
||||||
|
- Inspect refreshed specs with `openspec list --specs` and address any validation issues before handing off.
|
||||||
|
<!-- OPENSPEC:END -->
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
name: OpenSpec: Proposal
|
||||||
|
description: Scaffold a new OpenSpec change and validate strictly.
|
||||||
|
category: OpenSpec
|
||||||
|
tags: [openspec, change]
|
||||||
|
---
|
||||||
|
<!-- OPENSPEC:START -->
|
||||||
|
**Guardrails**
|
||||||
|
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||||
|
- Keep changes tightly scoped to the requested outcome.
|
||||||
|
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||||
|
- Identify any vague or ambiguous details and ask the necessary follow-up questions before editing files.
|
||||||
|
- Do not write any code during the proposal stage. Only create design documents (proposal.md, tasks.md, design.md, and spec deltas). Implementation happens in the apply stage after approval.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
1. Review `openspec/project.md`, run `openspec list` and `openspec list --specs`, and inspect related code or docs (e.g., via `rg`/`ls`) to ground the proposal in current behaviour; note any gaps that require clarification.
|
||||||
|
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, and `design.md` (when needed) under `openspec/changes/<id>/`.
|
||||||
|
3. Map the change into concrete capabilities or requirements, breaking multi-scope efforts into distinct spec deltas with clear relationships and sequencing.
|
||||||
|
4. Capture architectural reasoning in `design.md` when the solution spans multiple systems, introduces new patterns, or demands trade-off discussion before committing to specs.
|
||||||
|
5. Draft spec deltas in `changes/<id>/specs/<capability>/spec.md` (one folder per capability) using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement and cross-reference related capabilities when relevant.
|
||||||
|
6. Draft `tasks.md` as an ordered list of small, verifiable work items that deliver user-visible progress, include validation (tests, tooling), and highlight dependencies or parallelizable work.
|
||||||
|
7. Validate with `openspec validate <id> --strict --no-interactive` and resolve every issue before sharing the proposal.
|
||||||
|
|
||||||
|
**Reference**
|
||||||
|
- Use `openspec show <id> --json --deltas-only` or `openspec show <spec> --type spec` to inspect details when validation fails.
|
||||||
|
- Search existing requirements with `rg -n "Requirement:|Scenario:" openspec/specs` before writing new ones.
|
||||||
|
- Explore the codebase with `rg <keyword>`, `ls`, or direct file reads so proposals align with current implementation realities.
|
||||||
|
<!-- OPENSPEC:END -->
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"mcp__plugin_playwright_playwright__browser_navigate",
|
||||||
|
"mcp__plugin_playwright_playwright__browser_close",
|
||||||
|
"Bash(npm install:*)",
|
||||||
|
"Bash(npm run typecheck)",
|
||||||
|
"Bash(npm run build:*)",
|
||||||
|
"Bash(npx playwright install:*)",
|
||||||
|
"Bash(npm run dev)",
|
||||||
|
"mcp__plugin_playwright_playwright__browser_evaluate",
|
||||||
|
"mcp__plugin_playwright_playwright__browser_run_code",
|
||||||
|
"Bash(npx tsx:*)",
|
||||||
|
"Bash(test:*)",
|
||||||
|
"Bash(tsx test:*)",
|
||||||
|
"mcp__plugin_serena_serena__list_dir",
|
||||||
|
"Bash(dir /B D:projectrongtongjin)",
|
||||||
|
"Bash(openspec list:*)",
|
||||||
|
"Bash(npx openspec:*)",
|
||||||
|
"Bash(openspec:*)",
|
||||||
|
"Bash(node dist/index.js:*)",
|
||||||
|
"Bash(timeout:*)",
|
||||||
|
"Bash(npx dotenv-cli -e .env -- npx tsx test-llm-trend.ts:*)",
|
||||||
|
"Bash(npx dotenv-cli:*)",
|
||||||
|
"mcp__plugin_serena_serena__read_file"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# 监控间隔(毫秒),默认 60000(1 分钟)
|
||||||
|
MONITOR_INTERVAL=60000
|
||||||
|
|
||||||
|
# Webhook 地址(可选,用于企业微信、钉钉等告警)
|
||||||
|
# WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY
|
||||||
|
|
||||||
|
# 飞书 Webhook 地址(用于接收每小时汇总报告和白银基线告警)
|
||||||
|
# FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxxxxxxxxxxx
|
||||||
|
|
||||||
|
# 白银基线监控阈值(默认 0.2)
|
||||||
|
# 当白银价格相对于基线变化超过此值时触发告警
|
||||||
|
SILVER_BASELINE_THRESHOLD=0.2
|
||||||
|
|
||||||
|
# LLM API 配置(用于趋势分析功能)
|
||||||
|
# LLM API 基础 URL(可选,默认 OpenAI API)
|
||||||
|
# LLM_API_BASE=https://api.openai.com/v1
|
||||||
|
# LLM API 密钥(必需,如果未配置则跳过趋势分析功能)
|
||||||
|
# LLM_API_KEY=sk-xxxxxxxxxxxxxxxxxxxx
|
||||||
|
# LLM 模型(可选,默认 gpt-4o-mini)
|
||||||
|
# LLM_MODEL=gpt-4o-mini
|
||||||
|
|
||||||
|
# 趋势分析间隔(毫秒),默认 300000(5 分钟)
|
||||||
|
# TREND_ANALYSIS_INTERVAL=300000
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
# 依赖
|
||||||
|
node_modules/
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
pnpm-lock.yaml
|
||||||
|
|
||||||
|
# 构建产物
|
||||||
|
dist/
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# 环境变量
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# 数据和日志
|
||||||
|
src/data/*.json
|
||||||
|
logs/*.log
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# 操作系统
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# 临时文件
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<!-- OPENSPEC:START -->
|
||||||
|
# OpenSpec Instructions
|
||||||
|
|
||||||
|
These instructions are for AI assistants working in this project.
|
||||||
|
|
||||||
|
Always open `@/openspec/AGENTS.md` when the request:
|
||||||
|
- Mentions planning or proposals (words like proposal, spec, change, plan)
|
||||||
|
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
|
||||||
|
- Sounds ambiguous and you need the authoritative spec before coding
|
||||||
|
|
||||||
|
Use `@/openspec/AGENTS.md` to learn:
|
||||||
|
- How to create and apply change proposals
|
||||||
|
- Spec format and conventions
|
||||||
|
- Project structure and guidelines
|
||||||
|
|
||||||
|
Keep this managed block so 'openspec update' can refresh the instructions.
|
||||||
|
|
||||||
|
<!-- OPENSPEC:END -->
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<!-- OPENSPEC:START -->
|
||||||
|
# OpenSpec Instructions
|
||||||
|
|
||||||
|
These instructions are for AI assistants working in this project.
|
||||||
|
|
||||||
|
Always open `@/openspec/AGENTS.md` when the request:
|
||||||
|
- Mentions planning or proposals (words like proposal, spec, change, plan)
|
||||||
|
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
|
||||||
|
- Sounds ambiguous and you need the authoritative spec before coding
|
||||||
|
|
||||||
|
Use `@/openspec/AGENTS.md` to learn:
|
||||||
|
- How to create and apply change proposals
|
||||||
|
- Spec format and conventions
|
||||||
|
- Project structure and guidelines
|
||||||
|
|
||||||
|
Keep this managed block so 'openspec update' can refresh the instructions.
|
||||||
|
|
||||||
|
<!-- OPENSPEC:END -->
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
# 贵金属价格监控系统
|
||||||
|
|
||||||
|
基于 Node.js 和 Playwright 的贵金属价格监控项目,实时监控白银价格变化,并根据价格基线变化触发告警。
|
||||||
|
|
||||||
|
## 当前运行状态
|
||||||
|
|
||||||
|
**当前激活的监控功能**:
|
||||||
|
- ✅ 白银价格基线监控(监控"白银"商品销售价格)
|
||||||
|
- ✅ **LLM 趋势总结**(AI 分析最近 10 分钟的价格趋势)
|
||||||
|
- ⏸️ 价差监控(美白银 vs 伦敦银)- 已暂时禁用
|
||||||
|
- ⏸️ 每2小时汇总报告 - 已暂时禁用
|
||||||
|
|
||||||
|
## 监控逻辑
|
||||||
|
|
||||||
|
### 白银基线监控(当前运行)
|
||||||
|
|
||||||
|
系统监控白银销售价格相对于基线的变化:
|
||||||
|
|
||||||
|
- **基线初始化**:首次运行时,使用首次获取的白银价格作为基线
|
||||||
|
- **告警触发**:当价格相对于基线变化超过阈值(默认 ±0.2)时触发告警
|
||||||
|
- **基线更新**:告警触发后,立即将当前价格更新为新基线,避免重复告警
|
||||||
|
|
||||||
|
### 价差监控(已禁用)
|
||||||
|
|
||||||
|
系统可监控美白银和伦敦银的价差变化:
|
||||||
|
|
||||||
|
- **上涨信号**:美白银从 > 伦敦银 变成 < 伦敦银(价差从正变负)
|
||||||
|
- **下跌信号**:美白银从 < 伦敦银 变成 > 伦敦银(价差从负变正)
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
rongtongjin/
|
||||||
|
├── src/
|
||||||
|
│ ├── types/ # 类型定义
|
||||||
|
│ │ └── index.ts
|
||||||
|
│ ├── services/ # 核心服务
|
||||||
|
│ │ ├── database.ts # 文件数据库服务
|
||||||
|
│ │ ├── scraper.ts # Playwright 爬虫服务
|
||||||
|
│ │ └── monitor.ts # 监控服务
|
||||||
|
│ ├── utils/ # 工具函数
|
||||||
|
│ │ └── alert.ts # 告警服务
|
||||||
|
│ ├── data/ # 数据存储目录
|
||||||
|
│ ├── index.ts # 主入口文件
|
||||||
|
├── logs/ # 日志目录
|
||||||
|
├── .env.example # 环境变量示例
|
||||||
|
├── package.json
|
||||||
|
├── tsconfig.json
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 1. 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置环境变量(可选)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
编辑 `.env` 文件:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# 监控间隔(毫秒),默认 60000(1 分钟)
|
||||||
|
MONITOR_INTERVAL=60000
|
||||||
|
|
||||||
|
# Webhook 地址(可选)
|
||||||
|
# WEBHOOK_URL=https://your-webhook-url
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 启动项目
|
||||||
|
|
||||||
|
开发模式:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
生产模式:
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- ✅ 使用 Playwright 自动化获取价格数据
|
||||||
|
- ✅ 文件数据库存储历史数据(JSON 格式)
|
||||||
|
- ✅ **白银价格基线监控**(当前运行)
|
||||||
|
- ✅ 多种告警方式(控制台、日志文件、Webhook)
|
||||||
|
- ✅ 优雅的进程退出处理
|
||||||
|
- ✅ 统计信息展示
|
||||||
|
- ⏸️ 价差监控(已禁用,可恢复)
|
||||||
|
- ⏸️ 飞书汇总报告(已禁用,可恢复)
|
||||||
|
|
||||||
|
## 告警配置
|
||||||
|
|
||||||
|
### 控制台告警
|
||||||
|
默认启用,在控制台显示醒目的告警信息。
|
||||||
|
|
||||||
|
### 文件日志告警
|
||||||
|
告警信息会记录到 `logs/alerts.log` 文件。
|
||||||
|
|
||||||
|
### Webhook 告警
|
||||||
|
支持配置 Webhook 地址,可用于企业微信、钉钉等。
|
||||||
|
|
||||||
|
配置示例:
|
||||||
|
|
||||||
|
**企业微信机器人**:
|
||||||
|
```env
|
||||||
|
WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
**钉钉机器人**:
|
||||||
|
```env
|
||||||
|
WEBHOOK_URL=https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
### 飞书汇总报告(已禁用)
|
||||||
|
系统可以定期发送监控汇总报告到飞书,但目前此功能已禁用。如需恢复,请参考下面的"恢复价差监控"部分。
|
||||||
|
|
||||||
|
## 白银价格基线监控
|
||||||
|
|
||||||
|
系统新增了独立的白银价格基线监控功能,可以追踪页面上"白银"商品的销售价格变化。
|
||||||
|
|
||||||
|
### 监控逻辑
|
||||||
|
- **基线初始化**:首次运行时,使用首次获取的白银价格作为基线
|
||||||
|
- **告警触发**:当价格相对于基线变化超过阈值(默认 ±0.2)时触发告警
|
||||||
|
- **基线更新**:告警触发后,立即将当前价格更新为新基线,避免重复告警
|
||||||
|
|
||||||
|
### 配置方法
|
||||||
|
在 `.env` 文件中配置:
|
||||||
|
```env
|
||||||
|
# 白银基线监控阈值(默认 0.2)
|
||||||
|
SILVER_BASELINE_THRESHOLD=0.2
|
||||||
|
|
||||||
|
# 飞书 Webhook 地址(用于接收告警)
|
||||||
|
WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/你的密钥
|
||||||
|
```
|
||||||
|
|
||||||
|
### 告警示例
|
||||||
|
当白银价格上涨或下跌超过阈值时,会通过飞书发送告警消息,包含:
|
||||||
|
- 告警类型(上涨/下跌)
|
||||||
|
- 当前价格
|
||||||
|
- 基线价格
|
||||||
|
- 价格变化量
|
||||||
|
- 变化百分比
|
||||||
|
|
||||||
|
### 数据存储
|
||||||
|
白银基线监控的数据存储在 `src/data/silver-baseline.json`,包含:
|
||||||
|
- 当前基线值
|
||||||
|
- 历史价格记录
|
||||||
|
- 告警记录
|
||||||
|
|
||||||
|
## LLM 趋势总结(新增)
|
||||||
|
|
||||||
|
系统集成了 LLM(大语言模型)进行智能趋势分析,提供更深入的价格走势洞察。
|
||||||
|
|
||||||
|
### 功能特点
|
||||||
|
|
||||||
|
- **智能总结**:使用 LLM 分析最近 30 分钟的价格数据,重点总结最近 10 分钟的趋势
|
||||||
|
- **趋势识别**:自动识别上涨趋势、下跌趋势、平稳波动、剧烈波动等状态
|
||||||
|
- **告警触发**:当检测到趋势反转、剧烈波动或高风险信号时,通过飞书发送告警
|
||||||
|
- **风险评估**:提供低、中、高三个等级的风险评估
|
||||||
|
|
||||||
|
### 工作原理
|
||||||
|
|
||||||
|
1. **数据准备**:从白银基线数据中提取最近 30 个价格数据点(30 分钟)
|
||||||
|
2. **LLM 分析**:调用 OpenAI 兼容的 API 进行趋势分析
|
||||||
|
3. **结果解析**:解析 LLM 返回的结构化数据(趋势类型、置信度、总结、信号等)
|
||||||
|
4. **告警判断**:根据预设条件判断是否需要发送告警
|
||||||
|
5. **记录保存**:保存分析记录到 `src/data/silver-trends.json`
|
||||||
|
|
||||||
|
### 告警触发条件
|
||||||
|
|
||||||
|
满足以下任一条件时触发飞书告警:
|
||||||
|
|
||||||
|
1. **趋势反转**:从上涨趋势变为下跌趋势,或反之(置信度 > 0.6)
|
||||||
|
2. **价格剧烈波动**:检测到异常的价格波动幅度(置信度 > 0.7)
|
||||||
|
3. **高风险信号**:LLM 评估为高风险且置信度 > 0.8
|
||||||
|
|
||||||
|
### 配置方法
|
||||||
|
|
||||||
|
在 `.env` 文件中配置:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# LLM API 配置
|
||||||
|
LLM_API_BASE=https://api.openai.com/v1
|
||||||
|
LLM_API_KEY=sk-xxxxxxxxxxxxxxxxxxxx
|
||||||
|
LLM_MODEL=gpt-4o-mini
|
||||||
|
|
||||||
|
# 趋势分析间隔(默认 10 分钟)
|
||||||
|
TREND_ANALYSIS_INTERVAL=600000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 成本估算
|
||||||
|
|
||||||
|
- **每次分析**:约 $0.0003-0.0007(30 个数据点,约 1500 tokens)
|
||||||
|
- **每天成本**:约 $0.03-0.07(默认 10 分钟间隔,每小时 6 次)
|
||||||
|
- **建议模型**:`gpt-4o-mini`(性价比高,成本约为 GPT-4 的 1/10)
|
||||||
|
|
||||||
|
### 测试 LLM 趋势分析
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 确保 .env 文件中已配置 LLM_API_KEY
|
||||||
|
npx tsx test-llm-trend.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
## 数据文件
|
||||||
|
|
||||||
|
### prices.json
|
||||||
|
存储所有价格记录和变化记录,格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"prices": [
|
||||||
|
{
|
||||||
|
"usSilver": 85.430,
|
||||||
|
"londonSilver": 85.365,
|
||||||
|
"spread": 0.065,
|
||||||
|
"timestamp": "2026-01-12T15:47:00.000Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
{
|
||||||
|
"timestamp": "2026-01-12T15:47:00.000Z",
|
||||||
|
"prevSpread": -0.100,
|
||||||
|
"currentSpread": 0.065,
|
||||||
|
"changeType": "FALL",
|
||||||
|
"usSilver": 85.430,
|
||||||
|
"londonSilver": 85.365
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 开发
|
||||||
|
|
||||||
|
### 类型检查
|
||||||
|
```bash
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
### 构建
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
## 恢复价差监控
|
||||||
|
|
||||||
|
如需恢复价差监控和汇总报告功能,请按照以下步骤操作:
|
||||||
|
|
||||||
|
### 1. 恢复价差监控启动
|
||||||
|
|
||||||
|
编辑 `src/index.ts` 文件,找到 `start()` 方法中的以下代码段(约第 79-89 行):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 价差监控已禁用 - 仅运行白银基线监控
|
||||||
|
// 如需恢复价差监控,请取消下面的注释
|
||||||
|
/*
|
||||||
|
// 启动价差监控
|
||||||
|
this.monitor.startMonitor(
|
||||||
|
// 获取价格的函数
|
||||||
|
() => this.scraper.fetchSilverPrices(),
|
||||||
|
// 用于停止的 AbortSignal
|
||||||
|
this.abortController.signal
|
||||||
|
);
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
**恢复方法**:删除注释标记 `/*` 和 `*/`,即取消注释这段代码。
|
||||||
|
|
||||||
|
### 2. 恢复价差监控统计显示
|
||||||
|
|
||||||
|
继续编辑 `src/index.ts` 文件,找到 `showStats()` 方法中的价差监控统计代码(约第 134-155 行):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 价差监控已禁用 - 仅显示白银基线监控统计
|
||||||
|
/*
|
||||||
|
// 价差监控统计信息
|
||||||
|
const stats = this.monitor.getStats();
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('价差监控统计信息');
|
||||||
|
// ... 其他显示代码
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
**恢复方法**:删除注释标记 `/*` 和 `*/`。
|
||||||
|
|
||||||
|
### 3. 重新构建并启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
恢复后,系统将同时运行:
|
||||||
|
- ✅ 白银价格基线监控
|
||||||
|
- ✅ 价差监控(美白银 vs 伦敦银)
|
||||||
|
- ✅ 每2小时汇总报告
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. 首次运行会自动下载 Playwright 浏览器
|
||||||
|
2. 确保网络可以访问 `https://i.jzj9999.com/quoteh5/`
|
||||||
|
3. 数据文件存储在 `src/data/` 目录
|
||||||
|
4. 日志文件存储在 `logs/` 目录
|
||||||
|
5. 价差监控已被注释掉但未删除,可随时恢复
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { chromium } from 'playwright';
|
||||||
|
|
||||||
|
async function inspectPage() {
|
||||||
|
console.log('启动浏览器...');
|
||||||
|
const browser = await chromium.launch({ headless: true });
|
||||||
|
const page = await browser.newPage();
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log('导航到页面...');
|
||||||
|
await page.goto('https://i.jzj9999.com/quoteh5/', {
|
||||||
|
waitUntil: 'networkidle',
|
||||||
|
timeout: 30000
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('\n页面加载成功!');
|
||||||
|
console.log('页面标题:', await page.title());
|
||||||
|
console.log('页面URL:', page.url());
|
||||||
|
|
||||||
|
// 获取页面的 HTML 结构
|
||||||
|
console.log('\n查找所有包含"银"字的元素...');
|
||||||
|
const silverElements = await page.evaluate(() => {
|
||||||
|
const elements = Array.from(document.querySelectorAll('*'));
|
||||||
|
const results: string[] = [];
|
||||||
|
|
||||||
|
elements.forEach(el => {
|
||||||
|
const text = el.textContent?.trim() || '';
|
||||||
|
if (text.includes('银') && text.length < 50) {
|
||||||
|
const tagName = el.tagName.toLowerCase();
|
||||||
|
const className = el.className || '';
|
||||||
|
results.push(`${tagName}.${className}: "${text}"`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return results.slice(0, 20); // 只返回前20个
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('找到的元素:');
|
||||||
|
silverElements.forEach((el, i) => {
|
||||||
|
console.log(` ${i + 1}. ${el}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 查找所有可能的价格容器
|
||||||
|
console.log('\n查找价格容器结构...');
|
||||||
|
const structure = await page.evaluate(() => {
|
||||||
|
// 查找所有可能的容器
|
||||||
|
const containers = [
|
||||||
|
'div.e19',
|
||||||
|
'div.generic',
|
||||||
|
'[class*="price"]',
|
||||||
|
'[class*="item"]',
|
||||||
|
'[class*="row"]'
|
||||||
|
];
|
||||||
|
|
||||||
|
const results: any = {};
|
||||||
|
containers.forEach(selector => {
|
||||||
|
const elements = document.querySelectorAll(selector);
|
||||||
|
results[selector] = elements.length;
|
||||||
|
});
|
||||||
|
|
||||||
|
return results;
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('容器统计:');
|
||||||
|
Object.entries(structure).forEach(([selector, count]) => {
|
||||||
|
console.log(` ${selector}: ${count} 个`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 尝试获取所有商品名称
|
||||||
|
console.log('\n尝试获取商品列表...');
|
||||||
|
const products = await page.evaluate(() => {
|
||||||
|
const results: string[] = [];
|
||||||
|
|
||||||
|
// 尝试多种选择器
|
||||||
|
const selectors = [
|
||||||
|
'div.e19 > div.generic',
|
||||||
|
'div.generic',
|
||||||
|
'[class*="item"]',
|
||||||
|
'[class*="product"]'
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const selector of selectors) {
|
||||||
|
const elements = document.querySelectorAll(selector);
|
||||||
|
if (elements.length > 0) {
|
||||||
|
results.push(`\n使用选择器: ${selector} (找到 ${elements.length} 个)`);
|
||||||
|
|
||||||
|
Array.from(elements).slice(0, 5).forEach((el, i) => {
|
||||||
|
const text = el.textContent?.trim().substring(0, 100) || '';
|
||||||
|
results.push(` ${i + 1}. ${text}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
break; // 找到就停止
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
});
|
||||||
|
|
||||||
|
products.forEach(line => console.log(line));
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('错误:', error);
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
console.log('\n浏览器已关闭');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inspectPage();
|
||||||
@@ -0,0 +1,456 @@
|
|||||||
|
# OpenSpec Instructions
|
||||||
|
|
||||||
|
Instructions for AI coding assistants using OpenSpec for spec-driven development.
|
||||||
|
|
||||||
|
## TL;DR Quick Checklist
|
||||||
|
|
||||||
|
- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)
|
||||||
|
- Decide scope: new capability vs modify existing capability
|
||||||
|
- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)
|
||||||
|
- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability
|
||||||
|
- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement
|
||||||
|
- Validate: `openspec validate [change-id] --strict --no-interactive` and fix issues
|
||||||
|
- Request approval: Do not start implementation until proposal is approved
|
||||||
|
|
||||||
|
## Three-Stage Workflow
|
||||||
|
|
||||||
|
### Stage 1: Creating Changes
|
||||||
|
Create proposal when you need to:
|
||||||
|
- Add features or functionality
|
||||||
|
- Make breaking changes (API, schema)
|
||||||
|
- Change architecture or patterns
|
||||||
|
- Optimize performance (changes behavior)
|
||||||
|
- Update security patterns
|
||||||
|
|
||||||
|
Triggers (examples):
|
||||||
|
- "Help me create a change proposal"
|
||||||
|
- "Help me plan a change"
|
||||||
|
- "Help me create a proposal"
|
||||||
|
- "I want to create a spec proposal"
|
||||||
|
- "I want to create a spec"
|
||||||
|
|
||||||
|
Loose matching guidance:
|
||||||
|
- Contains one of: `proposal`, `change`, `spec`
|
||||||
|
- With one of: `create`, `plan`, `make`, `start`, `help`
|
||||||
|
|
||||||
|
Skip proposal for:
|
||||||
|
- Bug fixes (restore intended behavior)
|
||||||
|
- Typos, formatting, comments
|
||||||
|
- Dependency updates (non-breaking)
|
||||||
|
- Configuration changes
|
||||||
|
- Tests for existing behavior
|
||||||
|
|
||||||
|
**Workflow**
|
||||||
|
1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.
|
||||||
|
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.
|
||||||
|
3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.
|
||||||
|
4. Run `openspec validate <id> --strict --no-interactive` and resolve any issues before sharing the proposal.
|
||||||
|
|
||||||
|
### Stage 2: Implementing Changes
|
||||||
|
Track these steps as TODOs and complete them one by one.
|
||||||
|
1. **Read proposal.md** - Understand what's being built
|
||||||
|
2. **Read design.md** (if exists) - Review technical decisions
|
||||||
|
3. **Read tasks.md** - Get implementation checklist
|
||||||
|
4. **Implement tasks sequentially** - Complete in order
|
||||||
|
5. **Confirm completion** - Ensure every item in `tasks.md` is finished before updating statuses
|
||||||
|
6. **Update checklist** - After all work is done, set every task to `- [x]` so the list reflects reality
|
||||||
|
7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
|
||||||
|
|
||||||
|
### Stage 3: Archiving Changes
|
||||||
|
After deployment, create separate PR to:
|
||||||
|
- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/`
|
||||||
|
- Update `specs/` if capabilities changed
|
||||||
|
- Use `openspec archive <change-id> --skip-specs --yes` for tooling-only changes (always pass the change ID explicitly)
|
||||||
|
- Run `openspec validate --strict --no-interactive` to confirm the archived change passes checks
|
||||||
|
|
||||||
|
## Before Any Task
|
||||||
|
|
||||||
|
**Context Checklist:**
|
||||||
|
- [ ] Read relevant specs in `specs/[capability]/spec.md`
|
||||||
|
- [ ] Check pending changes in `changes/` for conflicts
|
||||||
|
- [ ] Read `openspec/project.md` for conventions
|
||||||
|
- [ ] Run `openspec list` to see active changes
|
||||||
|
- [ ] Run `openspec list --specs` to see existing capabilities
|
||||||
|
|
||||||
|
**Before Creating Specs:**
|
||||||
|
- Always check if capability already exists
|
||||||
|
- Prefer modifying existing specs over creating duplicates
|
||||||
|
- Use `openspec show [spec]` to review current state
|
||||||
|
- If request is ambiguous, ask 1–2 clarifying questions before scaffolding
|
||||||
|
|
||||||
|
### Search Guidance
|
||||||
|
- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)
|
||||||
|
- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)
|
||||||
|
- Show details:
|
||||||
|
- Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)
|
||||||
|
- Change: `openspec show <change-id> --json --deltas-only`
|
||||||
|
- Full-text search (use ripgrep): `rg -n "Requirement:|Scenario:" openspec/specs`
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### CLI Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Essential commands
|
||||||
|
openspec list # List active changes
|
||||||
|
openspec list --specs # List specifications
|
||||||
|
openspec show [item] # Display change or spec
|
||||||
|
openspec validate [item] # Validate changes or specs
|
||||||
|
openspec archive <change-id> [--yes|-y] # Archive after deployment (add --yes for non-interactive runs)
|
||||||
|
|
||||||
|
# Project management
|
||||||
|
openspec init [path] # Initialize OpenSpec
|
||||||
|
openspec update [path] # Update instruction files
|
||||||
|
|
||||||
|
# Interactive mode
|
||||||
|
openspec show # Prompts for selection
|
||||||
|
openspec validate # Bulk validation mode
|
||||||
|
|
||||||
|
# Debugging
|
||||||
|
openspec show [change] --json --deltas-only
|
||||||
|
openspec validate [change] --strict --no-interactive
|
||||||
|
```
|
||||||
|
|
||||||
|
### Command Flags
|
||||||
|
|
||||||
|
- `--json` - Machine-readable output
|
||||||
|
- `--type change|spec` - Disambiguate items
|
||||||
|
- `--strict` - Comprehensive validation
|
||||||
|
- `--no-interactive` - Disable prompts
|
||||||
|
- `--skip-specs` - Archive without spec updates
|
||||||
|
- `--yes`/`-y` - Skip confirmation prompts (non-interactive archive)
|
||||||
|
|
||||||
|
## Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
openspec/
|
||||||
|
├── project.md # Project conventions
|
||||||
|
├── specs/ # Current truth - what IS built
|
||||||
|
│ └── [capability]/ # Single focused capability
|
||||||
|
│ ├── spec.md # Requirements and scenarios
|
||||||
|
│ └── design.md # Technical patterns
|
||||||
|
├── changes/ # Proposals - what SHOULD change
|
||||||
|
│ ├── [change-name]/
|
||||||
|
│ │ ├── proposal.md # Why, what, impact
|
||||||
|
│ │ ├── tasks.md # Implementation checklist
|
||||||
|
│ │ ├── design.md # Technical decisions (optional; see criteria)
|
||||||
|
│ │ └── specs/ # Delta changes
|
||||||
|
│ │ └── [capability]/
|
||||||
|
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
|
||||||
|
│ └── archive/ # Completed changes
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating Change Proposals
|
||||||
|
|
||||||
|
### Decision Tree
|
||||||
|
|
||||||
|
```
|
||||||
|
New request?
|
||||||
|
├─ Bug fix restoring spec behavior? → Fix directly
|
||||||
|
├─ Typo/format/comment? → Fix directly
|
||||||
|
├─ New feature/capability? → Create proposal
|
||||||
|
├─ Breaking change? → Create proposal
|
||||||
|
├─ Architecture change? → Create proposal
|
||||||
|
└─ Unclear? → Create proposal (safer)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Proposal Structure
|
||||||
|
|
||||||
|
1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)
|
||||||
|
|
||||||
|
2. **Write proposal.md:**
|
||||||
|
```markdown
|
||||||
|
# Change: [Brief description of change]
|
||||||
|
|
||||||
|
## Why
|
||||||
|
[1-2 sentences on problem/opportunity]
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- [Bullet list of changes]
|
||||||
|
- [Mark breaking changes with **BREAKING**]
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
- Affected specs: [list capabilities]
|
||||||
|
- Affected code: [key files/systems]
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Create spec deltas:** `specs/[capability]/spec.md`
|
||||||
|
```markdown
|
||||||
|
## ADDED Requirements
|
||||||
|
### Requirement: New Feature
|
||||||
|
The system SHALL provide...
|
||||||
|
|
||||||
|
#### Scenario: Success case
|
||||||
|
- **WHEN** user performs action
|
||||||
|
- **THEN** expected result
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
### Requirement: Existing Feature
|
||||||
|
[Complete modified requirement]
|
||||||
|
|
||||||
|
## REMOVED Requirements
|
||||||
|
### Requirement: Old Feature
|
||||||
|
**Reason**: [Why removing]
|
||||||
|
**Migration**: [How to handle]
|
||||||
|
```
|
||||||
|
If multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`—one per capability.
|
||||||
|
|
||||||
|
4. **Create tasks.md:**
|
||||||
|
```markdown
|
||||||
|
## 1. Implementation
|
||||||
|
- [ ] 1.1 Create database schema
|
||||||
|
- [ ] 1.2 Implement API endpoint
|
||||||
|
- [ ] 1.3 Add frontend component
|
||||||
|
- [ ] 1.4 Write tests
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **Create design.md when needed:**
|
||||||
|
Create `design.md` if any of the following apply; otherwise omit it:
|
||||||
|
- Cross-cutting change (multiple services/modules) or a new architectural pattern
|
||||||
|
- New external dependency or significant data model changes
|
||||||
|
- Security, performance, or migration complexity
|
||||||
|
- Ambiguity that benefits from technical decisions before coding
|
||||||
|
|
||||||
|
Minimal `design.md` skeleton:
|
||||||
|
```markdown
|
||||||
|
## Context
|
||||||
|
[Background, constraints, stakeholders]
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
- Goals: [...]
|
||||||
|
- Non-Goals: [...]
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
- Decision: [What and why]
|
||||||
|
- Alternatives considered: [Options + rationale]
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
- [Risk] → Mitigation
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
[Steps, rollback]
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
- [...]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Spec File Format
|
||||||
|
|
||||||
|
### Critical: Scenario Formatting
|
||||||
|
|
||||||
|
**CORRECT** (use #### headers):
|
||||||
|
```markdown
|
||||||
|
#### Scenario: User login success
|
||||||
|
- **WHEN** valid credentials provided
|
||||||
|
- **THEN** return JWT token
|
||||||
|
```
|
||||||
|
|
||||||
|
**WRONG** (don't use bullets or bold):
|
||||||
|
```markdown
|
||||||
|
- **Scenario: User login** ❌
|
||||||
|
**Scenario**: User login ❌
|
||||||
|
### Scenario: User login ❌
|
||||||
|
```
|
||||||
|
|
||||||
|
Every requirement MUST have at least one scenario.
|
||||||
|
|
||||||
|
### Requirement Wording
|
||||||
|
- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)
|
||||||
|
|
||||||
|
### Delta Operations
|
||||||
|
|
||||||
|
- `## ADDED Requirements` - New capabilities
|
||||||
|
- `## MODIFIED Requirements` - Changed behavior
|
||||||
|
- `## REMOVED Requirements` - Deprecated features
|
||||||
|
- `## RENAMED Requirements` - Name changes
|
||||||
|
|
||||||
|
Headers matched with `trim(header)` - whitespace ignored.
|
||||||
|
|
||||||
|
#### When to use ADDED vs MODIFIED
|
||||||
|
- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding "Slash Command Configuration") rather than altering the semantics of an existing requirement.
|
||||||
|
- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.
|
||||||
|
- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.
|
||||||
|
|
||||||
|
Common pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren’t explicitly changing the existing requirement, add a new requirement under ADDED instead.
|
||||||
|
|
||||||
|
Authoring a MODIFIED requirement correctly:
|
||||||
|
1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.
|
||||||
|
2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).
|
||||||
|
3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.
|
||||||
|
4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.
|
||||||
|
|
||||||
|
Example for RENAMED:
|
||||||
|
```markdown
|
||||||
|
## RENAMED Requirements
|
||||||
|
- FROM: `### Requirement: Login`
|
||||||
|
- TO: `### Requirement: User Authentication`
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Common Errors
|
||||||
|
|
||||||
|
**"Change must have at least one delta"**
|
||||||
|
- Check `changes/[name]/specs/` exists with .md files
|
||||||
|
- Verify files have operation prefixes (## ADDED Requirements)
|
||||||
|
|
||||||
|
**"Requirement must have at least one scenario"**
|
||||||
|
- Check scenarios use `#### Scenario:` format (4 hashtags)
|
||||||
|
- Don't use bullet points or bold for scenario headers
|
||||||
|
|
||||||
|
**Silent scenario parsing failures**
|
||||||
|
- Exact format required: `#### Scenario: Name`
|
||||||
|
- Debug with: `openspec show [change] --json --deltas-only`
|
||||||
|
|
||||||
|
### Validation Tips
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Always use strict mode for comprehensive checks
|
||||||
|
openspec validate [change] --strict --no-interactive
|
||||||
|
|
||||||
|
# Debug delta parsing
|
||||||
|
openspec show [change] --json | jq '.deltas'
|
||||||
|
|
||||||
|
# Check specific requirement
|
||||||
|
openspec show [spec] --json -r 1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Happy Path Script
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1) Explore current state
|
||||||
|
openspec spec list --long
|
||||||
|
openspec list
|
||||||
|
# Optional full-text search:
|
||||||
|
# rg -n "Requirement:|Scenario:" openspec/specs
|
||||||
|
# rg -n "^#|Requirement:" openspec/changes
|
||||||
|
|
||||||
|
# 2) Choose change id and scaffold
|
||||||
|
CHANGE=add-two-factor-auth
|
||||||
|
mkdir -p openspec/changes/$CHANGE/{specs/auth}
|
||||||
|
printf "## Why\n...\n\n## What Changes\n- ...\n\n## Impact\n- ...\n" > openspec/changes/$CHANGE/proposal.md
|
||||||
|
printf "## 1. Implementation\n- [ ] 1.1 ...\n" > openspec/changes/$CHANGE/tasks.md
|
||||||
|
|
||||||
|
# 3) Add deltas (example)
|
||||||
|
cat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'
|
||||||
|
## ADDED Requirements
|
||||||
|
### Requirement: Two-Factor Authentication
|
||||||
|
Users MUST provide a second factor during login.
|
||||||
|
|
||||||
|
#### Scenario: OTP required
|
||||||
|
- **WHEN** valid credentials are provided
|
||||||
|
- **THEN** an OTP challenge is required
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# 4) Validate
|
||||||
|
openspec validate $CHANGE --strict --no-interactive
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multi-Capability Example
|
||||||
|
|
||||||
|
```
|
||||||
|
openspec/changes/add-2fa-notify/
|
||||||
|
├── proposal.md
|
||||||
|
├── tasks.md
|
||||||
|
└── specs/
|
||||||
|
├── auth/
|
||||||
|
│ └── spec.md # ADDED: Two-Factor Authentication
|
||||||
|
└── notifications/
|
||||||
|
└── spec.md # ADDED: OTP email notification
|
||||||
|
```
|
||||||
|
|
||||||
|
auth/spec.md
|
||||||
|
```markdown
|
||||||
|
## ADDED Requirements
|
||||||
|
### Requirement: Two-Factor Authentication
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
notifications/spec.md
|
||||||
|
```markdown
|
||||||
|
## ADDED Requirements
|
||||||
|
### Requirement: OTP Email Notification
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Simplicity First
|
||||||
|
- Default to <100 lines of new code
|
||||||
|
- Single-file implementations until proven insufficient
|
||||||
|
- Avoid frameworks without clear justification
|
||||||
|
- Choose boring, proven patterns
|
||||||
|
|
||||||
|
### Complexity Triggers
|
||||||
|
Only add complexity with:
|
||||||
|
- Performance data showing current solution too slow
|
||||||
|
- Concrete scale requirements (>1000 users, >100MB data)
|
||||||
|
- Multiple proven use cases requiring abstraction
|
||||||
|
|
||||||
|
### Clear References
|
||||||
|
- Use `file.ts:42` format for code locations
|
||||||
|
- Reference specs as `specs/auth/spec.md`
|
||||||
|
- Link related changes and PRs
|
||||||
|
|
||||||
|
### Capability Naming
|
||||||
|
- Use verb-noun: `user-auth`, `payment-capture`
|
||||||
|
- Single purpose per capability
|
||||||
|
- 10-minute understandability rule
|
||||||
|
- Split if description needs "AND"
|
||||||
|
|
||||||
|
### Change ID Naming
|
||||||
|
- Use kebab-case, short and descriptive: `add-two-factor-auth`
|
||||||
|
- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`
|
||||||
|
- Ensure uniqueness; if taken, append `-2`, `-3`, etc.
|
||||||
|
|
||||||
|
## Tool Selection Guide
|
||||||
|
|
||||||
|
| Task | Tool | Why |
|
||||||
|
|------|------|-----|
|
||||||
|
| Find files by pattern | Glob | Fast pattern matching |
|
||||||
|
| Search code content | Grep | Optimized regex search |
|
||||||
|
| Read specific files | Read | Direct file access |
|
||||||
|
| Explore unknown scope | Task | Multi-step investigation |
|
||||||
|
|
||||||
|
## Error Recovery
|
||||||
|
|
||||||
|
### Change Conflicts
|
||||||
|
1. Run `openspec list` to see active changes
|
||||||
|
2. Check for overlapping specs
|
||||||
|
3. Coordinate with change owners
|
||||||
|
4. Consider combining proposals
|
||||||
|
|
||||||
|
### Validation Failures
|
||||||
|
1. Run with `--strict` flag
|
||||||
|
2. Check JSON output for details
|
||||||
|
3. Verify spec file format
|
||||||
|
4. Ensure scenarios properly formatted
|
||||||
|
|
||||||
|
### Missing Context
|
||||||
|
1. Read project.md first
|
||||||
|
2. Check related specs
|
||||||
|
3. Review recent archives
|
||||||
|
4. Ask for clarification
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
### Stage Indicators
|
||||||
|
- `changes/` - Proposed, not yet built
|
||||||
|
- `specs/` - Built and deployed
|
||||||
|
- `archive/` - Completed changes
|
||||||
|
|
||||||
|
### File Purposes
|
||||||
|
- `proposal.md` - Why and what
|
||||||
|
- `tasks.md` - Implementation steps
|
||||||
|
- `design.md` - Technical decisions
|
||||||
|
- `spec.md` - Requirements and behavior
|
||||||
|
|
||||||
|
### CLI Essentials
|
||||||
|
```bash
|
||||||
|
openspec list # What's in progress?
|
||||||
|
openspec show [item] # View details
|
||||||
|
openspec validate --strict --no-interactive # Is it correct?
|
||||||
|
openspec archive <change-id> [--yes|-y] # Mark complete (add --yes for automation)
|
||||||
|
```
|
||||||
|
|
||||||
|
Remember: Specs are truth. Changes are proposals. Keep them in sync.
|
||||||
@@ -0,0 +1,434 @@
|
|||||||
|
# Design: LLM 趋势告警历史上下文判断
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本设计文档描述如何在 LLM 趋势分析流程中增加历史告警上下文,让 LLM 基于历史告警内容判断本次是否需要发送通知,从而避免重复告警和通知疲劳。
|
||||||
|
|
||||||
|
## 架构设计
|
||||||
|
|
||||||
|
### 数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
1. 获取价格数据 (最近 30 个数据点)
|
||||||
|
↓
|
||||||
|
2. 获取历史告警记录 (最近 3 次 triggered=true 的记录)
|
||||||
|
↓
|
||||||
|
3. 构建 LLM Prompt (包含价格数据 + 历史告警上下文)
|
||||||
|
↓
|
||||||
|
4. 调用 LLM API
|
||||||
|
↓
|
||||||
|
5. 解析响应 (包含 shouldNotify 和 notifyReason)
|
||||||
|
↓
|
||||||
|
6. 判断是否触发告警 (现有条件 + shouldNotify)
|
||||||
|
↓
|
||||||
|
7. 保存分析记录 (包含通知决策)
|
||||||
|
↓
|
||||||
|
8. 发送或跳过通知 (根据 shouldNotify)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 组件交互
|
||||||
|
|
||||||
|
```
|
||||||
|
SilverTrendAnalyzer
|
||||||
|
├─> DatabaseService.getRecentTriggeredAnalyses(3) // 获取历史告警
|
||||||
|
├─> DatabaseService.getRecentPricePoints(30) // 获取价格数据
|
||||||
|
├─> LLMClient.analyzeTrendWithHistory(data, history) // 调用 LLM
|
||||||
|
├─> shouldTriggerAlert(response, previous, dataPoints) // 判断触发条件
|
||||||
|
├─> checkShouldNotify(response) // 检查通知决策
|
||||||
|
└─> sendTrendAlert(record) or skipAlert(record) // 发送或跳过
|
||||||
|
```
|
||||||
|
|
||||||
|
## 详细设计
|
||||||
|
|
||||||
|
### 1. 数据库服务扩展
|
||||||
|
|
||||||
|
**新增方法**: `getRecentTriggeredAnalyses(count: number)`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
/**
|
||||||
|
* 获取最近 N 次已触发告警的分析记录
|
||||||
|
* @param count 获取的记录数量
|
||||||
|
* @returns 已触发告警的分析记录数组(按时间倒序)
|
||||||
|
*/
|
||||||
|
getRecentTriggeredAnalyses(count: number): TrendAnalysisRecord[] {
|
||||||
|
return this.trendAnalysisData.analyses
|
||||||
|
.filter(record => record.triggered === true)
|
||||||
|
.slice(-count)
|
||||||
|
.reverse();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**设计考虑**:
|
||||||
|
- 只返回 `triggered: true` 的记录,因为只有这些记录发送了通知
|
||||||
|
- 按时间倒序返回,最新的在前
|
||||||
|
- 如果历史记录不足 count 个,返回所有可用记录
|
||||||
|
|
||||||
|
### 2. LLM 客户端扩展
|
||||||
|
|
||||||
|
**新增方法**: `analyzeTrendWithHistory(data, history)`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
/**
|
||||||
|
* 分析价格趋势(包含历史告警上下文)
|
||||||
|
* @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);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Prompt 构建策略**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
private buildPromptWithHistory(
|
||||||
|
data: PriceDataPoint[],
|
||||||
|
history: TrendAnalysisRecord[]
|
||||||
|
): string {
|
||||||
|
const dataText = this.formatDataPoints(data);
|
||||||
|
const historyText = this.formatHistoryContext(history);
|
||||||
|
|
||||||
|
return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。
|
||||||
|
|
||||||
|
**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**
|
||||||
|
|
||||||
|
以下是白银最近 30 分钟的价格数据(每分钟一次):
|
||||||
|
|
||||||
|
${dataText}
|
||||||
|
|
||||||
|
${historyText}
|
||||||
|
|
||||||
|
请重点分析**最近 10 分钟**的价格趋势,并提供:
|
||||||
|
1. 趋势判断: uptrend/downtrend/sideways/volatile
|
||||||
|
2. 置信度: 0-1 之间的数值
|
||||||
|
3. 趋势总结: 用 1-2 句话描述最近 10 分钟的价格走势
|
||||||
|
4. 关键信号: 列出你观察到的 3-5 个关键信号
|
||||||
|
5. 风险评估: low/medium/high
|
||||||
|
6. **通知决策**: 判断是否应该发送通知(shouldNotify: true/false)
|
||||||
|
7. **通知原因**: 说明为什么应该或不应该发送通知(notifyReason)
|
||||||
|
|
||||||
|
**通知决策标准**:
|
||||||
|
- 如果本次分析与最近的历史告警**高度相似**(趋势类型相同、总结内容大部分重复、信号列表高度重叠),则 shouldNotify 应为 false
|
||||||
|
- 如果出现**新的重要变化**(趋势反转、新的风险信号、波动幅度显著变化),则 shouldNotify 应为 true
|
||||||
|
- 如果没有历史告警记录,则 shouldNotify 应为 true
|
||||||
|
- 相似度判断应综合考虑:趋势类型、总结内容、信号列表、风险评估
|
||||||
|
|
||||||
|
**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
|
||||||
|
{
|
||||||
|
"trend": "uptrend|downtrend|sideways|volatile",
|
||||||
|
"confidence": 0.85,
|
||||||
|
"summary": "...",
|
||||||
|
"signals": ["...", "...", "..."],
|
||||||
|
"risk": "low|medium|high",
|
||||||
|
"shouldNotify": true,
|
||||||
|
"notifyReason": "..."
|
||||||
|
}`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**历史上下文格式化**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
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}
|
||||||
|
|
||||||
|
请比较本次分析与上述历史告警的相似度,判断是否需要再次发送通知。`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**响应解析扩展**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
private parseResponseWithNotify(response: string): TrendAnalysisResponse {
|
||||||
|
const parsed = JSON.parse(response);
|
||||||
|
|
||||||
|
// 验证必需字段(包括新增字段)
|
||||||
|
const requiredFields = [
|
||||||
|
'trend', 'confidence', 'summary',
|
||||||
|
'signals', 'risk', 'shouldNotify', 'notifyReason'
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const field of requiredFields) {
|
||||||
|
if (!(field in parsed)) {
|
||||||
|
// 如果缺少 shouldNotify,默认为 true(保守策略)
|
||||||
|
if (field === 'shouldNotify') {
|
||||||
|
parsed.shouldNotify = true;
|
||||||
|
parsed.notifyReason = '未提供通知决策,默认发送通知';
|
||||||
|
} else {
|
||||||
|
throw new Error(`响应缺少必需字段: ${field}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 趋势分析服务调整
|
||||||
|
|
||||||
|
**修改 `analyzeTrend()` 方法**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取历史告警记录
|
||||||
|
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)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 保存分析记录
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 类型定义扩展
|
||||||
|
|
||||||
|
**扩展 `TrendAnalysisResponse` 接口**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export interface TrendAnalysisResponse {
|
||||||
|
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
|
||||||
|
confidence: number;
|
||||||
|
summary: string;
|
||||||
|
signals: string[];
|
||||||
|
risk: 'low' | 'medium' | 'high';
|
||||||
|
shouldNotify: boolean; // 新增:是否应该发送通知
|
||||||
|
notifyReason: string; // 新增:通知或跳过的原因
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**扩展 `TrendAnalysisRecord` 接口**(可选,用于记录通知决策):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export interface TrendAnalysisRecord {
|
||||||
|
id: string;
|
||||||
|
timestamp: string;
|
||||||
|
dataPoints: PriceDataPoint[];
|
||||||
|
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
|
||||||
|
confidence: number;
|
||||||
|
summary: string;
|
||||||
|
signals: string[];
|
||||||
|
risk: 'low' | 'medium' | 'high';
|
||||||
|
triggered: boolean;
|
||||||
|
llmResponseRaw: string;
|
||||||
|
shouldNotify?: boolean; // 新增(可选):LLM 的通知决策
|
||||||
|
notifyReason?: string; // 新增(可选):通知决策原因
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 边界情况处理
|
||||||
|
|
||||||
|
### 1. 历史记录不足
|
||||||
|
|
||||||
|
**场景**: 系统刚启动,还没有历史告警记录
|
||||||
|
|
||||||
|
**处理**:
|
||||||
|
- `getRecentTriggeredAnalyses(3)` 返回空数组
|
||||||
|
- Prompt 中说明"无历史告警记录"
|
||||||
|
- LLM 应返回 `shouldNotify: true`(首次告警应该发送)
|
||||||
|
|
||||||
|
### 2. LLM 未返回通知决策
|
||||||
|
|
||||||
|
**场景**: LLM 响应中缺少 `shouldNotify` 或 `notifyReason` 字段
|
||||||
|
|
||||||
|
**处理**:
|
||||||
|
- 默认 `shouldNotify: true`(保守策略,避免漏发重要告警)
|
||||||
|
- 默认 `notifyReason: "未提供通知决策,默认发送通知"`
|
||||||
|
- 记录警告日志
|
||||||
|
|
||||||
|
### 3. 告警触发条件不满足
|
||||||
|
|
||||||
|
**场景**: 现有的告警触发条件(趋势反转、剧烈波动、高风险)不满足
|
||||||
|
|
||||||
|
**处理**:
|
||||||
|
- 即使 `shouldNotify: true`,也不发送告警
|
||||||
|
- 保持现有的告警触发逻辑优先级
|
||||||
|
- 只有在满足触发条件后,才进一步检查 `shouldNotify`
|
||||||
|
|
||||||
|
### 4. 相似度判断失误
|
||||||
|
|
||||||
|
**场景**: LLM 错误地判断为相似,导致漏发重要告警
|
||||||
|
|
||||||
|
**缓解措施**:
|
||||||
|
- 在 Prompt 中明确定义"高度相似"的标准
|
||||||
|
- 强调"新的重要变化"应该发送通知
|
||||||
|
- 保留完整的分析记录,便于事后审计
|
||||||
|
- 可通过调整 Prompt 或增加规则来优化判断
|
||||||
|
|
||||||
|
## 性能和成本
|
||||||
|
|
||||||
|
### Token 消耗估算
|
||||||
|
|
||||||
|
- 价格数据(30 个点): ~500 tokens
|
||||||
|
- 历史告警上下文(3 条): ~300 tokens
|
||||||
|
- Prompt 指令: ~800 tokens
|
||||||
|
- **总输入**: ~1600 tokens (增加约 300 tokens)
|
||||||
|
|
||||||
|
- LLM 响应: ~200 tokens
|
||||||
|
|
||||||
|
**成本影响**:
|
||||||
|
- 使用 `gpt-4o-mini`: 输入 $0.15/1M tokens, 输出 $0.60/1M tokens
|
||||||
|
- 每次分析成本: ~$0.0004 (增加约 $0.0001)
|
||||||
|
- 每天成本(10分钟间隔): ~$0.06 (增加约 $0.01)
|
||||||
|
|
||||||
|
**成本优化**:
|
||||||
|
- 通过减少重复告警,可能降低整体通知成本
|
||||||
|
- 历史上下文数量可配置(1-5 条),允许用户权衡成本和效果
|
||||||
|
|
||||||
|
## 测试策略
|
||||||
|
|
||||||
|
### 单元测试
|
||||||
|
|
||||||
|
1. **数据库服务测试**:
|
||||||
|
- 测试 `getRecentTriggeredAnalyses()` 正确过滤和排序
|
||||||
|
- 测试历史记录不足时的行为
|
||||||
|
|
||||||
|
2. **LLM 客户端测试**:
|
||||||
|
- 测试历史上下文格式化
|
||||||
|
- 测试响应解析(包含新字段)
|
||||||
|
- 测试缺少 `shouldNotify` 时的默认行为
|
||||||
|
|
||||||
|
3. **趋势分析服务测试**:
|
||||||
|
- 测试告警触发逻辑(现有条件 + shouldNotify)
|
||||||
|
- 测试跳过通知的日志输出
|
||||||
|
|
||||||
|
### 集成测试
|
||||||
|
|
||||||
|
1. **端到端测试**:
|
||||||
|
- 模拟连续多次分析,验证历史上下文传递
|
||||||
|
- 验证相似告警被正确跳过
|
||||||
|
- 验证新变化触发通知
|
||||||
|
|
||||||
|
2. **边界情况测试**:
|
||||||
|
- 首次分析(无历史记录)
|
||||||
|
- LLM 响应异常(缺少字段)
|
||||||
|
- 历史记录数量不足 3 条
|
||||||
|
|
||||||
|
## 向后兼容性
|
||||||
|
|
||||||
|
### 数据兼容性
|
||||||
|
|
||||||
|
- 新增字段为可选(`shouldNotify?`, `notifyReason?`)
|
||||||
|
- 现有数据记录不受影响
|
||||||
|
- 旧版本分析记录可以正常读取
|
||||||
|
|
||||||
|
### API 兼容性
|
||||||
|
|
||||||
|
- 保留原有的 `analyzeTrend()` 方法签名
|
||||||
|
- 内部实现调整,外部接口不变
|
||||||
|
- 现有的告警触发逻辑保持优先级
|
||||||
|
|
||||||
|
## 监控和调试
|
||||||
|
|
||||||
|
### 日志输出
|
||||||
|
|
||||||
|
```
|
||||||
|
开始 LLM 趋势总结
|
||||||
|
获取到 3 条历史告警记录
|
||||||
|
调用 LLM API(包含历史告警上下文)
|
||||||
|
LLM 响应成功
|
||||||
|
趋势: uptrend
|
||||||
|
置信度: 85%
|
||||||
|
风险: medium
|
||||||
|
通知决策: 跳过
|
||||||
|
决策原因: 本次分析与最近一次告警高度相似,趋势类型相同,总结内容重复度高
|
||||||
|
⏭️ 满足告警条件但跳过通知: 本次分析与最近一次告警高度相似,趋势类型相同,总结内容重复度高
|
||||||
|
```
|
||||||
|
|
||||||
|
### 调试信息
|
||||||
|
|
||||||
|
- 在 `llmResponseRaw` 中保存完整的 LLM 响应
|
||||||
|
- 记录历史告警上下文的内容
|
||||||
|
- 记录通知决策的原因
|
||||||
|
|
||||||
|
## 总结
|
||||||
|
|
||||||
|
本设计通过在 LLM 分析流程中增加历史告警上下文,让 LLM 基于历史内容判断是否需要发送通知,从而有效避免重复告警和通知疲劳。设计保持了向后兼容性,并提供了完善的边界情况处理和调试支持。
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# Change: LLM 趋势告警增加历史上下文判断
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
当前 LLM 趋势告警系统在每次分析时独立判断是否触发告警,缺乏对历史告警的感知能力。
|
||||||
|
|
||||||
|
**现有功能的局限性**:
|
||||||
|
- 每次分析都是独立的,不考虑最近的告警历史
|
||||||
|
- 可能出现重复告警:如果趋势持续相同,会反复发送相似的告警
|
||||||
|
- 缺乏对告警内容相似度的判断
|
||||||
|
- 无法避免"通知疲劳"问题
|
||||||
|
|
||||||
|
**用户需求**:
|
||||||
|
- 避免发送重复或相似的告警通知
|
||||||
|
- 让 LLM 基于历史告警内容判断本次是否需要再次通知
|
||||||
|
- 如果本次总结与之前类似或大部分相同,应跳过本次通知
|
||||||
|
- 减少不必要的通知,提高告警的有效性
|
||||||
|
|
||||||
|
**业务价值**:
|
||||||
|
- 减少通知疲劳,提高用户对告警的关注度
|
||||||
|
- 避免重复信息干扰,让用户专注于真正重要的变化
|
||||||
|
- 提升系统的智能化水平,让 LLM 做出更合理的通知决策
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
在 LLM 趋势分析流程中增加历史告警上下文判断:
|
||||||
|
- 在调用 LLM 分析时,将最近 3 次**已触发告警**的分析记录作为上下文提供给模型
|
||||||
|
- 让 LLM 判断本次分析结果是否与历史告警相似
|
||||||
|
- 如果相似度高(内容大部分相同),则跳过本次告警
|
||||||
|
- 在 Prompt 中明确要求 LLM 输出是否应该发送通知的判断
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
### 新增功能
|
||||||
|
- ✅ **历史告警上下文** - 提供最近 3 次已触发告警的记录给 LLM
|
||||||
|
- ✅ **相似度判断** - LLM 判断本次分析是否与历史告警相似
|
||||||
|
- ✅ **智能通知决策** - 基于相似度自动决定是否发送通知
|
||||||
|
- ✅ **通知原因说明** - 在日志中记录为什么发送或跳过通知
|
||||||
|
|
||||||
|
### 受影响的文件
|
||||||
|
- `src/services/silver-trend-analyzer.ts` - 修改告警判断逻辑,增加历史上下文
|
||||||
|
- `src/utils/llm-client.ts` - 修改 Prompt 构建,增加历史告警上下文和通知判断
|
||||||
|
- `src/types/index.ts` - 扩展 `TrendAnalysisResponse` 类型,增加 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
- `src/services/database.ts` - 增加获取最近 N 次已触发告警记录的方法
|
||||||
|
|
||||||
|
### 不受影响
|
||||||
|
- 现有的趋势分析逻辑保持不变
|
||||||
|
- 数据存储结构保持兼容(新增字段为可选)
|
||||||
|
- 白银基线监控功能不受影响
|
||||||
|
|
||||||
|
## 技术实现要点
|
||||||
|
|
||||||
|
### 历史告警上下文
|
||||||
|
- 从数据库获取最近 3 次 `triggered: true` 的分析记录
|
||||||
|
- 提取关键信息:趋势类型、总结、信号、风险评估
|
||||||
|
- 格式化为简洁的文本,作为 Prompt 的一部分
|
||||||
|
|
||||||
|
### LLM 判断逻辑
|
||||||
|
- 在 Prompt 中明确要求 LLM 比较本次分析与历史告警的相似度
|
||||||
|
- 要求 LLM 输出 `shouldNotify` 布尔值和 `notifyReason` 说明
|
||||||
|
- 相似度判断标准:
|
||||||
|
- 趋势类型相同
|
||||||
|
- 总结内容大部分相同(关键信息重复)
|
||||||
|
- 信号列表高度重叠
|
||||||
|
- 风险评估相同
|
||||||
|
|
||||||
|
### 响应结构扩展
|
||||||
|
```typescript
|
||||||
|
interface TrendAnalysisResponse {
|
||||||
|
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
|
||||||
|
confidence: number;
|
||||||
|
summary: string;
|
||||||
|
signals: string[];
|
||||||
|
risk: 'low' | 'medium' | 'high';
|
||||||
|
shouldNotify: boolean; // 新增:是否应该发送通知
|
||||||
|
notifyReason: string; // 新增:通知或跳过的原因
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 告警触发逻辑调整
|
||||||
|
- 保留现有的告警触发条件(趋势反转、剧烈波动、高风险)
|
||||||
|
- 在满足触发条件后,进一步检查 `shouldNotify` 字段
|
||||||
|
- 如果 `shouldNotify: false`,则跳过告警,但仍记录分析结果
|
||||||
|
- 在日志中输出 `notifyReason`,说明决策原因
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 成本考虑
|
||||||
|
- 增加历史上下文会略微增加 Prompt 长度(约 200-300 tokens)
|
||||||
|
- 预计每次分析成本增加约 $0.0001-0.0002
|
||||||
|
- 但通过减少重复告警,可能降低整体通知成本
|
||||||
|
|
||||||
|
### 可靠性考虑
|
||||||
|
- 如果 LLM 未返回 `shouldNotify` 字段,默认为 `true`(保守策略)
|
||||||
|
- 确保不会因为新功能导致漏发重要告警
|
||||||
|
- 保留完整的分析记录,即使跳过通知
|
||||||
|
|
||||||
|
### 用户体验
|
||||||
|
- 减少重复通知,提高告警质量
|
||||||
|
- 在日志中清晰记录跳过原因,便于调试和审计
|
||||||
|
- 保持告警的及时性,不影响重要信号的通知
|
||||||
|
|
||||||
|
## 未来扩展方向
|
||||||
|
|
||||||
|
- 支持配置历史告警上下文的数量(默认 3 次,可调整为 1-5 次)
|
||||||
|
- 支持配置相似度阈值,允许用户自定义判断标准
|
||||||
|
- 提供告警历史查询接口,方便用户查看被跳过的分析
|
||||||
|
- 增加告警统计功能,展示发送率、跳过率等指标
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
# silver-trend-analysis Specification Delta
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: LLM 趋势总结服务
|
||||||
|
系统 SHALL 提供 LLM 趋势总结服务,定期调用 LLM API 总结白银价格趋势,**并基于历史告警上下文判断是否需要发送通知**。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `SilverTrendAnalyzer` 服务类
|
||||||
|
- 使用可配置的定时器触发总结(默认 10 分钟)
|
||||||
|
- 从数据库获取最近 10 分钟的价格数据
|
||||||
|
- **从数据库获取最近 3 次已触发告警的分析记录**
|
||||||
|
- 调用 LLM API 进行趋势总结,**包含历史告警上下文**
|
||||||
|
- 解析 LLM 的结构化响应,**包含通知决策字段**
|
||||||
|
|
||||||
|
#### Scenario: 定时执行趋势总结(包含历史上下文)
|
||||||
|
- **WHEN** 系统启动且配置了 LLM API Key
|
||||||
|
- **THEN** 首次延迟 10 分钟后执行第一次总结(等待数据积累)
|
||||||
|
- **AND** 之后按照配置的间隔(默认 10 分钟)定期执行总结
|
||||||
|
- **AND** 每次从数据库获取最近 30 个价格数据点(作为上下文)
|
||||||
|
- **AND** **每次从数据库获取最近 3 次 `triggered: true` 的分析记录**
|
||||||
|
- **AND** 让 LLM 重点总结最近 10 分钟的趋势
|
||||||
|
- **AND** **让 LLM 判断本次分析是否与历史告警相似,决定是否发送通知**
|
||||||
|
|
||||||
|
#### Scenario: LLM API 调用成功(包含通知决策)
|
||||||
|
- **WHEN** LLM API 成功返回总结结果
|
||||||
|
- **THEN** 解析 JSON 格式的响应
|
||||||
|
- **AND** 提取趋势类型、置信度、总结、信号等字段
|
||||||
|
- **AND** **提取 `shouldNotify` 和 `notifyReason` 字段**
|
||||||
|
- **AND** 保存分析记录到数据库
|
||||||
|
- **AND** 判断是否需要触发告警,**同时考虑现有触发条件和 `shouldNotify` 字段**
|
||||||
|
|
||||||
|
#### Scenario: 历史告警记录不足
|
||||||
|
- **WHEN** 数据库中已触发告警的记录少于 3 条
|
||||||
|
- **THEN** 获取所有可用的已触发告警记录
|
||||||
|
- **AND** 在 Prompt 中说明历史记录数量
|
||||||
|
- **AND** LLM 应基于可用的历史记录进行判断
|
||||||
|
- **AND** 如果没有历史记录,LLM 应返回 `shouldNotify: true`
|
||||||
|
|
||||||
|
#### Scenario: LLM 未返回通知决策字段
|
||||||
|
- **WHEN** LLM 响应中缺少 `shouldNotify` 或 `notifyReason` 字段
|
||||||
|
- **THEN** 默认 `shouldNotify: true`(保守策略,避免漏发重要告警)
|
||||||
|
- **AND** 默认 `notifyReason: "未提供通知决策,默认发送通知"`
|
||||||
|
- **AND** 记录警告日志:"LLM 响应缺少通知决策字段,使用默认值"
|
||||||
|
|
||||||
|
### Requirement: LLM API 客户端
|
||||||
|
系统 SHALL 提供 LLM API 客户端,封装与 OpenAI 兼容 API 的交互,**支持包含历史告警上下文的趋势分析**。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `LLMClient` 工具类
|
||||||
|
- 支持配置 API Base URL、API Key、模型名称
|
||||||
|
- 构建专业的金融分析 Prompt,**包含历史告警上下文**
|
||||||
|
- 解析结构化的 JSON 响应,**包含通知决策字段**
|
||||||
|
|
||||||
|
#### Scenario: 构建总结 Prompt(包含历史告警上下文)
|
||||||
|
- **WHEN** 调用 `buildPromptWithHistory(data, history)` 方法
|
||||||
|
- **THEN** 将最近 30 分钟的价格数据格式化为易读的文本表格
|
||||||
|
- **AND** 包含时间、价格、变化、波动等信息
|
||||||
|
- **AND** **将最近 3 次已触发告警的记录格式化为历史上下文**
|
||||||
|
- **AND** **历史上下文包含:时间、趋势类型、总结、信号、风险评估**
|
||||||
|
- **AND** 添加 LLM 任务说明:
|
||||||
|
- 提供最近 30 分钟的数据作为上下文
|
||||||
|
- 重点总结最近 10 分钟的价格趋势
|
||||||
|
- **比较本次分析与历史告警的相似度**
|
||||||
|
- **判断是否需要发送通知(`shouldNotify`)**
|
||||||
|
- **说明通知或跳过的原因(`notifyReason`)**
|
||||||
|
- 不预测未来走势
|
||||||
|
- **AND** 要求返回 JSON 格式的结构化响应
|
||||||
|
- **AND** Prompt 长度控制在 2000 tokens 以内
|
||||||
|
|
||||||
|
#### Scenario: 格式化历史告警上下文
|
||||||
|
- **WHEN** 调用 `formatHistoryContext(history)` 方法
|
||||||
|
- **THEN** 如果 `history` 为空数组:
|
||||||
|
- 返回 "**历史告警记录**: 无(这是首次分析或首次触发告警)"
|
||||||
|
- **AND** 如果 `history` 不为空:
|
||||||
|
- 对每条记录格式化为:
|
||||||
|
- 时间戳(本地时间格式)
|
||||||
|
- 趋势类型
|
||||||
|
- 总结内容
|
||||||
|
- 信号列表(用分号连接)
|
||||||
|
- 风险评估
|
||||||
|
- 置信度(百分比)
|
||||||
|
- 返回格式化后的文本,包含标题 "**最近 N 次历史告警记录**:"
|
||||||
|
|
||||||
|
#### Scenario: 解析 LLM 响应(包含通知决策)
|
||||||
|
- **WHEN** 调用 `parseResponseWithNotify(response)` 方法
|
||||||
|
- **THEN** 尝试解析 JSON 格式的响应
|
||||||
|
- **AND** 验证包含必需字段:trend、confidence、summary、signals、risk、**shouldNotify**、**notifyReason**
|
||||||
|
- **AND** 如果缺少 `shouldNotify` 字段:
|
||||||
|
- 设置默认值 `shouldNotify: true`
|
||||||
|
- 设置默认值 `notifyReason: "未提供通知决策,默认发送通知"`
|
||||||
|
- **AND** 如果缺少 `notifyReason` 字段:
|
||||||
|
- 设置默认值 `notifyReason: "未提供原因说明"`
|
||||||
|
- **AND** 如果解析失败,抛出包含错误详情的异常
|
||||||
|
|
||||||
|
### Requirement: 趋势数据存储
|
||||||
|
系统 SHALL 在数据库中存储趋势总结记录,**包含通知决策信息**。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 扩展 `DatabaseService` 添加趋势数据管理方法
|
||||||
|
- **新增 `getRecentTriggeredAnalyses(count)` 方法**
|
||||||
|
- 创建 `src/data/silver-trends.json` 文件
|
||||||
|
- 存储分析记录、LLM 原始响应等信息
|
||||||
|
|
||||||
|
#### Scenario: 获取最近的已触发告警记录
|
||||||
|
- **WHEN** 调用 `getRecentTriggeredAnalyses(count)` 方法
|
||||||
|
- **THEN** 从 `silver-trends.json` 的 `analyses` 数组中筛选 `triggered: true` 的记录
|
||||||
|
- **AND** 按时间戳倒序排列(最新的在前)
|
||||||
|
- **AND** 返回最近的 `count` 条记录
|
||||||
|
- **AND** 如果可用记录少于 `count`,返回所有可用记录
|
||||||
|
- **AND** 如果没有已触发告警的记录,返回空数组
|
||||||
|
|
||||||
|
#### Scenario: 保存趋势分析记录(包含通知决策)
|
||||||
|
- **WHEN** 趋势总结完成
|
||||||
|
- **THEN** 创建包含以下字段的记录:
|
||||||
|
- `id`:唯一标识符(UUID)
|
||||||
|
- `timestamp`:分析时间戳
|
||||||
|
- `dataPoints`:使用的价格数据点
|
||||||
|
- `trend`:趋势类型(uptrend/downtrend/sideways/volatile)
|
||||||
|
- `confidence`:置信度(0-1)
|
||||||
|
- `summary`:趋势总结
|
||||||
|
- `signals`:关键信号列表
|
||||||
|
- `risk`:风险评估(low/medium/high)
|
||||||
|
- `triggered`:是否触发告警(现有条件 AND shouldNotify)
|
||||||
|
- `llmResponseRaw`:LLM 原始响应
|
||||||
|
- **`shouldNotify`(可选):LLM 的通知决策**
|
||||||
|
- **`notifyReason`(可选):通知决策原因**
|
||||||
|
- **AND** 将记录追加到 `silver-trends.json` 的 `analyses` 数组
|
||||||
|
- **AND** 保持最多 1000 条记录(超过后删除最旧的记录)
|
||||||
|
|
||||||
|
### Requirement: 趋势告警判断
|
||||||
|
系统 SHALL 根据趋势分析结果智能判断是否需要发送告警,**同时考虑 LLM 的通知决策**。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 实现多条件告警触发逻辑
|
||||||
|
- 对比当前分析和上次分析,检测趋势变化
|
||||||
|
- 根据趋势类型、置信度、风险评估等综合判断
|
||||||
|
- **在满足触发条件后,进一步检查 `shouldNotify` 字段**
|
||||||
|
|
||||||
|
#### Scenario: 综合判断是否发送告警
|
||||||
|
- **WHEN** 趋势分析完成
|
||||||
|
- **THEN** 首先判断是否满足现有的告警触发条件:
|
||||||
|
- 趋势反转(置信度 > 0.6)
|
||||||
|
- 剧烈波动(trend = volatile 且置信度 > 0.7 且波动幅度 > 0.2)
|
||||||
|
- 高风险信号(risk = high 且置信度 > 0.8)
|
||||||
|
- **AND** 如果满足触发条件:
|
||||||
|
- 进一步检查 `shouldNotify` 字段
|
||||||
|
- 如果 `shouldNotify: true`,发送告警
|
||||||
|
- 如果 `shouldNotify: false`,跳过告警,记录原因
|
||||||
|
- **AND** 如果不满足触发条件:
|
||||||
|
- 不发送告警,无论 `shouldNotify` 的值
|
||||||
|
|
||||||
|
#### Scenario: 跳过相似告警
|
||||||
|
- **WHEN** 满足告警触发条件但 `shouldNotify: false`
|
||||||
|
- **THEN** 不发送飞书告警
|
||||||
|
- **AND** 在控制台输出:"⏭️ 满足告警条件但跳过通知: {notifyReason}"
|
||||||
|
- **AND** 将 `triggered` 字段设置为 `false`(因为实际未发送通知)
|
||||||
|
- **AND** 保存完整的分析记录(包含 `shouldNotify` 和 `notifyReason`)
|
||||||
|
|
||||||
|
#### Scenario: 发送新告警
|
||||||
|
- **WHEN** 满足告警触发条件且 `shouldNotify: true`
|
||||||
|
- **THEN** 发送飞书告警
|
||||||
|
- **AND** 在控制台输出:"⚠️ 触发趋势告警!"
|
||||||
|
- **AND** 将 `triggered` 字段设置为 `true`
|
||||||
|
- **AND** 保存完整的分析记录
|
||||||
|
|
||||||
|
### Requirement: 主程序集成
|
||||||
|
系统 SHALL 在主程序中集成 LLM 趋势分析功能,**支持历史告警上下文判断**。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `App` 类中添加 `trendAnalyzer` 成员
|
||||||
|
- 在构造函数中初始化趋势分析服务
|
||||||
|
- 在 `start()` 方法中启动定时分析任务
|
||||||
|
- 确保与白银基线监控并行运行
|
||||||
|
- **在分析流程中集成历史上下文获取和通知决策**
|
||||||
|
|
||||||
|
#### Scenario: 执行趋势分析(包含历史上下文)
|
||||||
|
- **WHEN** 定时器触发趋势分析
|
||||||
|
- **THEN** 调用 `trendAnalyzer.analyzeTrend()` 方法
|
||||||
|
- **AND** 方法内部:
|
||||||
|
- 获取最近 30 个价格数据点
|
||||||
|
- **获取最近 3 次已触发告警的记录**
|
||||||
|
- 调用 `llmClient.analyzeTrendWithHistory(data, history)`
|
||||||
|
- 解析响应,包含 `shouldNotify` 和 `notifyReason`
|
||||||
|
- 判断是否满足告警触发条件
|
||||||
|
- **如果满足条件且 `shouldNotify: true`,发送告警**
|
||||||
|
- **如果满足条件但 `shouldNotify: false`,跳过告警并记录原因**
|
||||||
|
- 保存分析记录
|
||||||
|
|
||||||
|
#### Scenario: 日志输出(包含通知决策)
|
||||||
|
- **WHEN** 趋势分析完成
|
||||||
|
- **THEN** 在控制台输出以下信息:
|
||||||
|
- "开始 LLM 趋势总结"
|
||||||
|
- **"获取到 N 条历史告警记录"**
|
||||||
|
- **"调用 LLM API(包含历史告警上下文)"**
|
||||||
|
- "LLM 响应成功"
|
||||||
|
- " 趋势: {trend}"
|
||||||
|
- " 置信度: {confidence}%"
|
||||||
|
- " 风险: {risk}"
|
||||||
|
- **" 通知决策: {shouldNotify ? '发送' : '跳过'}"**
|
||||||
|
- **" 决策原因: {notifyReason}"**
|
||||||
|
- **AND** 如果满足触发条件且 `shouldNotify: true`:
|
||||||
|
- "⚠️ 触发趋势告警!"
|
||||||
|
- **AND** 如果满足触发条件但 `shouldNotify: false`:
|
||||||
|
- **"⏭️ 满足告警条件但跳过通知: {notifyReason}"**
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: 通知决策字段
|
||||||
|
系统 SHALL 在 LLM 响应和分析记录中包含通知决策相关字段。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 扩展 `TrendAnalysisResponse` 接口,增加 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
- 扩展 `TrendAnalysisRecord` 接口,增加可选的 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
- 确保向后兼容性(新字段为可选)
|
||||||
|
|
||||||
|
#### Scenario: 定义通知决策字段
|
||||||
|
- **WHEN** 定义 `TrendAnalysisResponse` 接口
|
||||||
|
- **THEN** 包含以下字段:
|
||||||
|
- `shouldNotify: boolean` - 是否应该发送通知
|
||||||
|
- `notifyReason: string` - 通知或跳过的原因
|
||||||
|
- **AND** 这两个字段为必需字段
|
||||||
|
|
||||||
|
#### Scenario: 扩展分析记录字段
|
||||||
|
- **WHEN** 定义 `TrendAnalysisRecord` 接口
|
||||||
|
- **THEN** 增加以下可选字段:
|
||||||
|
- `shouldNotify?: boolean` - LLM 的通知决策
|
||||||
|
- `notifyReason?: string` - 通知决策原因
|
||||||
|
- **AND** 这两个字段为可选,保持向后兼容性
|
||||||
|
|
||||||
|
#### Scenario: 默认值处理
|
||||||
|
- **WHEN** LLM 响应中缺少 `shouldNotify` 字段
|
||||||
|
- **THEN** 使用默认值 `true`(保守策略)
|
||||||
|
- **AND** 使用默认 `notifyReason: "未提供通知决策,默认发送通知"`
|
||||||
|
- **AND** 记录警告日志
|
||||||
|
|
||||||
|
### Requirement: 历史告警上下文 Prompt
|
||||||
|
系统 SHALL 在 LLM Prompt 中包含历史告警上下文和通知决策指导。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 Prompt 中添加历史告警记录部分
|
||||||
|
- 明确定义通知决策标准
|
||||||
|
- 要求 LLM 输出 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
|
||||||
|
#### Scenario: Prompt 包含历史告警上下文
|
||||||
|
- **WHEN** 构建 LLM Prompt
|
||||||
|
- **THEN** 在价格数据之后,分析要求之前,插入历史告警上下文部分
|
||||||
|
- **AND** 如果有历史记录:
|
||||||
|
- 标题:"**最近 N 次历史告警记录**:"
|
||||||
|
- 对每条记录列出:时间、趋势、总结、信号、风险、置信度
|
||||||
|
- 说明:"请比较本次分析与上述历史告警的相似度,判断是否需要再次发送通知。"
|
||||||
|
- **AND** 如果没有历史记录:
|
||||||
|
- 说明:"**历史告警记录**: 无(这是首次分析或首次触发告警)"
|
||||||
|
|
||||||
|
#### Scenario: Prompt 包含通知决策指导
|
||||||
|
- **WHEN** 构建 LLM Prompt
|
||||||
|
- **THEN** 在分析要求中增加:
|
||||||
|
- "6. **通知决策**: 判断是否应该发送通知(shouldNotify: true/false)"
|
||||||
|
- "7. **通知原因**: 说明为什么应该或不应该发送通知(notifyReason)"
|
||||||
|
- **AND** 添加 "**通知决策标准**" 部分:
|
||||||
|
- 如果本次分析与最近的历史告警**高度相似**,则 `shouldNotify` 应为 `false`
|
||||||
|
- 如果出现**新的重要变化**,则 `shouldNotify` 应为 `true`
|
||||||
|
- 如果没有历史告警记录,则 `shouldNotify` 应为 `true`
|
||||||
|
- 相似度判断应综合考虑:趋势类型、总结内容、信号列表、风险评估
|
||||||
|
- **AND** 在输出格式中包含 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
|
||||||
|
#### Scenario: 相似度判断标准
|
||||||
|
- **WHEN** LLM 判断是否应该发送通知
|
||||||
|
- **THEN** 应考虑以下因素:
|
||||||
|
- **趋势类型相同**:如果本次和历史告警的趋势类型相同(如都是 uptrend)
|
||||||
|
- **总结内容重复**:如果本次总结与历史总结的关键信息大部分相同
|
||||||
|
- **信号列表重叠**:如果本次信号与历史信号高度重叠(> 70%)
|
||||||
|
- **风险评估相同**:如果本次和历史告警的风险评估相同
|
||||||
|
- **AND** 如果以上因素大部分满足,应判定为"高度相似",`shouldNotify: false`
|
||||||
|
- **AND** 如果出现以下情况,应判定为"新的重要变化",`shouldNotify: true`:
|
||||||
|
- 趋势类型发生变化
|
||||||
|
- 出现新的重要信号
|
||||||
|
- 风险评估升级或降级
|
||||||
|
- 价格波动幅度显著变化
|
||||||
|
|
||||||
|
## 影响范围
|
||||||
|
|
||||||
|
### 修改的文件
|
||||||
|
- `src/services/silver-trend-analyzer.ts` - 修改 `analyzeTrend()` 方法
|
||||||
|
- `src/utils/llm-client.ts` - 新增 `analyzeTrendWithHistory()` 和相关方法
|
||||||
|
- `src/types/index.ts` - 扩展 `TrendAnalysisResponse` 和 `TrendAnalysisRecord` 接口
|
||||||
|
- `src/services/database.ts` - 新增 `getRecentTriggeredAnalyses()` 方法
|
||||||
|
|
||||||
|
### 不受影响的功能
|
||||||
|
- 白银基线监控
|
||||||
|
- 现有的告警触发条件
|
||||||
|
- 飞书告警卡片格式
|
||||||
|
- 数据存储结构(向后兼容)
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
# Implementation Tasks
|
||||||
|
|
||||||
|
## 任务清单
|
||||||
|
|
||||||
|
### 1. 扩展类型定义
|
||||||
|
- [x] 在 `src/types/index.ts` 中扩展 `TrendAnalysisResponse` 接口
|
||||||
|
- [x] 添加 `shouldNotify: boolean` 字段
|
||||||
|
- [x] 添加 `notifyReason: string` 字段
|
||||||
|
- [x] 在 `src/types/index.ts` 中扩展 `TrendAnalysisRecord` 接口
|
||||||
|
- [x] 添加 `shouldNotify?: boolean` 可选字段
|
||||||
|
- [x] 添加 `notifyReason?: string` 可选字段
|
||||||
|
|
||||||
|
### 2. 扩展数据库服务
|
||||||
|
- [x] 在 `src/services/database.ts` 中新增 `getRecentTriggeredAnalyses(count: number)` 方法
|
||||||
|
- [x] 从 `trendAnalysisData.analyses` 中筛选 `triggered: true` 的记录
|
||||||
|
- [x] 按时间戳倒序排列
|
||||||
|
- [x] 返回最近的 `count` 条记录
|
||||||
|
- [x] 如果记录不足,返回所有可用记录
|
||||||
|
- [x] 添加单元测试验证筛选和排序逻辑
|
||||||
|
|
||||||
|
### 3. 扩展 LLM 客户端
|
||||||
|
- [x] 在 `src/utils/llm-client.ts` 中新增 `analyzeTrendWithHistory()` 方法
|
||||||
|
- [x] 接收 `data: PriceDataPoint[]` 和 `history: TrendAnalysisRecord[]` 参数
|
||||||
|
- [x] 调用 `buildPromptWithHistory(data, history)` 构建 Prompt
|
||||||
|
- [x] 调用 `callAPI(prompt)` 获取响应
|
||||||
|
- [x] 调用 `parseResponseWithNotify(response)` 解析响应
|
||||||
|
- [x] 返回包含 `shouldNotify` 和 `notifyReason` 的 `TrendAnalysisResponse`
|
||||||
|
|
||||||
|
- [x] 在 `src/utils/llm-client.ts` 中新增 `buildPromptWithHistory()` 私有方法
|
||||||
|
- [x] 调用 `formatDataPoints(data)` 格式化价格数据
|
||||||
|
- [x] 调用 `formatHistoryContext(history)` 格式化历史告警上下文
|
||||||
|
- [x] 构建包含历史上下文和通知决策指导的 Prompt
|
||||||
|
- [x] 在 Prompt 中明确通知决策标准
|
||||||
|
- [x] 在输出格式中包含 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
|
||||||
|
- [x] 在 `src/utils/llm-client.ts` 中新增 `formatHistoryContext()` 私有方法
|
||||||
|
- [x] 如果 `history` 为空,返回"无历史告警记录"说明
|
||||||
|
- [x] 如果 `history` 不为空,格式化每条记录:
|
||||||
|
- [x] 时间戳(本地时间格式)
|
||||||
|
- [x] 趋势类型
|
||||||
|
- [x] 总结内容
|
||||||
|
- [x] 信号列表(用分号连接)
|
||||||
|
- [x] 风险评估
|
||||||
|
- [x] 置信度(百分比)
|
||||||
|
- [x] 返回格式化后的文本
|
||||||
|
|
||||||
|
- [x] 在 `src/utils/llm-client.ts` 中修改 `parseResponse()` 方法为 `parseResponseWithNotify()`
|
||||||
|
- [x] 验证响应包含 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
- [x] 如果缺少 `shouldNotify`,设置默认值 `true`
|
||||||
|
- [x] 如果缺少 `notifyReason`,设置默认值"未提供通知决策,默认发送通知"
|
||||||
|
- [x] 记录警告日志
|
||||||
|
- [x] 返回完整的 `TrendAnalysisResponse`
|
||||||
|
|
||||||
|
- [x] 保留原有的 `analyzeTrend()` 方法作为向后兼容(可选)
|
||||||
|
- [x] 内部调用 `analyzeTrendWithHistory(data, [])`
|
||||||
|
|
||||||
|
### 4. 修改趋势分析服务
|
||||||
|
- [x] 在 `src/services/silver-trend-analyzer.ts` 中修改 `analyzeTrend()` 方法
|
||||||
|
- [x] 在获取价格数据后,调用 `this.db.getRecentTriggeredAnalyses(3)` 获取历史告警
|
||||||
|
- [x] 记录日志:"获取到 N 条历史告警记录"
|
||||||
|
- [x] 调用 `this.llmClient.analyzeTrendWithHistory(dataPoints, historyAlerts)`
|
||||||
|
- [x] 记录日志:"调用 LLM API(包含历史告警上下文)"
|
||||||
|
- [x] 在响应日志中增加:
|
||||||
|
- [x] "通知决策: {shouldNotify ? '发送' : '跳过'}"
|
||||||
|
- [x] "决策原因: {notifyReason}"
|
||||||
|
|
||||||
|
- [x] 修改告警触发逻辑
|
||||||
|
- [x] 保留现有的 `shouldTriggerAlert()` 判断
|
||||||
|
- [x] 在满足触发条件后,检查 `llmResponse.shouldNotify`
|
||||||
|
- [x] 如果 `shouldNotify: true`,发送告警,记录日志:"⚠️ 触发趋势告警!"
|
||||||
|
- [x] 如果 `shouldNotify: false`,跳过告警,记录日志:"⏭️ 满足告警条件但跳过通知: {notifyReason}"
|
||||||
|
- [x] 将 `triggered` 字段设置为 `shouldAlert && llmResponse.shouldNotify`
|
||||||
|
|
||||||
|
- [x] 在保存分析记录时,包含 `shouldNotify` 和 `notifyReason` 字段(可选)
|
||||||
|
- [x] 从 `llmResponse` 中提取这两个字段
|
||||||
|
- [x] 添加到 `TrendAnalysisRecord` 对象中
|
||||||
|
|
||||||
|
### 5. 测试和验证
|
||||||
|
- [x] 创建测试脚本 `test-llm-history-context.ts`
|
||||||
|
- [x] 模拟有历史告警记录的场景
|
||||||
|
- [x] 模拟无历史告警记录的场景
|
||||||
|
- [x] 验证 LLM 返回 `shouldNotify: false` 时跳过通知
|
||||||
|
- [x] 验证 LLM 返回 `shouldNotify: true` 时发送通知
|
||||||
|
- [x] 验证日志输出包含通知决策信息
|
||||||
|
|
||||||
|
- [x] 创建测试脚本 `test-db-history-method.ts`
|
||||||
|
- [x] 测试 `getRecentTriggeredAnalyses()` 方法
|
||||||
|
- [x] 验证筛选和排序逻辑
|
||||||
|
- [x] 测试边界情况(0条、1条、大量记录)
|
||||||
|
|
||||||
|
- [x] 运行类型检查
|
||||||
|
- [x] 执行 `npm run typecheck`
|
||||||
|
- [x] 确保没有类型错误
|
||||||
|
|
||||||
|
- [x] 运行构建
|
||||||
|
- [x] 执行 `npm run build`
|
||||||
|
- [x] 确保构建成功
|
||||||
|
|
||||||
|
### 6. 文档更新
|
||||||
|
- [ ] 更新 `README.md`
|
||||||
|
- [ ] 在"LLM 趋势总结"部分说明新增的历史上下文判断功能
|
||||||
|
- [ ] 说明如何避免重复告警
|
||||||
|
- [ ] 更新成本估算(增加约 $0.0001/次)
|
||||||
|
|
||||||
|
- [ ] 更新 `.env.example`(如果需要新增配置项)
|
||||||
|
- [ ] 如果支持配置历史告警数量,添加 `TREND_HISTORY_COUNT=3`
|
||||||
|
|
||||||
|
### 7. 代码审查检查清单
|
||||||
|
- [x] 代码符合 TypeScript 严格模式
|
||||||
|
- [x] 新增字段为可选,保持向后兼容性
|
||||||
|
- [x] 错误处理完善(LLM 响应缺少字段时的默认值)
|
||||||
|
- [x] 日志输出清晰,便于调试
|
||||||
|
- [x] 没有硬编码的配置值
|
||||||
|
- [ ] 单元测试覆盖核心逻辑
|
||||||
|
|
||||||
|
## 实施顺序
|
||||||
|
|
||||||
|
建议按照以下顺序实施任务:
|
||||||
|
|
||||||
|
1. **类型定义**(任务 1) - 定义数据结构
|
||||||
|
2. **数据库服务**(任务 2) - 提供历史数据查询
|
||||||
|
3. **LLM 客户端**(任务 3) - 实现核心逻辑
|
||||||
|
4. **趋势分析服务**(任务 4) - 集成新功能
|
||||||
|
5. **测试验证**(任务 5) - 确保功能正确
|
||||||
|
6. **文档更新**(任务 6) - 同步文档
|
||||||
|
7. **代码审查**(任务 7) - 最终检查
|
||||||
|
|
||||||
|
## 验收标准
|
||||||
|
|
||||||
|
- ✅ 所有类型检查通过(`npm run typecheck`)
|
||||||
|
- ✅ 构建成功(`npm run build`)
|
||||||
|
- ✅ 测试脚本验证通过
|
||||||
|
- ✅ 手动测试验证以下场景:
|
||||||
|
- 首次分析(无历史记录)发送通知
|
||||||
|
- 相似趋势跳过通知
|
||||||
|
- 新变化发送通知
|
||||||
|
- ✅ 日志输出包含通知决策信息
|
||||||
|
- ✅ 数据记录包含 `shouldNotify` 和 `notifyReason` 字段
|
||||||
|
- ✅ 文档已更新
|
||||||
|
|
||||||
|
## 预计工作量
|
||||||
|
|
||||||
|
- 类型定义: 15 分钟
|
||||||
|
- 数据库服务: 30 分钟
|
||||||
|
- LLM 客户端: 2 小时
|
||||||
|
- 趋势分析服务: 1 小时
|
||||||
|
- 测试验证: 1.5 小时
|
||||||
|
- 文档更新: 30 分钟
|
||||||
|
- 代码审查: 30 分钟
|
||||||
|
|
||||||
|
**总计**: 约 6 小时
|
||||||
|
|
||||||
|
## 风险和注意事项
|
||||||
|
|
||||||
|
1. **LLM 判断准确性**: LLM 可能错误判断相似度,导致漏发或多发通知
|
||||||
|
- 缓解: 在 Prompt 中明确定义相似度标准,并通过测试优化
|
||||||
|
|
||||||
|
2. **成本增加**: 增加历史上下文会略微增加 token 消耗
|
||||||
|
- 缓解: 控制历史记录数量(默认 3 条),可配置
|
||||||
|
|
||||||
|
3. **向后兼容性**: 新增字段可能影响现有数据
|
||||||
|
- 缓解: 新字段为可选,提供默认值
|
||||||
|
|
||||||
|
4. **调试困难**: 通知决策由 LLM 做出,可能难以调试
|
||||||
|
- 缓解: 记录完整的 `notifyReason` 和 `llmResponseRaw`,便于分析
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
# LLM 趋势总结架构设计
|
||||||
|
|
||||||
|
## 系统架构概述
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 主程序 (index.ts) │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────────────────┐ ┌──────────────────────────┐ │
|
||||||
|
│ │ 白银基线监控 │ │ LLM 趋势总结(新功能) │ │
|
||||||
|
│ │ (每分钟执行) │ │ (每 10 分钟执行) │ │
|
||||||
|
│ └──────────────────────┘ └──────────────────────────┘ │
|
||||||
|
│ │ │ │
|
||||||
|
│ ▼ ▼ │
|
||||||
|
└────────────┼─────────────────────────┼──────────────────────┘
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌────────────────────┐ ┌──────────────────────────┐
|
||||||
|
│ SilverBaseline │ │ SilverTrendAnalyzer │
|
||||||
|
│ Monitor │ │ (新服务) │
|
||||||
|
│ │ │ │
|
||||||
|
│ - 基线管理 │ │ - 定时触发 │
|
||||||
|
│ - 阈值告警 │ │ - 数据准备 │
|
||||||
|
│ - 飞书告警 │ │ - LLM 调用 │
|
||||||
|
└────────────────────┘ │ - 结果解析 │
|
||||||
|
│ - 告警判断 │
|
||||||
|
└──────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ LLMClient │
|
||||||
|
│ (新工具类) │
|
||||||
|
│ │
|
||||||
|
│ - OpenAI API 调用 │
|
||||||
|
│ - Prompt 构建 │
|
||||||
|
│ - 响应解析 │
|
||||||
|
│ - 错误处理 │
|
||||||
|
└──────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ DatabaseService │
|
||||||
|
│ │
|
||||||
|
│ - 趋势数据存储 │
|
||||||
|
│ - 历史查询 │
|
||||||
|
└──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心组件设计
|
||||||
|
|
||||||
|
### 1. SilverTrendAnalyzer Service
|
||||||
|
|
||||||
|
**职责**:
|
||||||
|
- 协调趋势总结的完整流程
|
||||||
|
- 从数据库获取最近30分钟的价格数据(作为上下文)
|
||||||
|
- 指导 LLM 重点总结最近10分钟的趋势
|
||||||
|
- 解析 LLM 响应并判断是否需要告警
|
||||||
|
- 触发飞书告警通知
|
||||||
|
- 保存分析记录
|
||||||
|
|
||||||
|
**接口设计**:
|
||||||
|
```typescript
|
||||||
|
class SilverTrendAnalyzer {
|
||||||
|
constructor(
|
||||||
|
db: DatabaseService,
|
||||||
|
alertService: AlertService,
|
||||||
|
llmClient: LLMClient,
|
||||||
|
webhookUrl?: string
|
||||||
|
)
|
||||||
|
|
||||||
|
// 主要方法
|
||||||
|
async analyzeTrend(): Promise<TrendAnalysisResult | null>
|
||||||
|
|
||||||
|
// 内部方法
|
||||||
|
private async prepareAnalysisData(): Promise<PriceDataPoint[]>
|
||||||
|
private async callLLM(data: PriceDataPoint[]): Promise<LLMResponse>
|
||||||
|
private parseLLMResponse(response: LLMResponse): ParsedTrendAnalysis
|
||||||
|
private shouldAlert(analysis: ParsedTrendAnalysis, previous?: ParsedTrendAnalysis): boolean
|
||||||
|
private async sendTrendAlert(analysis: ParsedTrendAnalysis): Promise<void>
|
||||||
|
private async saveAnalysis(analysis: ParsedTrendAnalysis): Promise<void>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. LLMClient Utility
|
||||||
|
|
||||||
|
**职责**:
|
||||||
|
- 封装 LLM API 调用细节
|
||||||
|
- 构建趋势总结提示词(Prompt)
|
||||||
|
- 解析 LLM 的结构化响应
|
||||||
|
- 处理 API 错误和重试逻辑
|
||||||
|
|
||||||
|
**接口设计**:
|
||||||
|
```typescript
|
||||||
|
class LLMClient {
|
||||||
|
constructor(config: LLMConfig)
|
||||||
|
|
||||||
|
async analyzeTrend(data: PriceDataPoint[]): Promise<TrendAnalysisResponse>
|
||||||
|
|
||||||
|
// 配置接口
|
||||||
|
private buildPrompt(data: PriceDataPoint[]): string
|
||||||
|
private parseResponse(response: string): TrendAnalysisResponse
|
||||||
|
private callAPI(prompt: string): Promise<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LLMConfig {
|
||||||
|
apiBase: string
|
||||||
|
apiKey: string
|
||||||
|
model: string
|
||||||
|
timeout?: number
|
||||||
|
maxRetries?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TrendAnalysisResponse {
|
||||||
|
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile'
|
||||||
|
confidence: number // 0-1
|
||||||
|
summary: string // 人类可读的趋势总结
|
||||||
|
signals: string[] // 识别到的关键信号
|
||||||
|
risk: 'low' | 'medium' | 'high'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 数据类型定义
|
||||||
|
|
||||||
|
**新增类型**(在 `src/types/index.ts` 中):
|
||||||
|
```typescript
|
||||||
|
// 价格数据点(用于 LLM 分析)
|
||||||
|
interface PriceDataPoint {
|
||||||
|
price: number
|
||||||
|
timestamp: string
|
||||||
|
// 可选:包含更多技术指标
|
||||||
|
changeFromPrevious?: number
|
||||||
|
volatility?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 趋势分析记录
|
||||||
|
interface TrendAnalysisRecord {
|
||||||
|
id: string
|
||||||
|
timestamp: string
|
||||||
|
dataPoints: PriceDataPoint[]
|
||||||
|
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile'
|
||||||
|
confidence: number
|
||||||
|
summary: string
|
||||||
|
signals: string[]
|
||||||
|
risk: 'low' | 'medium' | 'high'
|
||||||
|
triggered: boolean // 是否触发了告警
|
||||||
|
llmResponseRaw: string // 原始响应(用于调试)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 趋势分析数据库
|
||||||
|
interface TrendAnalysisDatabase {
|
||||||
|
analyses: TrendAnalysisRecord[]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prompt 工程
|
||||||
|
|
||||||
|
### Prompt 设计原则
|
||||||
|
1. **结构化输入**:将价格数据转换为易读的格式
|
||||||
|
2. **明确任务**:清晰定义 LLM 需要完成的任务(总结趋势,而非预测)
|
||||||
|
3. **结构化输出**:要求 LLM 返回 JSON 格式的响应
|
||||||
|
4. **上下文信息**:提供足够的背景信息帮助 LLM 理解数据
|
||||||
|
|
||||||
|
### Prompt 模板(示例)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const promptTemplate = `
|
||||||
|
你是一个专业的金融分析师,擅长分析贵金属价格趋势。
|
||||||
|
|
||||||
|
以下是白银最近 30 分钟的价格数据(每分钟一次):
|
||||||
|
|
||||||
|
{PRICE_DATA}
|
||||||
|
|
||||||
|
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
|
||||||
|
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
|
||||||
|
2. 置信度:0-1 之间的数值
|
||||||
|
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势
|
||||||
|
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
|
||||||
|
5. 风险评估:low/medium/high
|
||||||
|
|
||||||
|
**重要**:
|
||||||
|
- 专注于总结已经发生的趋势,不要预测未来走势
|
||||||
|
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
|
||||||
|
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
|
||||||
|
- 如果检测到价格剧烈波动(波动幅度异常增大),必须将 trend 设为 volatile
|
||||||
|
- 关注价格变化的幅度、速度和持续性
|
||||||
|
|
||||||
|
请以 JSON 格式返回:
|
||||||
|
{
|
||||||
|
"trend": "uptrend|downtrend|sideways|volatile",
|
||||||
|
"confidence": 0.85,
|
||||||
|
"summary": "...",
|
||||||
|
"signals": ["...", "...", "..."],
|
||||||
|
"risk": "low|medium|high"
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 数据格式化
|
||||||
|
将价格数据格式化为易读的文本:
|
||||||
|
```
|
||||||
|
时间 价格 变化 波动
|
||||||
|
2026-01-14 16:00 22.24 +0.01 0.5%
|
||||||
|
2026-01-14 16:01 22.24 0.00 0.0%
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
## 告警逻辑
|
||||||
|
|
||||||
|
### 告警触发条件
|
||||||
|
```typescript
|
||||||
|
function shouldAlert(
|
||||||
|
current: ParsedTrendAnalysis,
|
||||||
|
previous?: ParsedTrendAnalysis
|
||||||
|
): boolean {
|
||||||
|
// 条件 1:趋势反转
|
||||||
|
if (previous && isTrendReversal(previous.trend, current.trend)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 条件 2:剧烈波动
|
||||||
|
if (current.trend === 'volatile' && current.confidence > 0.7) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 条件 3:高风险 + 高置信度
|
||||||
|
if (current.risk === 'high' && current.confidence > 0.8) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 飞书告警卡片设计
|
||||||
|
|
||||||
|
使用飞书交互式卡片,包含:
|
||||||
|
- 标题:白银价格趋势告警
|
||||||
|
- 趋势标签(上涨📈 / 下跌📉 / 平稳➡️ / 波动📊)
|
||||||
|
- 趋势总结
|
||||||
|
- 关键信号列表
|
||||||
|
- 风险评估(颜色编码)
|
||||||
|
- 分析时间
|
||||||
|
- 置信度指示器
|
||||||
|
|
||||||
|
## 集成方案
|
||||||
|
|
||||||
|
### 主程序集成(`src/index.ts`)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class App {
|
||||||
|
private trendAnalyzer: SilverTrendAnalyzer
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// ... 现有初始化代码
|
||||||
|
|
||||||
|
// 配置 LLM 客户端
|
||||||
|
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: 30000
|
||||||
|
}
|
||||||
|
const llmClient = new LLMClient(llmConfig)
|
||||||
|
|
||||||
|
// 配置趋势总结服务
|
||||||
|
this.trendAnalyzer = new SilverTrendAnalyzer(
|
||||||
|
this.db,
|
||||||
|
this.alertService,
|
||||||
|
llmClient,
|
||||||
|
process.env.WEBHOOK_URL
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
// ... 现有白银基线监控代码
|
||||||
|
|
||||||
|
// 启动 LLM 趋势总结
|
||||||
|
const trendAnalysisInterval = Number(process.env.TREND_ANALYSIS_INTERVAL) || 600000 // 默认 10 分钟
|
||||||
|
const analyzeTrend = async () => {
|
||||||
|
try {
|
||||||
|
await this.trendAnalyzer.analyzeTrend()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('趋势总结执行出错:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首次延迟 10 分钟执行(等待积累足够数据)
|
||||||
|
setTimeout(analyzeTrend, 600000)
|
||||||
|
|
||||||
|
// 定时执行
|
||||||
|
setInterval(analyzeTrend, trendAnalysisInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 错误处理和容错
|
||||||
|
|
||||||
|
### LLM API 调用失败处理
|
||||||
|
- 重试机制:最多重试 2 次,间隔 5 秒
|
||||||
|
- 超时处理:30 秒超时,避免阻塞主程序
|
||||||
|
- 降级处理:分析失败时记录日志,不影响基线监控
|
||||||
|
- 告警抑制:连续失败时暂停告警,避免频繁通知
|
||||||
|
|
||||||
|
### 数据不足处理
|
||||||
|
- 如果历史数据少于 30 个点,跳过本次分析
|
||||||
|
- 记录警告日志,等待下次执行
|
||||||
|
|
||||||
|
## 性能和成本优化
|
||||||
|
|
||||||
|
### 成本控制
|
||||||
|
- 使用 `gpt-4o-mini` 模型(成本较低)
|
||||||
|
- 控制输入 token 数量(约 1000-2000 tokens)
|
||||||
|
- 可配置分析间隔,默认 10 分钟
|
||||||
|
- 仅在检测到重要信号时发送告警
|
||||||
|
|
||||||
|
### 性能优化
|
||||||
|
- 异步执行,不阻塞主程序
|
||||||
|
- 缓存 LLM 客户端实例
|
||||||
|
- 数据库查询优化(添加索引)
|
||||||
|
|
||||||
|
## 测试策略
|
||||||
|
|
||||||
|
### 单元测试
|
||||||
|
- LLMClient 的 Prompt 构建和响应解析
|
||||||
|
- 趋势判断逻辑
|
||||||
|
- 告警触发条件
|
||||||
|
|
||||||
|
### 集成测试
|
||||||
|
- 端到端的分析流程
|
||||||
|
- 飞书告警发送
|
||||||
|
- 数据库存储
|
||||||
|
|
||||||
|
### 手动测试
|
||||||
|
- 使用测试数据验证 LLM 响应质量
|
||||||
|
- 测试不同市场情况(上涨、下跌、波动)
|
||||||
|
- 验证告警触发逻辑
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Change: 新增基于 LLM 的白银价格趋势总结告警
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
当前白银监控系统仅提供简单的基线告警(价格变化超过固定阈值触发告警),缺乏对价格趋势的智能总结和分析能力。
|
||||||
|
|
||||||
|
**现有功能的局限性**:
|
||||||
|
- 只能检测价格相对于基线的绝对变化
|
||||||
|
- 无法识别价格变化的趋势模式(上涨/下跌/波动)
|
||||||
|
- 无法生成自然语言的趋势总结
|
||||||
|
- 无法提供直观的市场状态描述
|
||||||
|
|
||||||
|
**用户需求**:
|
||||||
|
- 利用 LLM 的智能总结能力,描述最近10分钟的价格走势
|
||||||
|
- 提供趋势判断(上涨趋势/下跌趋势/平稳波动)
|
||||||
|
- 识别异常波动和重要信号
|
||||||
|
- 通过飞书及时通知异常趋势
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
新增基于 LLM 的白银价格趋势总结功能:
|
||||||
|
- 新增 `SilverTrendAnalyzer` 服务,定期调用 LLM API 总结价格趋势
|
||||||
|
- 新增 LLM API 客户端模块,支持 OpenAI API(可配置 apiBase/key/model)
|
||||||
|
- 新增趋势总结数据存储结构
|
||||||
|
- 新增飞书趋势告警卡片模板
|
||||||
|
- 在主程序中集成趋势总结定时任务
|
||||||
|
- 可配置的分析间隔(默认每10分钟总结一次最近10分钟的趋势)
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
### 新增功能
|
||||||
|
- ✅ **LLM 趋势总结服务** - 定期总结白银价格趋势(最近10分钟)
|
||||||
|
- ✅ **智能告警** - 当 LLM 检测到异常波动或重要信号时触发告警
|
||||||
|
- ✅ **飞书趋势报告** - 发送包含趋势总结、信号识别的富文本卡片
|
||||||
|
|
||||||
|
### 受影响的文件
|
||||||
|
- `src/types/index.ts` - 新增趋势分析相关类型定义
|
||||||
|
- `src/services/silver-trend-analyzer.ts` - 新增趋势分析服务
|
||||||
|
- `src/utils/llm-client.ts` - 新增 LLM API 客户端
|
||||||
|
- `src/utils/alert.ts` - 新增趋势告警飞书卡片模板
|
||||||
|
- `src/services/database.ts` - 新增趋势分析数据存储方法
|
||||||
|
- `src/index.ts` - 集成趋势分析定时任务
|
||||||
|
- `.env.example` - 新增 LLM API 配置项
|
||||||
|
|
||||||
|
### 不受影响
|
||||||
|
- 现有的白银基线监控功能保持不变
|
||||||
|
- 数据库结构扩展(不破坏现有数据)
|
||||||
|
- 现有告警机制保持独立运行
|
||||||
|
|
||||||
|
## 技术实现要点
|
||||||
|
|
||||||
|
### LLM 服务配置
|
||||||
|
- 使用 OpenAI 兼容 API(支持 OpenAI、Azure OpenAI、以及其他兼容服务)
|
||||||
|
- 通过环境变量配置:`LLM_API_BASE`、`LLM_API_KEY`、`LLM_MODEL`
|
||||||
|
- 默认模型:`gpt-4o-mini`(性价比高)
|
||||||
|
- 超时设置:30 秒
|
||||||
|
|
||||||
|
### 分析策略
|
||||||
|
- **输入数据**:提供最近 30 分钟的白银价格数据(约 30 个数据点)作为上下文
|
||||||
|
- **总结范围**:重点总结最近 10 分钟的价格趋势
|
||||||
|
- **分析频率**:可配置间隔(默认 10 分钟)
|
||||||
|
- **Prompt 工程**:精心设计的提示词,引导 LLM 在了解背景的情况下总结近期趋势
|
||||||
|
- **响应解析**:结构化输出(JSON 格式),包含趋势类型、总结、信号等信息
|
||||||
|
|
||||||
|
### 告警触发条件
|
||||||
|
当 LLM 总结结果满足以下任一条件时触发告警:
|
||||||
|
1. **趋势反转**:从上涨趋势变为下跌趋势,或反之
|
||||||
|
2. **价格剧烈波动**:检测到异常的价格波动幅度
|
||||||
|
3. **重要信号**:LLM 识别出需要关注的市场信号
|
||||||
|
|
||||||
|
### 数据存储
|
||||||
|
- 趋势总结记录存储在 `src/data/silver-trends.json`
|
||||||
|
- 包含:分析时间戳、趋势类型、LLM 总结、识别的信号、是否触发告警
|
||||||
|
- 保留最近的分析历史(最多 1000 条记录)
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 成本考虑
|
||||||
|
- LLM API 调用会产生费用,需要合理控制调用频率
|
||||||
|
- 使用 `gpt-4o-mini` 等成本较低的模型
|
||||||
|
- 可通过配置调整分析间隔以平衡成本和实时性
|
||||||
|
- 分析30分钟数据(重点总结最近10分钟)成本约为每次 $0.0003-0.0007
|
||||||
|
|
||||||
|
### 可靠性考虑
|
||||||
|
- LLM API 可能失败或超时,需要容错处理
|
||||||
|
- 如果 LLM 总结失败,不影响基线监控的正常运行
|
||||||
|
- 记录失败日志以便排查问题
|
||||||
|
|
||||||
|
### 隐私和安全
|
||||||
|
- API Key 通过环境变量管理,不硬编码
|
||||||
|
- 价格数据不包含敏感信息,可安全发送给 LLM API
|
||||||
|
- 建议使用企业级 API 服务以确保数据安全
|
||||||
|
|
||||||
|
## 未来扩展方向
|
||||||
|
|
||||||
|
- 支持多个 LLM 服务(Claude API、本地开源模型等)
|
||||||
|
- 增加更多技术指标分析(移动平均线、RSI 等)
|
||||||
|
- 提供趋势总结的可视化图表
|
||||||
|
- 支持多个时间窗口的分析(5分钟、30分钟、1小时)
|
||||||
|
- 支持自定义告警条件和阈值
|
||||||
+334
@@ -0,0 +1,334 @@
|
|||||||
|
# silver-trend-analysis Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
提供基于 LLM 的白银价格趋势总结和智能告警功能,利用大语言模型理解价格变化的复杂模式,总结最近10分钟的趋势。
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: LLM 趋势总结服务
|
||||||
|
系统 SHALL 提供 LLM 趋势总结服务,定期调用 LLM API 总结白银价格趋势。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `SilverTrendAnalyzer` 服务类
|
||||||
|
- 使用可配置的定时器触发总结(默认 10 分钟)
|
||||||
|
- 从数据库获取最近 10 分钟的价格数据
|
||||||
|
- 调用 LLM API 进行趋势总结
|
||||||
|
- 解析 LLM 的结构化响应
|
||||||
|
|
||||||
|
#### Scenario: 定时执行趋势总结
|
||||||
|
- **WHEN** 系统启动且配置了 LLM API Key
|
||||||
|
- **THEN** 首次延迟 10 分钟后执行第一次总结(等待数据积累)
|
||||||
|
- **AND** 之后按照配置的间隔(默认 10 分钟)定期执行总结
|
||||||
|
- **AND** 每次从数据库获取最近 30 个价格数据点(作为上下文)
|
||||||
|
- **AND** 让 LLM 重点总结最近 10 分钟的趋势
|
||||||
|
|
||||||
|
#### Scenario: LLM API 调用成功
|
||||||
|
- **WHEN** LLM API 成功返回总结结果
|
||||||
|
- **THEN** 解析 JSON 格式的响应
|
||||||
|
- **AND** 提取趋势类型、置信度、总结、信号等字段
|
||||||
|
- **AND** 保存分析记录到数据库
|
||||||
|
- **AND** 判断是否需要触发告警
|
||||||
|
|
||||||
|
#### Scenario: LLM API 调用失败
|
||||||
|
- **WHEN** LLM API 调用失败(网络错误、超时、API 错误等)
|
||||||
|
- **THEN** 记录错误日志
|
||||||
|
- **AND** 最多重试 2 次,每次间隔 5 秒
|
||||||
|
- **AND** 如果仍然失败,跳过本次总结,等待下次定时触发
|
||||||
|
- **AND** 不影响白银基线监控的正常运行
|
||||||
|
|
||||||
|
#### Scenario: 历史数据不足
|
||||||
|
- **WHEN** 数据库中的价格数据少于 5 个点
|
||||||
|
- **THEN** 跳过本次总结
|
||||||
|
- **AND** 记录警告日志:"历史数据不足,跳过趋势总结"
|
||||||
|
- **AND** 等待下次定时触发
|
||||||
|
|
||||||
|
### Requirement: LLM API 客户端
|
||||||
|
系统 SHALL 提供 LLM API 客户端,封装与 OpenAI 兼容 API 的交互。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `LLMClient` 工具类
|
||||||
|
- 支持配置 API Base URL、API Key、模型名称
|
||||||
|
- 构建专业的金融分析 Prompt
|
||||||
|
- 解析结构化的 JSON 响应
|
||||||
|
|
||||||
|
#### Scenario: 配置 LLM API 客户端
|
||||||
|
- **WHEN** 创建 LLMClient 实例
|
||||||
|
- **THEN** 从环境变量读取配置:
|
||||||
|
- `LLM_API_BASE`:API 基础 URL(默认 `https://api.openai.com/v1`)
|
||||||
|
- `LLM_API_KEY`:API 密钥(必需)
|
||||||
|
- `LLM_MODEL`:模型名称(默认 `gpt-4o-mini`)
|
||||||
|
- **AND** 设置超时时间为 30 秒
|
||||||
|
- **AND** 设置最大重试次数为 2
|
||||||
|
|
||||||
|
#### Scenario: 构建总结 Prompt
|
||||||
|
- **WHEN** 调用 `buildPrompt(data)` 方法
|
||||||
|
- **THEN** 将最近 30 分钟的价格数据格式化为易读的文本表格
|
||||||
|
- **AND** 包含时间、价格、变化、波动等信息
|
||||||
|
- **AND** 添加 LLM 任务说明:
|
||||||
|
- 提供最近 30 分钟的数据作为上下文
|
||||||
|
- 重点总结最近 10 分钟的价格趋势
|
||||||
|
- 不预测未来走势
|
||||||
|
- **AND** 要求返回 JSON 格式的结构化响应
|
||||||
|
- **AND** Prompt 长度控制在 1500 tokens 以内
|
||||||
|
|
||||||
|
#### Scenario: 调用 LLM API
|
||||||
|
- **WHEN** 调用 `callAPI(prompt)` 方法
|
||||||
|
- **THEN** 使用 POST 请求调用 `/chat/completions` 端点
|
||||||
|
- **AND** 设置 `Content-Type: application/json`
|
||||||
|
- **AND** 设置 `Authorization: Bearer {API_KEY}`
|
||||||
|
- **AND** 请求体包含 messages、model、temperature 等参数
|
||||||
|
- **AND** 等待响应,超时时间为 30 秒
|
||||||
|
- **AND** 返回响应中的 content 文本
|
||||||
|
|
||||||
|
#### Scenario: 解析 LLM 响应
|
||||||
|
- **WHEN** 调用 `parseResponse(response)` 方法
|
||||||
|
- **THEN** 尝试解析 JSON 格式的响应
|
||||||
|
- **AND** 验证包含必需字段:trend、confidence、summary、signals、risk
|
||||||
|
- **AND** 如果解析失败,抛出包含错误详情的异常
|
||||||
|
|
||||||
|
### Requirement: 趋势数据存储
|
||||||
|
系统 SHALL 在数据库中存储趋势总结记录。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 扩展 `DatabaseService` 添加趋势数据管理方法
|
||||||
|
- 创建 `src/data/silver-trends.json` 文件
|
||||||
|
- 存储分析记录、LLM 原始响应等信息
|
||||||
|
|
||||||
|
#### Scenario: 保存趋势分析记录
|
||||||
|
- **WHEN** 趋势总结完成
|
||||||
|
- **THEN** 创建包含以下字段的记录:
|
||||||
|
- `id`:唯一标识符(UUID)
|
||||||
|
- `timestamp`:分析时间戳
|
||||||
|
- `dataPoints`:使用的价格数据点
|
||||||
|
- `trend`:趋势类型(uptrend/downtrend/sideways/volatile)
|
||||||
|
- `confidence`:置信度(0-1)
|
||||||
|
- `summary`:趋势总结
|
||||||
|
- `signals`:关键信号列表
|
||||||
|
- `risk`:风险评估(low/medium/high)
|
||||||
|
- `triggered`:是否触发告警
|
||||||
|
- `llmResponseRaw`:LLM 原始响应
|
||||||
|
- **AND** 将记录追加到 `silver-trends.json` 的 `analyses` 数组
|
||||||
|
- **AND** 保持最多 1000 条记录(超过后删除最旧的记录)
|
||||||
|
|
||||||
|
#### Scenario: 加载历史趋势数据
|
||||||
|
- **WHEN** 系统启动或需要查询历史
|
||||||
|
- **THEN** 从 `silver-trends.json` 加载数据
|
||||||
|
- **AND** 如果文件不存在,返回空数据结构
|
||||||
|
- **AND** 如果文件格式错误,记录错误并使用空数据结构
|
||||||
|
|
||||||
|
#### Scenario: 获取最近的价格数据点
|
||||||
|
- **WHEN** 需要准备 LLM 总结数据
|
||||||
|
- **THEN** 从白银基线数据的 `prices` 数组获取最近的数据点
|
||||||
|
- **AND** 默认获取最近 30 个数据点(30 分钟,作为上下文)
|
||||||
|
- **AND** LLM 将重点分析最后 10 个数据点(最近 10 分钟)的趋势
|
||||||
|
- **AND** 如果数据不足,返回所有可用数据点
|
||||||
|
- **AND** 按时间戳升序排列
|
||||||
|
- **AND** 转换为 `PriceDataPoint` 格式(包含价格和时间戳)
|
||||||
|
|
||||||
|
### Requirement: 趋势告警判断
|
||||||
|
系统 SHALL 根据趋势分析结果智能判断是否需要发送告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 实现多条件告警触发逻辑
|
||||||
|
- 对比当前分析和上次分析,检测趋势变化
|
||||||
|
- 根据趋势类型、置信度、风险评估等综合判断
|
||||||
|
|
||||||
|
#### Scenario: 检测趋势反转
|
||||||
|
- **WHEN** 当前分析的趋势类型与上次分析相反
|
||||||
|
- **AND** 两次分析的置信度都大于 0.6
|
||||||
|
- **THEN** 判定为趋势反转
|
||||||
|
- **AND** 触发告警:"检测到趋势反转:从 {prev_trend} 变为 {current_trend}"
|
||||||
|
|
||||||
|
#### Scenario: 检测剧烈波动
|
||||||
|
- **WHEN** 当前分析的趋势类型为 `volatile`
|
||||||
|
- **AND** 置信度大于 0.7
|
||||||
|
- **THEN** 判定为剧烈波动
|
||||||
|
- **AND** 触发告警:"检测到价格剧烈波动,请谨慎操作"
|
||||||
|
|
||||||
|
#### Scenario: 检测高风险信号
|
||||||
|
- **WHEN** 当前分析的风险评估为 `high`
|
||||||
|
- **AND** 置信度大于 0.8
|
||||||
|
- **THEN** 判定为高风险
|
||||||
|
- **AND** 触发告警:"检测到高风险信号,建议密切关注"
|
||||||
|
|
||||||
|
#### Scenario: 无需告警
|
||||||
|
- **WHEN** 当前分析不满足任何告警条件
|
||||||
|
- **THEN** 不触发告警
|
||||||
|
- **AND** 在控制台输出简要信息:"趋势分析完成:{trend},置信度 {confidence},风险 {risk}"
|
||||||
|
|
||||||
|
### Requirement: 飞书趋势告警
|
||||||
|
系统 SHALL 在触发趋势告警时发送飞书通知。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `AlertService` 中添加 `sendTrendAlert()` 方法
|
||||||
|
- 使用飞书交互式卡片格式展示趋势分析结果
|
||||||
|
- 包含趋势标签、总结、信号列表、风险评估等信息
|
||||||
|
|
||||||
|
#### Scenario: 发送趋势告警卡片
|
||||||
|
- **WHEN** 趋势总结满足告警条件
|
||||||
|
- **THEN** 调用 `sendTrendAlert(analysis)` 方法
|
||||||
|
- **AND** 发送 POST 请求到配置的 Webhook URL
|
||||||
|
- **AND** 请求体包含飞书卡片消息,包含:
|
||||||
|
- 标题:"🤖 LLM 趋势总结告警"
|
||||||
|
- 趋势标签:
|
||||||
|
- 上涨趋势:📈 上涨趋势
|
||||||
|
- 下跌趋势:📉 下跌趋势
|
||||||
|
- 平稳波动:➡️ 平稳波动
|
||||||
|
- 剧烈波动:📊 剧烈波动
|
||||||
|
- 趋势总结:summary 字段内容
|
||||||
|
- 关键信号:signals 数组,每个信号一行
|
||||||
|
- 风险评估:
|
||||||
|
- low:绿色标签 "低风险"
|
||||||
|
- medium:黄色标签 "中等风险"
|
||||||
|
- high:红色标签 "高风险"
|
||||||
|
- 置信度:百分比显示(如 "85%")
|
||||||
|
- 分析时间:格式化为本地时间
|
||||||
|
- **AND** 记录发送结果日志
|
||||||
|
|
||||||
|
#### Scenario: Webhook URL 未配置
|
||||||
|
- **WHEN** 触发趋势告警但未配置 `WEBHOOK_URL`
|
||||||
|
- **THEN** 在控制台输出告警信息
|
||||||
|
- **AND** 记录日志:"未配置 Webhook URL,跳过飞书告警"
|
||||||
|
|
||||||
|
#### Scenario: Webhook 发送失败
|
||||||
|
- **WHEN** 飞书 Webhook 调用失败
|
||||||
|
- **THEN** 记录错误日志:"飞书告警发送失败:{error}"
|
||||||
|
- **AND** 不影响后续的分析和告警
|
||||||
|
|
||||||
|
### Requirement: 配置管理
|
||||||
|
系统 SHALL 支持通过环境变量配置 LLM 趋势分析功能。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `.env.example` 中添加 LLM 相关配置项
|
||||||
|
- 在主程序中读取配置并应用默认值
|
||||||
|
- 提供配置验证,确保必需的配置项存在
|
||||||
|
|
||||||
|
#### Scenario: 读取 LLM 配置
|
||||||
|
- **WHEN** 系统启动
|
||||||
|
- **THEN** 从环境变量读取以下配置:
|
||||||
|
- `LLM_API_BASE`:API 基础 URL(可选)
|
||||||
|
- `LLM_API_KEY`:API 密钥(必需)
|
||||||
|
- `LLM_MODEL`:模型名称(可选)
|
||||||
|
- `TREND_ANALYSIS_INTERVAL`:分析间隔(可选)
|
||||||
|
- **AND** 应用默认值:
|
||||||
|
- `LLM_API_BASE` 默认:`https://api.openai.com/v1`
|
||||||
|
- `LLM_MODEL` 默认:`gpt-4o-mini`
|
||||||
|
- `TREND_ANALYSIS_INTERVAL` 默认:`600000`(10 分钟)
|
||||||
|
|
||||||
|
#### Scenario: 验证必需配置
|
||||||
|
- **WHEN** 系统启动
|
||||||
|
- **THEN** 检查 `LLM_API_KEY` 是否存在
|
||||||
|
- **AND** 如果不存在:
|
||||||
|
- 记录警告日志:"未配置 LLM_API_KEY,跳过 LLM 趋势分析功能"
|
||||||
|
- 不启动趋势分析定时任务
|
||||||
|
- **AND** 如果存在:
|
||||||
|
- 初始化 LLMClient 和 TrendAnalyzer
|
||||||
|
- 启动趋势分析定时任务
|
||||||
|
|
||||||
|
#### Scenario: 配置 LLM API Base
|
||||||
|
- **WHEN** 用户使用非 OpenAI 的兼容服务(如 Azure OpenAI)
|
||||||
|
- **THEN** 可以通过 `LLM_API_BASE` 配置自定义 API 端点
|
||||||
|
- **AND** 示例:
|
||||||
|
- Azure OpenAI:`https://{resource}.openai.azure.com/openai/deployments/{deployment}`
|
||||||
|
- 其他兼容服务:`https://api.example.com/v1`
|
||||||
|
|
||||||
|
### Requirement: 主程序集成
|
||||||
|
系统 SHALL 在主程序中集成 LLM 趋势分析功能。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `App` 类中添加 `trendAnalyzer` 成员
|
||||||
|
- 在构造函数中初始化趋势分析服务
|
||||||
|
- 在 `start()` 方法中启动定时分析任务
|
||||||
|
- 确保与白银基线监控并行运行
|
||||||
|
|
||||||
|
#### Scenario: 初始化趋势分析服务
|
||||||
|
- **WHEN** 创建 App 实例
|
||||||
|
- **THEN** 如果配置了 `LLM_API_KEY`:
|
||||||
|
- 创建 `LLMClient` 实例
|
||||||
|
- 创建 `SilverTrendAnalyzer` 实例
|
||||||
|
- 传递 `db`、`alertService`、`llmClient`、`webhookUrl` 参数
|
||||||
|
- **AND** 如果未配置 `LLM_API_KEY`:
|
||||||
|
- `trendAnalyzer` 保持为 `null`
|
||||||
|
- 不启动趋势分析功能
|
||||||
|
|
||||||
|
#### Scenario: 启动趋势总结定时任务
|
||||||
|
- **WHEN** 调用 `app.start()` 方法
|
||||||
|
- **THEN** 如果 `trendAnalyzer` 已初始化:
|
||||||
|
- 定义 `analyzeTrend()` 异步函数,调用 `trendAnalyzer.analyzeTrend()`
|
||||||
|
- 使用 `setTimeout` 延迟 600000 毫秒(10 分钟)后首次执行
|
||||||
|
- 使用 `setInterval` 按配置的间隔定期执行
|
||||||
|
- 在 `abortController.signal` 上监听 'abort' 事件,停止定时器
|
||||||
|
- **AND** 在控制台输出:"LLM 趋势总结已启动,分析间隔:{interval}ms"
|
||||||
|
|
||||||
|
#### Scenario: 优雅停止趋势分析
|
||||||
|
- **WHEN** 系统收到退出信号(SIGINT 或 SIGTERM)
|
||||||
|
- **THEN** 调用 `abortController.abort()`
|
||||||
|
- **AND** 停止趋势分析定时器
|
||||||
|
- **AND** 在控制台输出:"LLM 趋势分析已停止"
|
||||||
|
|
||||||
|
### Requirement: 错误处理和日志
|
||||||
|
系统 SHALL 提供完善的错误处理和日志记录。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 每个关键步骤都有日志记录
|
||||||
|
- 错误不应导致主程序崩溃
|
||||||
|
- 提供足够的调试信息
|
||||||
|
|
||||||
|
#### Scenario: 分析流程日志
|
||||||
|
- **WHEN** 执行趋势总结
|
||||||
|
- **THEN** 记录以下日志:
|
||||||
|
- 开始分析:"开始 LLM 趋势总结,使用 {count} 个数据点"
|
||||||
|
- API 调用:"调用 LLM API,模型:{model}"
|
||||||
|
- 响应接收:"LLM 响应成功,长度:{length} 字符"
|
||||||
|
- 分析完成:"趋势总结完成:{trend},置信度 {confidence},风险 {risk}"
|
||||||
|
|
||||||
|
#### Scenario: 错误日志
|
||||||
|
- **WHEN** 发生错误
|
||||||
|
- **THEN** 记录详细的错误信息:
|
||||||
|
- API 调用失败:"LLM API 调用失败:{error}"
|
||||||
|
- 响应解析失败:"LLM 响应解析失败:{error},原始响应:{response}"
|
||||||
|
- 数据保存失败:"趋势数据保存失败:{error}"
|
||||||
|
- 告警发送失败:"飞书告警发送失败:{error}"
|
||||||
|
|
||||||
|
#### Scenario: 错误不影响主程序
|
||||||
|
- **WHEN** 趋势分析过程中发生错误
|
||||||
|
- **THEN** 捕获异常并记录日志
|
||||||
|
- **AND** 不影响白银基线监控的运行
|
||||||
|
- **AND** 不影响下次定时分析任务的执行
|
||||||
|
- **AND** 确保主程序继续正常运行
|
||||||
|
|
||||||
|
### Requirement: 成本和性能优化
|
||||||
|
系统 SHALL 在设计和实现中考虑成本和性能优化。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用成本较低的 LLM 模型
|
||||||
|
- 控制 Prompt 长度以减少 token 消耗
|
||||||
|
- 可配置分析间隔以平衡成本和实时性
|
||||||
|
- 仅在重要信号时发送告警
|
||||||
|
|
||||||
|
#### Scenario: 选择成本优化的模型
|
||||||
|
- **WHEN** 用户未指定 LLM 模型
|
||||||
|
- **THEN** 使用 `gpt-4o-mini` 作为默认模型
|
||||||
|
- **AND** 该模型成本约为 GPT-4 的 1/10
|
||||||
|
- **AND** 性能足够完成趋势分析任务
|
||||||
|
|
||||||
|
#### Scenario: 控制 Prompt 长度
|
||||||
|
- **WHEN** 构建 LLM Prompt
|
||||||
|
- **THEN** 包含最近 30 个价格数据点(作为上下文)
|
||||||
|
- **AND** 使用简洁的文本格式(不包含冗余信息)
|
||||||
|
- **AND** Prompt 长度控制在 1500 tokens 以内
|
||||||
|
- **AND** 预计每次总结成本约 $0.0003-0.0007
|
||||||
|
|
||||||
|
#### Scenario: 可配置分析间隔
|
||||||
|
- **WHEN** 用户需要平衡成本和实时性
|
||||||
|
- **THEN** 可以通过 `TREND_ANALYSIS_INTERVAL` 配置分析间隔
|
||||||
|
- **AND** 默认 10 分钟(每小时 6 次调用)
|
||||||
|
- **AND** 可调整为 5 分钟(每小时 12 次)或 30 分钟(每小时 2 次)
|
||||||
|
- **AND** 估计成本:默认配置下每天约 $0.03-0.07
|
||||||
|
|
||||||
|
#### Scenario: 减少不必要的告警
|
||||||
|
- **WHEN** 趋势分析结果变化不大
|
||||||
|
- **THEN** 如果连续两次分析结果相似(趋势类型相同、置信度相近)
|
||||||
|
- **AND** 且没有检测到新的风险信号
|
||||||
|
- **THEN** 不发送飞书告警,避免通知疲劳
|
||||||
|
- **AND** 仅在控制台输出简要信息
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
# LLM 趋势分析功能实施任务
|
||||||
|
|
||||||
|
## Phase 1: 基础设施和类型定义
|
||||||
|
- [x] 1.1 在 `src/types/index.ts` 中添加趋势分析相关类型定义
|
||||||
|
- [x] PriceDataPoint 接口
|
||||||
|
- [x] TrendAnalysisRecord 接口
|
||||||
|
- [x] TrendAnalysisDatabase 接口
|
||||||
|
- [x] LLMConfig 和相关类型
|
||||||
|
|
||||||
|
## Phase 2: LLM 客户端实现
|
||||||
|
- [x] 2.1 创建 `src/utils/llm-client.ts` 文件
|
||||||
|
- [x] 2.2 实现 LLMClient 类的基础结构
|
||||||
|
- [x] 2.3 实现 `buildPrompt()` 方法,生成分析提示词
|
||||||
|
- [x] 2.4 实现 `callAPI()` 方法,调用 OpenAI API
|
||||||
|
- [x] 2.5 实现 `parseResponse()` 方法,解析 JSON 响应
|
||||||
|
- [x] 2.6 添加错误处理和重试逻辑
|
||||||
|
- [x] 2.7 添加超时控制
|
||||||
|
|
||||||
|
## Phase 3: 数据库扩展
|
||||||
|
- [x] 3.1 在 DatabaseService 中添加趋势数据存储方法
|
||||||
|
- [x] `loadTrendAnalysis()` - 加载趋势分析数据
|
||||||
|
- [x] `saveTrendAnalysis()` - 保存趋势分析数据
|
||||||
|
- [x] `addTrendAnalysis()` - 添加新的分析记录
|
||||||
|
- [x] `getRecentPricePoints()` - 获取最近的价格数据点
|
||||||
|
- [x] 3.2 创建 `src/data/silver-trends.json` 数据文件
|
||||||
|
- [x] 3.3 实现数据持久化逻辑
|
||||||
|
|
||||||
|
## Phase 4: 趋势分析服务实现
|
||||||
|
- [x] 4.1 创建 `src/services/silver-trend-analyzer.ts` 文件
|
||||||
|
- [x] 4.2 实现 SilverTrendAnalyzer 类的基础结构
|
||||||
|
- [x] 4.3 实现 `prepareAnalysisData()` 方法,准备分析数据
|
||||||
|
- [x] 4.4 实现 `analyzeTrend()` 主方法,协调分析流程
|
||||||
|
- [x] 4.5 实现 `shouldAlert()` 方法,判断是否需要告警
|
||||||
|
- [x] 4.6 实现趋势反转检测逻辑
|
||||||
|
- [x] 4.7 实现剧烈波动检测逻辑
|
||||||
|
- [x] 4.8 实现风险信号检测逻辑
|
||||||
|
- [x] 4.9 添加分析记录保存逻辑
|
||||||
|
|
||||||
|
## Phase 5: 飞书告警集成
|
||||||
|
- [x] 5.1 在 AlertService 中添加趋势告警方法
|
||||||
|
- [x] `sendTrendAlert()` - 发送趋势分析告警
|
||||||
|
- [x] 5.2 设计飞书趋势告警卡片模板
|
||||||
|
- [x] 标题和趋势标签
|
||||||
|
- [x] 趋势总结显示
|
||||||
|
- [x] 关键信号列表
|
||||||
|
- [x] 风险评估(颜色编码)
|
||||||
|
- [x] 置信度指示器
|
||||||
|
- [x] 5.3 实现卡片消息构建逻辑
|
||||||
|
|
||||||
|
## Phase 6: 主程序集成
|
||||||
|
- [x] 6.1 在 `src/index.ts` 中导入新服务
|
||||||
|
- [x] 6.2 在 App 类中添加 trendAnalyzer 成员变量
|
||||||
|
- [x] 6.3 在构造函数中初始化 LLMClient 和 TrendAnalyzer
|
||||||
|
- [x] 6.4 在 start() 方法中添加趋势分析定时任务
|
||||||
|
- [x] 6.5 实现首次执行延迟(等待数据积累)
|
||||||
|
- [x] 6.6 添加错误处理和日志记录
|
||||||
|
|
||||||
|
## Phase 7: 配置管理
|
||||||
|
- [x] 7.1 在 `.env.example` 中添加 LLM 配置项
|
||||||
|
- [x] LLM_API_BASE(默认 OpenAI API 地址)
|
||||||
|
- [x] LLM_API_KEY(必需)
|
||||||
|
- [x] LLM_MODEL(默认 gpt-4o-mini)
|
||||||
|
- [x] TREND_ANALYSIS_INTERVAL(默认 600000ms = 10 分钟)
|
||||||
|
- [x] 7.2 在 `src/index.ts` 中读取配置并应用默认值
|
||||||
|
- [x] 7.3 添加配置验证逻辑
|
||||||
|
|
||||||
|
## Phase 8: 测试和验证
|
||||||
|
- [x] 8.1 运行类型检查 `npm run typecheck`
|
||||||
|
- [x] 8.2 运行构建 `npm run build`
|
||||||
|
- [x] 8.3 创建测试脚本 `test-llm-trend.ts`
|
||||||
|
- [x] 测试 LLM API 连接
|
||||||
|
- [x] 测试 Prompt 生成
|
||||||
|
- [x] 测试响应解析
|
||||||
|
- [x] 8.4 手动测试趋势分析功能
|
||||||
|
- [x] 验证数据准备正确
|
||||||
|
- [x] 验证 LLM 调用成功
|
||||||
|
- [x] 验证响应解析正确
|
||||||
|
- [x] 验证告警触发逻辑
|
||||||
|
- [x] 8.5 测试飞书告警发送
|
||||||
|
- [x] 8.6 测试错误处理(API 失败、超时等)
|
||||||
|
- [x] 8.7 测试数据持久化
|
||||||
|
- [x] 8.8 长时间运行测试(验证定时任务稳定运行)
|
||||||
|
|
||||||
|
## Phase 9: 文档更新
|
||||||
|
- [x] 9.1 更新 README.md
|
||||||
|
- [x] 添加 LLM 趋势分析功能说明
|
||||||
|
- [x] 添加 LLM API 配置说明
|
||||||
|
- [x] 添加成本和性能建议
|
||||||
|
- [x] 9.2 更新 openspec/project.md
|
||||||
|
- [x] 添加 LLM 服务依赖说明
|
||||||
|
- [x] 9.3 创建使用指南
|
||||||
|
- [x] 如何获取 OpenAI API Key
|
||||||
|
- [x] 如何配置 LLM 服务
|
||||||
|
- [x] 如何调整分析间隔
|
||||||
|
- [x] 如何解读趋势分析结果
|
||||||
|
|
||||||
|
## Phase 10: 代码审查和优化
|
||||||
|
- [x] 10.1 代码审查(检查类型安全、错误处理)
|
||||||
|
- [x] 10.2 性能优化(减少不必要的 API 调用)
|
||||||
|
- [x] 10.3 成本优化(Prompt 压缩、模型选择)
|
||||||
|
- [x] 10.4 添加详细的注释和文档
|
||||||
|
- [x] 10.5 最终验证和清理
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 依赖关系
|
||||||
|
- Phase 2 必须在 Phase 4 之前完成
|
||||||
|
- Phase 3 必须在 Phase 4 之前完成
|
||||||
|
- Phase 5 可以与 Phase 4 并行开发
|
||||||
|
- Phase 6 必须在前面所有 Phase 完成后执行
|
||||||
|
|
||||||
|
### 可并行任务
|
||||||
|
- Phase 2, Phase 3, Phase 5 可以并行开发
|
||||||
|
- Phase 7 可以在 Phase 6 之前完成
|
||||||
|
- Phase 9 可以与开发并行进行
|
||||||
|
|
||||||
|
### 关键验证点
|
||||||
|
- 每个 Phase 完成后运行 `npm run typecheck` 和 `npm run build`
|
||||||
|
- Phase 8 是关键测试阶段,必须充分验证
|
||||||
|
- 确保 LLM API 调用失败不影响主程序运行
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Change: 新增白银价格基线监控
|
||||||
|
|
||||||
|
## Why
|
||||||
|
当前系统仅监控美白银和伦敦银的价差变化,无法直接监控单一白银商品的价格波动。用户需要一个独立的监控点,能够追踪页面上"白银"商品的销售价格,并在价格相对于基线值变化超过 ±0.2 时及时告警。
|
||||||
|
|
||||||
|
这个功能可以帮助用户:
|
||||||
|
- 独立监控白银商品的价格波动
|
||||||
|
- 通过基线机制避免频繁告警
|
||||||
|
- 及时捕捉价格的显著变化(±0.2)
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- 在 `ScraperService` 中新增获取"白银"商品价格的方法
|
||||||
|
- 新增白银基线监控服务 `SilverBaselineMonitor`
|
||||||
|
- 实现基线初始化、价格对比、告警触发和基线更新逻辑
|
||||||
|
- 在数据库中存储白银价格历史和基线值
|
||||||
|
- 通过飞书 Webhook 发送告警通知
|
||||||
|
- 在主程序中集成白银基线监控
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
- **新增功能**:白银价格基线监控(不影响现有的价差监控)
|
||||||
|
- **受影响的文件**:
|
||||||
|
- `src/types/index.ts` - 新增类型定义
|
||||||
|
- `src/services/scraper.ts` - 新增获取白银价格方法
|
||||||
|
- `src/services/database.ts` - 新增白银数据存储方法
|
||||||
|
- `src/services/silver-baseline-monitor.ts` - 新增监控服务(新文件)
|
||||||
|
- `src/index.ts` - 集成新监控服务
|
||||||
|
- `.env.example` - 新增配置项说明
|
||||||
|
- **数据存储**:新增 `src/data/silver-baseline.json` 文件
|
||||||
|
- **配置项**:新增 `SILVER_BASELINE_THRESHOLD` 环境变量(默认 0.2)
|
||||||
|
- **向后兼容**:完全兼容,不影响现有功能
|
||||||
+215
@@ -0,0 +1,215 @@
|
|||||||
|
# Silver Baseline Monitoring Specification
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: 白银价格获取
|
||||||
|
系统 SHALL 能够从页面中获取"白银"商品的销售价格。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用 Playwright 的 locator API 从页面提取数据
|
||||||
|
- 页面结构:`div.price-table-row` 包含商品行,`span.symbol-name` 包含商品名称
|
||||||
|
- 商品名称可能包含空格("白 银"),需要规范化处理
|
||||||
|
- 价格列存储在 `div.el-col` 元素中,按顺序为:商品名、回购价、销售价、最高价、最低价
|
||||||
|
|
||||||
|
#### Scenario: 成功获取白银价格
|
||||||
|
- **WHEN** 调用 `ScraperService.fetchSilverPrice()` 方法
|
||||||
|
- **THEN** 返回包含白银销售价格和时间戳的 `MetalPrice` 对象
|
||||||
|
- **AND** 价格值为有效的正数
|
||||||
|
- **AND** 包含回购价、销售价、最高价、最低价字段
|
||||||
|
|
||||||
|
#### Scenario: 白银商品不存在
|
||||||
|
- **WHEN** 页面中不存在"白银"商品
|
||||||
|
- **THEN** 返回 `null`
|
||||||
|
- **AND** 记录错误日志
|
||||||
|
|
||||||
|
#### Scenario: 页面结构变化
|
||||||
|
- **WHEN** 页面 DOM 结构发生变化
|
||||||
|
- **THEN** 使用 `ensurePageLoaded()` 方法确保页面已加载
|
||||||
|
- **AND** 智能判断是否需要重新导航或刷新页面
|
||||||
|
- **AND** 避免导航冲突(ERR_ABORTED 错误)
|
||||||
|
|
||||||
|
### Requirement: 基线初始化
|
||||||
|
系统 SHALL 在首次运行时自动初始化白银价格基线。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 基线值存储在 `DatabaseService.silverBaselineData.baseline` 中
|
||||||
|
- 初始化时使用首次获取的白银销售价格(`sellPrice`)
|
||||||
|
- 基线值持久化到 `src/data/silver-baseline.json`
|
||||||
|
|
||||||
|
#### Scenario: 首次运行初始化基线
|
||||||
|
- **WHEN** 系统首次启动且没有历史基线数据(`baseline === null`)
|
||||||
|
- **THEN** 使用首次获取的白银价格作为基线值
|
||||||
|
- **AND** 将基线值保存到数据库
|
||||||
|
- **AND** 记录基线初始化日志("📊 初始化白银价格基线: {price}")
|
||||||
|
- **AND** 保存初始价格记录到历史数据
|
||||||
|
|
||||||
|
#### Scenario: 从历史数据恢复基线
|
||||||
|
- **WHEN** 系统重启且存在历史基线数据
|
||||||
|
- **THEN** 从数据库加载上次保存的基线值
|
||||||
|
- **AND** 记录基线恢复日志("白银基线数据加载成功,基线值: {baseline}")
|
||||||
|
|
||||||
|
### Requirement: 价格变化监控
|
||||||
|
系统 SHALL 监控白银价格相对于基线的变化,并在变化超过阈值时触发告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 监控逻辑在 `SilverBaselineMonitor.processPrice()` 方法中实现
|
||||||
|
- 使用绝对值判断:`Math.abs(currentPrice - baseline) >= threshold`
|
||||||
|
- 默认阈值:0.2(可通过 `SILVER_BASELINE_THRESHOLD` 环境变量配置)
|
||||||
|
|
||||||
|
#### Scenario: 价格上涨超过阈值
|
||||||
|
- **WHEN** 当前白银价格 - 基线值 >= 0.2
|
||||||
|
- **THEN** 触发上涨告警(`type: 'RISE'`)
|
||||||
|
- **AND** 通过飞书发送告警消息(绿色卡片)
|
||||||
|
- **AND** 立即将当前价格更新为新基线
|
||||||
|
- **AND** 记录告警日志("⚠️ 白银价格上涨告警触发!")
|
||||||
|
- **AND** 保存告警记录到数据库
|
||||||
|
|
||||||
|
#### Scenario: 价格下跌超过阈值
|
||||||
|
- **WHEN** 基线值 - 当前白银价格 >= 0.2
|
||||||
|
- **THEN** 触发下跌告警(`type: 'FALL'`)
|
||||||
|
- **AND** 通过飞书发送告警消息(红色卡片)
|
||||||
|
- **AND** 立即将当前价格更新为新基线
|
||||||
|
- **AND** 记录告警日志("⚠️ 白银价格下跌告警触发!")
|
||||||
|
- **AND** 保存告警记录到数据库
|
||||||
|
|
||||||
|
#### Scenario: 价格变化未超过阈值
|
||||||
|
- **WHEN** |当前价格 - 基线值| < 0.2
|
||||||
|
- **THEN** 不触发告警
|
||||||
|
- **AND** 保持当前基线不变
|
||||||
|
- **AND** 记录价格监控日志("白银价格监控: 当前={price}, 基线={baseline}, 差值={diff} (未超过阈值 {threshold})")
|
||||||
|
|
||||||
|
### Requirement: 基线更新
|
||||||
|
系统 SHALL 在触发告警后立即更新基线值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 基线更新在告警触发后立即执行,避免重复告警
|
||||||
|
- 更新方法:`DatabaseService.updateSilverBaseline(newBaseline)`
|
||||||
|
- 更新后自动保存到 `src/data/silver-baseline.json`
|
||||||
|
|
||||||
|
#### Scenario: 告警触发后更新基线
|
||||||
|
- **WHEN** 价格变化超过阈值并触发告警
|
||||||
|
- **THEN** 将当前价格设置为新的基线值
|
||||||
|
- **AND** 保存新基线到数据库
|
||||||
|
- **AND** 记录基线更新日志("🔄 更新白银价格基线: {oldBaseline} -> {newBaseline}")
|
||||||
|
|
||||||
|
### Requirement: 飞书告警通知
|
||||||
|
系统 SHALL 通过飞书 Webhook 发送白银价格告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用飞书交互式卡片消息格式(`msg_type: 'interactive'`)
|
||||||
|
- 告警方法:`AlertService.sendSilverBaselineAlert(webhookUrl, alert)`
|
||||||
|
- 上涨告警使用绿色模板,下跌告警使用红色模板
|
||||||
|
|
||||||
|
#### Scenario: 发送上涨告警
|
||||||
|
- **WHEN** 白银价格上涨超过阈值
|
||||||
|
- **THEN** 发送包含以下信息的飞书消息:
|
||||||
|
- 告警类型("🔔 白银价格📈 上涨告警")
|
||||||
|
- 当前价格(保留3位小数)
|
||||||
|
- 基线价格(保留3位小数)
|
||||||
|
- 价格变化量(带正负号,保留3位小数)
|
||||||
|
- 变化百分比(带正负号,保留2位小数)
|
||||||
|
- 时间戳(本地化格式)
|
||||||
|
- 告警说明("价格上涨超过阈值,基线已自动更新为当前价格")
|
||||||
|
|
||||||
|
#### Scenario: 发送下跌告警
|
||||||
|
- **WHEN** 白银价格下跌超过阈值
|
||||||
|
- **THEN** 发送包含以下信息的飞书消息:
|
||||||
|
- 告警类型("🔔 白银价格📉 下跌告警")
|
||||||
|
- 当前价格(保留3位小数)
|
||||||
|
- 基线价格(保留3位小数)
|
||||||
|
- 价格变化量(带正负号,保留3位小数)
|
||||||
|
- 变化百分比(带正负号,保留2位小数)
|
||||||
|
- 时间戳(本地化格式)
|
||||||
|
- 告警说明("价格下跌超过阈值,基线已自动更新为当前价格")
|
||||||
|
|
||||||
|
#### Scenario: Webhook 发送失败
|
||||||
|
- **WHEN** 飞书 Webhook 调用失败
|
||||||
|
- **THEN** 记录错误日志("❌ 飞书告警发送失败: {error}")
|
||||||
|
- **AND** 基线仍然更新(避免重复告警)
|
||||||
|
- **AND** 不影响后续监控
|
||||||
|
|
||||||
|
### Requirement: 数据持久化
|
||||||
|
系统 SHALL 持久化存储白银价格历史和基线值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 数据文件:`src/data/silver-baseline.json`
|
||||||
|
- 数据结构:`SilverBaselineDatabase` 接口
|
||||||
|
- `baseline: number | null` - 当前基线值
|
||||||
|
- `prices: SilverBaselineData[]` - 历史价格记录
|
||||||
|
- `alerts: SilverBaselineAlert[]` - 告警记录
|
||||||
|
- 使用 JSON 格式存储,带格式化(2空格缩进)
|
||||||
|
|
||||||
|
#### Scenario: 保存白银价格记录
|
||||||
|
- **WHEN** 获取到新的白银价格
|
||||||
|
- **THEN** 将价格记录保存到 `src/data/silver-baseline.json`
|
||||||
|
- **AND** 包含 `currentPrice`、`baseline`、`timestamp` 字段
|
||||||
|
- **AND** 追加到 `prices` 数组
|
||||||
|
|
||||||
|
#### Scenario: 保存基线值
|
||||||
|
- **WHEN** 基线值被初始化或更新
|
||||||
|
- **THEN** 将新基线值保存到数据库
|
||||||
|
- **AND** 确保数据持久化成功
|
||||||
|
- **AND** 更新 `baseline` 字段
|
||||||
|
|
||||||
|
#### Scenario: 保存告警记录
|
||||||
|
- **WHEN** 触发告警
|
||||||
|
- **THEN** 将告警记录保存到数据库
|
||||||
|
- **AND** 包含 `type`、`currentPrice`、`baseline`、`change`、`changePercent`、`timestamp` 字段
|
||||||
|
- **AND** 追加到 `alerts` 数组
|
||||||
|
|
||||||
|
### Requirement: 配置管理
|
||||||
|
系统 SHALL 支持通过环境变量配置告警阈值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 环境变量:`SILVER_BASELINE_THRESHOLD`
|
||||||
|
- 读取方式:`Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2`
|
||||||
|
- 配置文件:`.env.example` 中提供示例
|
||||||
|
|
||||||
|
#### Scenario: 使用默认阈值
|
||||||
|
- **WHEN** 未配置 `SILVER_BASELINE_THRESHOLD` 环境变量
|
||||||
|
- **THEN** 使用默认阈值 0.2
|
||||||
|
|
||||||
|
#### Scenario: 使用自定义阈值
|
||||||
|
- **WHEN** 配置了 `SILVER_BASELINE_THRESHOLD` 环境变量
|
||||||
|
- **THEN** 使用配置的阈值值
|
||||||
|
- **AND** 验证阈值为有效的正数(通过 `Number()` 转换)
|
||||||
|
|
||||||
|
### Requirement: 监控集成
|
||||||
|
系统 SHALL 将白银基线监控集成到主监控循环中。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `App` 类中创建 `SilverBaselineMonitor` 实例
|
||||||
|
- 使用独立的定时器(`setInterval`)与价差监控并行运行
|
||||||
|
- 监控间隔与价差监控相同(`MONITOR_INTERVAL`)
|
||||||
|
- 使用 `AbortController` 统一管理退出信号
|
||||||
|
|
||||||
|
#### Scenario: 与现有监控同步运行
|
||||||
|
- **WHEN** 主监控循环执行
|
||||||
|
- **THEN** 同时执行白银基线监控和价差监控
|
||||||
|
- **AND** 两个监控相互独立,互不影响
|
||||||
|
- **AND** 使用相同的监控间隔
|
||||||
|
- **AND** 共享同一个 `ScraperService` 实例
|
||||||
|
|
||||||
|
#### Scenario: 优雅退出
|
||||||
|
- **WHEN** 接收到退出信号(SIGINT/SIGTERM)
|
||||||
|
- **THEN** 保存当前基线值(自动通过数据库服务完成)
|
||||||
|
- **AND** 关闭浏览器资源(`scraper.close()`)
|
||||||
|
- **AND** 记录退出日志("白银基线监控已停止")
|
||||||
|
- **AND** 清理定时器(`clearInterval`)
|
||||||
|
|
||||||
|
### Requirement: 统计信息展示
|
||||||
|
系统 SHALL 在控制台显示白银基线监控的统计信息。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 统计方法:`SilverBaselineMonitor.getStats()`
|
||||||
|
- 显示频率:每5分钟(与价差监控统计一起显示)
|
||||||
|
- 显示内容:当前基线、总价格记录、总告警次数、上涨/下跌告警次数
|
||||||
|
|
||||||
|
#### Scenario: 显示统计信息
|
||||||
|
- **WHEN** 定时器触发统计信息显示
|
||||||
|
- **THEN** 显示白银基线监控统计信息
|
||||||
|
- **AND** 包含当前基线值(保留3位小数或"未初始化")
|
||||||
|
- **AND** 包含总价格记录数
|
||||||
|
- **AND** 包含总告警次数
|
||||||
|
- **AND** 包含上涨告警次数
|
||||||
|
- **AND** 包含下跌告警次数
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
## 1. 类型定义
|
||||||
|
- [ ] 1.1 在 `src/types/index.ts` 中新增 `SilverBaselineData` 接口
|
||||||
|
- [ ] 1.2 在 `src/types/index.ts` 中新增 `SilverBaselineAlert` 接口
|
||||||
|
- [ ] 1.3 在 `src/types/index.ts` 中新增 `SilverBaselineDatabase` 接口
|
||||||
|
|
||||||
|
## 2. 数据获取
|
||||||
|
- [ ] 2.1 在 `ScraperService` 中实现 `fetchSilverPrice()` 方法
|
||||||
|
- [ ] 2.2 测试白银价格获取功能
|
||||||
|
|
||||||
|
## 3. 数据存储
|
||||||
|
- [ ] 3.1 在 `DatabaseService` 中新增 `loadSilverBaseline()` 方法
|
||||||
|
- [ ] 3.2 在 `DatabaseService` 中新增 `saveSilverBaseline()` 方法
|
||||||
|
- [ ] 3.3 在 `DatabaseService` 中新增 `addSilverPrice()` 方法
|
||||||
|
- [ ] 3.4 在 `DatabaseService` 中新增 `updateSilverBaseline()` 方法
|
||||||
|
|
||||||
|
## 4. 监控服务
|
||||||
|
- [ ] 4.1 创建 `src/services/silver-baseline-monitor.ts` 文件
|
||||||
|
- [ ] 4.2 实现 `SilverBaselineMonitor` 类
|
||||||
|
- [ ] 4.3 实现基线初始化逻辑
|
||||||
|
- [ ] 4.4 实现价格对比和告警触发逻辑
|
||||||
|
- [ ] 4.5 实现基线更新逻辑
|
||||||
|
|
||||||
|
## 5. 告警功能
|
||||||
|
- [ ] 5.1 在 `AlertService` 中新增 `sendSilverBaselineAlert()` 方法
|
||||||
|
- [ ] 5.2 设计飞书告警消息格式
|
||||||
|
- [ ] 5.3 测试飞书告警发送
|
||||||
|
|
||||||
|
## 6. 主程序集成
|
||||||
|
- [ ] 6.1 在 `src/index.ts` 中集成白银基线监控
|
||||||
|
- [ ] 6.2 配置监控间隔(与现有监控同步)
|
||||||
|
- [ ] 6.3 实现优雅退出处理
|
||||||
|
|
||||||
|
## 7. 配置和文档
|
||||||
|
- [ ] 7.1 更新 `.env.example` 添加 `SILVER_BASELINE_THRESHOLD` 配置
|
||||||
|
- [ ] 7.2 更新 `README.md` 添加白银基线监控说明
|
||||||
|
- [ ] 7.3 创建测试脚本 `test-silver-baseline.ts`
|
||||||
|
|
||||||
|
## 8. 测试验证
|
||||||
|
- [ ] 8.1 运行类型检查 `npm run typecheck`
|
||||||
|
- [ ] 8.2 运行构建 `npm run build`
|
||||||
|
- [ ] 8.3 测试白银价格获取
|
||||||
|
- [ ] 8.4 测试基线初始化
|
||||||
|
- [ ] 8.5 测试告警触发(模拟价格变化)
|
||||||
|
- [ ] 8.6 测试基线更新
|
||||||
|
- [ ] 8.7 验证数据持久化
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Change: 禁用价差监控和每小时汇总报告
|
||||||
|
|
||||||
|
## Why
|
||||||
|
当前系统同时运行两个监控功能:
|
||||||
|
1. **价差监控**(美白银 vs 伦敦银):监控价差方向变化并触发告警
|
||||||
|
2. **白银基线监控**:监控白银价格相对于基线的变化
|
||||||
|
|
||||||
|
用户希望暂时禁用价差监控和相关的每小时汇总报告,只保留白银价格监控功能。
|
||||||
|
|
||||||
|
**原因**:
|
||||||
|
- 用户只需要关注白银价格的基线监控
|
||||||
|
- 减少系统资源消耗(减少页面刷新次数)
|
||||||
|
- 简化监控逻辑,避免并发冲突
|
||||||
|
- 减少不必要的通知和报告
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- 在主程序中禁用价差监控的启动
|
||||||
|
- 移除价差监控的统计信息显示
|
||||||
|
- 保留白银基线监控功能
|
||||||
|
- 保留所有相关代码(便于将来恢复)
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
- **受影响的功能**:
|
||||||
|
- ✅ 价差监控(美白银 vs 伦敦银)- 将被禁用
|
||||||
|
- ✅ 每2小时汇总报告 - 将被禁用
|
||||||
|
- ✅ 价差监控统计信息显示 - 将被移除
|
||||||
|
- ✅ 白银基线监控 - **保持运行**
|
||||||
|
|
||||||
|
- **受影响的文件**:
|
||||||
|
- `src/index.ts` - 注释掉价差监控启动代码
|
||||||
|
- `src/index.ts` - 移除价差监控统计信息显示
|
||||||
|
|
||||||
|
- **不受影响**:
|
||||||
|
- 所有服务类代码保持不变
|
||||||
|
- 白银基线监控完全正常工作
|
||||||
|
- 数据库结构不变
|
||||||
|
- 配置文件不变
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
- 这是一个**可逆的变更**(通过注释/取消注释即可恢复)
|
||||||
|
- 代码不会被删除,只是禁用执行
|
||||||
|
- 数据库中的历史数据得以保留
|
||||||
|
- 便于将来需要时恢复价差监控功能
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
# 价差监控规格变更
|
||||||
|
|
||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: 价差监控运行
|
||||||
|
系统 SHALL 在主程序启动时自动启动价差监控。
|
||||||
|
|
||||||
|
**Reason**: 用户要求暂时禁用价差监控,只保留白银基线监控
|
||||||
|
|
||||||
|
**Migration**:
|
||||||
|
- 价差监控代码保留但不再执行
|
||||||
|
- 如需恢复,取消 `src/index.ts` 中的注释即可
|
||||||
|
|
||||||
|
#### Scenario: 禁用前 - 价差监控自动运行
|
||||||
|
- **WHEN** 系统启动
|
||||||
|
- **THEN** 自动启动价差监控(美白银 vs 伦敦银)
|
||||||
|
- **AND** 使用 `MonitorService.startMonitor()` 启动
|
||||||
|
- **AND** 按照配置的间隔定期执行
|
||||||
|
|
||||||
|
### Requirement: 每2小时汇总报告
|
||||||
|
系统 SHALL 每120次监控周期(约2小时)发送飞书汇总报告。
|
||||||
|
|
||||||
|
**Reason**: 禁用价差监控后,不再需要相关的汇总报告
|
||||||
|
|
||||||
|
**Migration**:
|
||||||
|
- 汇总报告代码保留在 `MonitorService.sendSummaryReport()` 中
|
||||||
|
- 如需恢复,取消注释价差监控启动代码即可自动恢复汇总报告
|
||||||
|
|
||||||
|
#### Scenario: 禁用前 - 自动发送汇总报告
|
||||||
|
- **WHEN** 监控执行次数达到120次的倍数
|
||||||
|
- **THEN** 自动调用 `sendSummaryReport()` 方法
|
||||||
|
- **AND** 通过飞书发送汇总报告
|
||||||
|
- **AND** 包含运行统计、当前价格、最近变化等信息
|
||||||
|
|
||||||
|
### Requirement: 价差监控统计信息显示
|
||||||
|
系统 SHALL 在控制台显示价差监控的统计信息。
|
||||||
|
|
||||||
|
**Reason**: 禁用价差监控后,不再显示相关统计
|
||||||
|
|
||||||
|
**Migration**:
|
||||||
|
- 统计信息显示代码保留但不再执行
|
||||||
|
- `MonitorService.getStats()` 等方法仍然可用
|
||||||
|
- 如需恢复,取消注释统计信息显示代码即可
|
||||||
|
|
||||||
|
#### Scenario: 禁用前 - 显示价差监控统计
|
||||||
|
- **WHEN** 定时器触发统计信息显示(每5分钟)
|
||||||
|
- **THEN** 显示价差监控统计信息
|
||||||
|
- **AND** 包含总价格记录、总变化次数、上涨次数、下跌次数
|
||||||
|
- **AND** 显示最近的变化记录
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# 禁用价差监控实施任务
|
||||||
|
|
||||||
|
## 1. 禁用价差监控启动
|
||||||
|
- [x] 1.1 在 `src/index.ts` 中注释掉价差监控启动代码
|
||||||
|
- [x] 1.2 保留白银基线监控启动代码
|
||||||
|
- [x] 1.3 确保白银基线监控仍然正常工作
|
||||||
|
|
||||||
|
## 2. 移除价差监控统计信息显示
|
||||||
|
- [x] 2.1 在 `src/index.ts` 的 `showStats()` 方法中注释掉价差监控统计显示
|
||||||
|
- [x] 2.2 保留白银基线监控统计信息显示
|
||||||
|
- [x] 2.3 更新统计信息显示格式
|
||||||
|
|
||||||
|
## 3. 验证功能
|
||||||
|
- [x] 3.1 运行类型检查 `npm run typecheck`
|
||||||
|
- [x] 3.2 运行构建 `npm run build`
|
||||||
|
- [x] 3.3 测试白银基线监控是否正常工作
|
||||||
|
- [x] 3.4 确认价差监控不再启动
|
||||||
|
- [x] 3.5 确认不再发送汇总报告
|
||||||
|
- [x] 3.6 确认统计信息只显示白银基线监控数据
|
||||||
|
|
||||||
|
## 4. 更新文档
|
||||||
|
- [x] 4.1 更新 README.md 说明当前只运行白银基线监控
|
||||||
|
- [x] 4.2 添加说明如何恢复价差监控
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Project Context
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
贵金属价格监控系统 - 实时监控美白银和伦敦银的价格变化,通过价差方向变化预测涨跌趋势,并提供多种告警方式。
|
||||||
|
|
||||||
|
**核心功能**:
|
||||||
|
- 自动化获取美白银和伦敦银价格数据
|
||||||
|
- 监控价差变化并识别涨跌信号
|
||||||
|
- 多渠道告警(控制台、日志、Webhook)
|
||||||
|
- 每小时汇总报告(飞书)
|
||||||
|
- 历史数据存储和统计分析
|
||||||
|
|
||||||
|
**监控逻辑**:
|
||||||
|
- **上涨信号**:美白银从 > 伦敦银 变成 < 伦敦银(价差从正变负)
|
||||||
|
- **下跌信号**:美白银从 < 伦敦银 变成 > 伦敦银(价差从负变正)
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
- **运行时**:Node.js (ES2022)
|
||||||
|
- **语言**:TypeScript 5.9+
|
||||||
|
- **自动化**:Playwright 1.49+ (浏览器自动化)
|
||||||
|
- **配置管理**:dotenv
|
||||||
|
- **开发工具**:tsx (TypeScript 执行器)
|
||||||
|
- **模块系统**:ES Modules (type: "module")
|
||||||
|
|
||||||
|
## Project Conventions
|
||||||
|
|
||||||
|
### Code Style
|
||||||
|
- **类型系统**:严格模式 TypeScript (`strict: true`)
|
||||||
|
- **命名约定**:
|
||||||
|
- 变量/函数:camelCase (如 `usSilver`, `londonSilver`)
|
||||||
|
- 类型/接口:PascalCase (如 `PriceData`, `ChangeRecord`)
|
||||||
|
- 常量:UPPER_SNAKE_CASE (如 `MONITOR_INTERVAL`)
|
||||||
|
- 枚举值:UPPER_SNAKE_CASE (如 `RISE`, `FALL`)
|
||||||
|
- **格式化**:
|
||||||
|
- 缩进:2 空格
|
||||||
|
- 文件编码:UTF-8
|
||||||
|
- 换行符:LF (Unix 风格)
|
||||||
|
- **注释**:使用中文注释解释业务逻辑
|
||||||
|
|
||||||
|
### Architecture Patterns
|
||||||
|
- **分层架构**:
|
||||||
|
- `src/types/` - 类型定义层
|
||||||
|
- `src/services/` - 核心业务逻辑层
|
||||||
|
- `src/utils/` - 工具函数层
|
||||||
|
- `src/data/` - 数据存储层
|
||||||
|
- **服务模块**:
|
||||||
|
- `database.ts` - 文件数据库服务(JSON 存储)
|
||||||
|
- `scraper.ts` - Playwright 爬虫服务
|
||||||
|
- `monitor.ts` - 监控服务(协调其他服务)
|
||||||
|
- `alert.ts` - 告警服务(多渠道通知)
|
||||||
|
- **设计原则**:
|
||||||
|
- 单一职责:每个服务模块专注一个功能
|
||||||
|
- 依赖注入:服务之间通过参数传递依赖
|
||||||
|
- 优雅退出:使用信号处理器确保资源清理
|
||||||
|
|
||||||
|
### Testing Strategy
|
||||||
|
- **手动测试**:
|
||||||
|
- `test-webhook.ts` - Webhook 告警测试
|
||||||
|
- `test-feishu-summary.ts` - 飞书汇总报告测试
|
||||||
|
- **类型检查**:`npm run typecheck` (必须通过)
|
||||||
|
- **构建验证**:`npm run build` (确保无编译错误)
|
||||||
|
- **未来计划**:添加单元测试和集成测试
|
||||||
|
|
||||||
|
### Git Workflow
|
||||||
|
- **提交信息**:使用中文,清晰描述"为什么"而非"是什么"
|
||||||
|
- **分支命名**:`feature/`, `fix/`, `refactor/` 等前缀
|
||||||
|
- **提交前检查**:
|
||||||
|
- 运行类型检查 (`npm run typecheck`)
|
||||||
|
- 确保代码可以构建 (`npm run build`)
|
||||||
|
- 测试核心功能是否正常
|
||||||
|
|
||||||
|
## Domain Context
|
||||||
|
|
||||||
|
### 贵金属价格监控领域知识
|
||||||
|
- **美白银**:美国白银期货价格
|
||||||
|
- **伦敦银**:伦敦现货白银价格
|
||||||
|
- **价差 (spread)**:美白银价格 - 伦敦银价格
|
||||||
|
- **价差方向变化**:价差从正变负或从负变正,是重要的趋势信号
|
||||||
|
|
||||||
|
### 数据来源
|
||||||
|
- 价格数据来源:`https://i.jzj9999.com/quoteh5/`
|
||||||
|
- 使用 Playwright 模拟浏览器访问获取实时数据
|
||||||
|
- 数据更新频率:默认每分钟一次(可配置)
|
||||||
|
|
||||||
|
### 告警策略
|
||||||
|
- **即时告警**:价差方向变化时立即触发
|
||||||
|
- **汇总报告**:每运行 60 次(约 1 小时)发送统计报告
|
||||||
|
- **告警渠道**:控制台、日志文件、Webhook(企业微信/钉钉/飞书)
|
||||||
|
|
||||||
|
## Important Constraints
|
||||||
|
|
||||||
|
### 技术约束
|
||||||
|
- 必须使用 ES Modules (不支持 CommonJS)
|
||||||
|
- 需要网络访问 `https://i.jzj9999.com/quoteh5/`
|
||||||
|
- 首次运行需要下载 Playwright 浏览器(约 100MB+)
|
||||||
|
- 数据文件存储在本地文件系统(`src/data/prices.json`)
|
||||||
|
|
||||||
|
### 业务约束
|
||||||
|
- 监控间隔不应过短(避免频繁请求)
|
||||||
|
- 价差变化判断需要至少两次数据记录
|
||||||
|
- 告警信息需要包含完整的价格和价差数据
|
||||||
|
|
||||||
|
### 运行环境约束
|
||||||
|
- Node.js 版本:建议 18.x 或更高
|
||||||
|
- 操作系统:支持 Windows、Linux、macOS
|
||||||
|
- 磁盘空间:需要足够空间存储历史数据和日志
|
||||||
|
|
||||||
|
## External Dependencies
|
||||||
|
|
||||||
|
### 核心依赖
|
||||||
|
- **Playwright**:浏览器自动化框架
|
||||||
|
- 用途:模拟浏览器访问获取价格数据
|
||||||
|
- 版本:^1.49.0
|
||||||
|
- 注意:首次运行会自动下载浏览器
|
||||||
|
|
||||||
|
- **dotenv**:环境变量管理
|
||||||
|
- 用途:加载 `.env` 配置文件
|
||||||
|
- 版本:^17.2.3
|
||||||
|
|
||||||
|
### 外部服务
|
||||||
|
- **价格数据源**:`https://i.jzj9999.com/quoteh5/`
|
||||||
|
- 依赖:需要稳定的网络连接
|
||||||
|
- 风险:网站结构变化可能导致爬虫失效
|
||||||
|
|
||||||
|
- **Webhook 服务**(可选):
|
||||||
|
- 企业微信机器人:`https://qyapi.weixin.qq.com/cgi-bin/webhook/send`
|
||||||
|
- 钉钉机器人:`https://oapi.dingtalk.com/robot/send`
|
||||||
|
- 飞书机器人:`https://open.feishu.cn/open-apis/bot/v2/hook/`
|
||||||
|
|
||||||
|
### 开发依赖
|
||||||
|
- **TypeScript**:类型系统和编译器 (^5.9.3)
|
||||||
|
- **tsx**:TypeScript 执行器,用于开发模式 (^4.21.0)
|
||||||
|
- **@types/node**:Node.js 类型定义 (^20.19.28)
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
# silver-baseline-monitoring Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
TBD - created by archiving change add-silver-baseline-monitor. Update Purpose after archive.
|
||||||
|
## Requirements
|
||||||
|
### Requirement: 白银价格获取
|
||||||
|
系统 SHALL 能够从页面中获取"白银"商品的销售价格。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用 Playwright 的 locator API 从页面提取数据
|
||||||
|
- 页面结构:`div.price-table-row` 包含商品行,`span.symbol-name` 包含商品名称
|
||||||
|
- 商品名称可能包含空格("白 银"),需要规范化处理
|
||||||
|
- 价格列存储在 `div.el-col` 元素中,按顺序为:商品名、回购价、销售价、最高价、最低价
|
||||||
|
|
||||||
|
#### Scenario: 成功获取白银价格
|
||||||
|
- **WHEN** 调用 `ScraperService.fetchSilverPrice()` 方法
|
||||||
|
- **THEN** 返回包含白银销售价格和时间戳的 `MetalPrice` 对象
|
||||||
|
- **AND** 价格值为有效的正数
|
||||||
|
- **AND** 包含回购价、销售价、最高价、最低价字段
|
||||||
|
|
||||||
|
#### Scenario: 白银商品不存在
|
||||||
|
- **WHEN** 页面中不存在"白银"商品
|
||||||
|
- **THEN** 返回 `null`
|
||||||
|
- **AND** 记录错误日志
|
||||||
|
|
||||||
|
#### Scenario: 页面结构变化
|
||||||
|
- **WHEN** 页面 DOM 结构发生变化
|
||||||
|
- **THEN** 使用 `ensurePageLoaded()` 方法确保页面已加载
|
||||||
|
- **AND** 智能判断是否需要重新导航或刷新页面
|
||||||
|
- **AND** 避免导航冲突(ERR_ABORTED 错误)
|
||||||
|
|
||||||
|
### Requirement: 基线初始化
|
||||||
|
系统 SHALL 在首次运行时自动初始化白银价格基线。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 基线值存储在 `DatabaseService.silverBaselineData.baseline` 中
|
||||||
|
- 初始化时使用首次获取的白银销售价格(`sellPrice`)
|
||||||
|
- 基线值持久化到 `src/data/silver-baseline.json`
|
||||||
|
|
||||||
|
#### Scenario: 首次运行初始化基线
|
||||||
|
- **WHEN** 系统首次启动且没有历史基线数据(`baseline === null`)
|
||||||
|
- **THEN** 使用首次获取的白银价格作为基线值
|
||||||
|
- **AND** 将基线值保存到数据库
|
||||||
|
- **AND** 记录基线初始化日志("📊 初始化白银价格基线: {price}")
|
||||||
|
- **AND** 保存初始价格记录到历史数据
|
||||||
|
|
||||||
|
#### Scenario: 从历史数据恢复基线
|
||||||
|
- **WHEN** 系统重启且存在历史基线数据
|
||||||
|
- **THEN** 从数据库加载上次保存的基线值
|
||||||
|
- **AND** 记录基线恢复日志("白银基线数据加载成功,基线值: {baseline}")
|
||||||
|
|
||||||
|
### Requirement: 价格变化监控
|
||||||
|
系统 SHALL 监控白银价格相对于基线的变化,并在变化超过阈值时触发告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 监控逻辑在 `SilverBaselineMonitor.processPrice()` 方法中实现
|
||||||
|
- 使用绝对值判断:`Math.abs(currentPrice - baseline) >= threshold`
|
||||||
|
- 默认阈值:0.2(可通过 `SILVER_BASELINE_THRESHOLD` 环境变量配置)
|
||||||
|
|
||||||
|
#### Scenario: 价格上涨超过阈值
|
||||||
|
- **WHEN** 当前白银价格 - 基线值 >= 0.2
|
||||||
|
- **THEN** 触发上涨告警(`type: 'RISE'`)
|
||||||
|
- **AND** 通过飞书发送告警消息(绿色卡片)
|
||||||
|
- **AND** 立即将当前价格更新为新基线
|
||||||
|
- **AND** 记录告警日志("⚠️ 白银价格上涨告警触发!")
|
||||||
|
- **AND** 保存告警记录到数据库
|
||||||
|
|
||||||
|
#### Scenario: 价格下跌超过阈值
|
||||||
|
- **WHEN** 基线值 - 当前白银价格 >= 0.2
|
||||||
|
- **THEN** 触发下跌告警(`type: 'FALL'`)
|
||||||
|
- **AND** 通过飞书发送告警消息(红色卡片)
|
||||||
|
- **AND** 立即将当前价格更新为新基线
|
||||||
|
- **AND** 记录告警日志("⚠️ 白银价格下跌告警触发!")
|
||||||
|
- **AND** 保存告警记录到数据库
|
||||||
|
|
||||||
|
#### Scenario: 价格变化未超过阈值
|
||||||
|
- **WHEN** |当前价格 - 基线值| < 0.2
|
||||||
|
- **THEN** 不触发告警
|
||||||
|
- **AND** 保持当前基线不变
|
||||||
|
- **AND** 记录价格监控日志("白银价格监控: 当前={price}, 基线={baseline}, 差值={diff} (未超过阈值 {threshold})")
|
||||||
|
|
||||||
|
### Requirement: 基线更新
|
||||||
|
系统 SHALL 在触发告警后立即更新基线值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 基线更新在告警触发后立即执行,避免重复告警
|
||||||
|
- 更新方法:`DatabaseService.updateSilverBaseline(newBaseline)`
|
||||||
|
- 更新后自动保存到 `src/data/silver-baseline.json`
|
||||||
|
|
||||||
|
#### Scenario: 告警触发后更新基线
|
||||||
|
- **WHEN** 价格变化超过阈值并触发告警
|
||||||
|
- **THEN** 将当前价格设置为新的基线值
|
||||||
|
- **AND** 保存新基线到数据库
|
||||||
|
- **AND** 记录基线更新日志("🔄 更新白银价格基线: {oldBaseline} -> {newBaseline}")
|
||||||
|
|
||||||
|
### Requirement: 飞书告警通知
|
||||||
|
系统 SHALL 通过飞书 Webhook 发送白银价格告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用飞书交互式卡片消息格式(`msg_type: 'interactive'`)
|
||||||
|
- 告警方法:`AlertService.sendSilverBaselineAlert(webhookUrl, alert)`
|
||||||
|
- 上涨告警使用绿色模板,下跌告警使用红色模板
|
||||||
|
|
||||||
|
#### Scenario: 发送上涨告警
|
||||||
|
- **WHEN** 白银价格上涨超过阈值
|
||||||
|
- **THEN** 发送包含以下信息的飞书消息:
|
||||||
|
- 告警类型("🔔 白银价格📈 上涨告警")
|
||||||
|
- 当前价格(保留3位小数)
|
||||||
|
- 基线价格(保留3位小数)
|
||||||
|
- 价格变化量(带正负号,保留3位小数)
|
||||||
|
- 变化百分比(带正负号,保留2位小数)
|
||||||
|
- 时间戳(本地化格式)
|
||||||
|
- 告警说明("价格上涨超过阈值,基线已自动更新为当前价格")
|
||||||
|
|
||||||
|
#### Scenario: 发送下跌告警
|
||||||
|
- **WHEN** 白银价格下跌超过阈值
|
||||||
|
- **THEN** 发送包含以下信息的飞书消息:
|
||||||
|
- 告警类型("🔔 白银价格📉 下跌告警")
|
||||||
|
- 当前价格(保留3位小数)
|
||||||
|
- 基线价格(保留3位小数)
|
||||||
|
- 价格变化量(带正负号,保留3位小数)
|
||||||
|
- 变化百分比(带正负号,保留2位小数)
|
||||||
|
- 时间戳(本地化格式)
|
||||||
|
- 告警说明("价格下跌超过阈值,基线已自动更新为当前价格")
|
||||||
|
|
||||||
|
#### Scenario: Webhook 发送失败
|
||||||
|
- **WHEN** 飞书 Webhook 调用失败
|
||||||
|
- **THEN** 记录错误日志("❌ 飞书告警发送失败: {error}")
|
||||||
|
- **AND** 基线仍然更新(避免重复告警)
|
||||||
|
- **AND** 不影响后续监控
|
||||||
|
|
||||||
|
### Requirement: 数据持久化
|
||||||
|
系统 SHALL 持久化存储白银价格历史和基线值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 数据文件:`src/data/silver-baseline.json`
|
||||||
|
- 数据结构:`SilverBaselineDatabase` 接口
|
||||||
|
- `baseline: number | null` - 当前基线值
|
||||||
|
- `prices: SilverBaselineData[]` - 历史价格记录
|
||||||
|
- `alerts: SilverBaselineAlert[]` - 告警记录
|
||||||
|
- 使用 JSON 格式存储,带格式化(2空格缩进)
|
||||||
|
|
||||||
|
#### Scenario: 保存白银价格记录
|
||||||
|
- **WHEN** 获取到新的白银价格
|
||||||
|
- **THEN** 将价格记录保存到 `src/data/silver-baseline.json`
|
||||||
|
- **AND** 包含 `currentPrice`、`baseline`、`timestamp` 字段
|
||||||
|
- **AND** 追加到 `prices` 数组
|
||||||
|
|
||||||
|
#### Scenario: 保存基线值
|
||||||
|
- **WHEN** 基线值被初始化或更新
|
||||||
|
- **THEN** 将新基线值保存到数据库
|
||||||
|
- **AND** 确保数据持久化成功
|
||||||
|
- **AND** 更新 `baseline` 字段
|
||||||
|
|
||||||
|
#### Scenario: 保存告警记录
|
||||||
|
- **WHEN** 触发告警
|
||||||
|
- **THEN** 将告警记录保存到数据库
|
||||||
|
- **AND** 包含 `type`、`currentPrice`、`baseline`、`change`、`changePercent`、`timestamp` 字段
|
||||||
|
- **AND** 追加到 `alerts` 数组
|
||||||
|
|
||||||
|
### Requirement: 配置管理
|
||||||
|
系统 SHALL 支持通过环境变量配置告警阈值。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 环境变量:`SILVER_BASELINE_THRESHOLD`
|
||||||
|
- 读取方式:`Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2`
|
||||||
|
- 配置文件:`.env.example` 中提供示例
|
||||||
|
|
||||||
|
#### Scenario: 使用默认阈值
|
||||||
|
- **WHEN** 未配置 `SILVER_BASELINE_THRESHOLD` 环境变量
|
||||||
|
- **THEN** 使用默认阈值 0.2
|
||||||
|
|
||||||
|
#### Scenario: 使用自定义阈值
|
||||||
|
- **WHEN** 配置了 `SILVER_BASELINE_THRESHOLD` 环境变量
|
||||||
|
- **THEN** 使用配置的阈值值
|
||||||
|
- **AND** 验证阈值为有效的正数(通过 `Number()` 转换)
|
||||||
|
|
||||||
|
### Requirement: 监控集成
|
||||||
|
系统 SHALL 将白银基线监控集成到主监控循环中。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `App` 类中创建 `SilverBaselineMonitor` 实例
|
||||||
|
- 使用独立的定时器(`setInterval`)与价差监控并行运行
|
||||||
|
- 监控间隔与价差监控相同(`MONITOR_INTERVAL`)
|
||||||
|
- 使用 `AbortController` 统一管理退出信号
|
||||||
|
|
||||||
|
#### Scenario: 与现有监控同步运行
|
||||||
|
- **WHEN** 主监控循环执行
|
||||||
|
- **THEN** 同时执行白银基线监控和价差监控
|
||||||
|
- **AND** 两个监控相互独立,互不影响
|
||||||
|
- **AND** 使用相同的监控间隔
|
||||||
|
- **AND** 共享同一个 `ScraperService` 实例
|
||||||
|
|
||||||
|
#### Scenario: 优雅退出
|
||||||
|
- **WHEN** 接收到退出信号(SIGINT/SIGTERM)
|
||||||
|
- **THEN** 保存当前基线值(自动通过数据库服务完成)
|
||||||
|
- **AND** 关闭浏览器资源(`scraper.close()`)
|
||||||
|
- **AND** 记录退出日志("白银基线监控已停止")
|
||||||
|
- **AND** 清理定时器(`clearInterval`)
|
||||||
|
|
||||||
|
### Requirement: 统计信息展示
|
||||||
|
系统 SHALL 在控制台显示白银基线监控的统计信息。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 统计方法:`SilverBaselineMonitor.getStats()`
|
||||||
|
- 显示频率:每5分钟(与价差监控统计一起显示)
|
||||||
|
- 显示内容:当前基线、总价格记录、总告警次数、上涨/下跌告警次数
|
||||||
|
|
||||||
|
#### Scenario: 显示统计信息
|
||||||
|
- **WHEN** 定时器触发统计信息显示
|
||||||
|
- **THEN** 显示白银基线监控统计信息
|
||||||
|
- **AND** 包含当前基线值(保留3位小数或"未初始化")
|
||||||
|
- **AND** 包含总价格记录数
|
||||||
|
- **AND** 包含总告警次数
|
||||||
|
- **AND** 包含上涨告警次数
|
||||||
|
- **AND** 包含下跌告警次数
|
||||||
|
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
# silver-trend-analysis Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
TBD - created by archiving change add-llm-trend-analysis. Update Purpose after archive.
|
||||||
|
## Requirements
|
||||||
|
### Requirement: LLM 趋势总结服务
|
||||||
|
系统 SHALL 提供 LLM 趋势总结服务,定期调用 LLM API 总结白银价格趋势。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `SilverTrendAnalyzer` 服务类
|
||||||
|
- 使用可配置的定时器触发总结(默认 10 分钟)
|
||||||
|
- 从数据库获取最近 10 分钟的价格数据
|
||||||
|
- 调用 LLM API 进行趋势总结
|
||||||
|
- 解析 LLM 的结构化响应
|
||||||
|
|
||||||
|
#### Scenario: 定时执行趋势总结
|
||||||
|
- **WHEN** 系统启动且配置了 LLM API Key
|
||||||
|
- **THEN** 首次延迟 10 分钟后执行第一次总结(等待数据积累)
|
||||||
|
- **AND** 之后按照配置的间隔(默认 10 分钟)定期执行总结
|
||||||
|
- **AND** 每次从数据库获取最近 30 个价格数据点(作为上下文)
|
||||||
|
- **AND** 让 LLM 重点总结最近 10 分钟的趋势
|
||||||
|
|
||||||
|
#### Scenario: LLM API 调用成功
|
||||||
|
- **WHEN** LLM API 成功返回总结结果
|
||||||
|
- **THEN** 解析 JSON 格式的响应
|
||||||
|
- **AND** 提取趋势类型、置信度、总结、信号等字段
|
||||||
|
- **AND** 保存分析记录到数据库
|
||||||
|
- **AND** 判断是否需要触发告警
|
||||||
|
|
||||||
|
#### Scenario: LLM API 调用失败
|
||||||
|
- **WHEN** LLM API 调用失败(网络错误、超时、API 错误等)
|
||||||
|
- **THEN** 记录错误日志
|
||||||
|
- **AND** 最多重试 2 次,每次间隔 5 秒
|
||||||
|
- **AND** 如果仍然失败,跳过本次总结,等待下次定时触发
|
||||||
|
- **AND** 不影响白银基线监控的正常运行
|
||||||
|
|
||||||
|
#### Scenario: 历史数据不足
|
||||||
|
- **WHEN** 数据库中的价格数据少于 5 个点
|
||||||
|
- **THEN** 跳过本次总结
|
||||||
|
- **AND** 记录警告日志:"历史数据不足,跳过趋势总结"
|
||||||
|
- **AND** 等待下次定时触发
|
||||||
|
|
||||||
|
### Requirement: LLM API 客户端
|
||||||
|
系统 SHALL 提供 LLM API 客户端,封装与 OpenAI 兼容 API 的交互。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 创建 `LLMClient` 工具类
|
||||||
|
- 支持配置 API Base URL、API Key、模型名称
|
||||||
|
- 构建专业的金融分析 Prompt
|
||||||
|
- 解析结构化的 JSON 响应
|
||||||
|
|
||||||
|
#### Scenario: 配置 LLM API 客户端
|
||||||
|
- **WHEN** 创建 LLMClient 实例
|
||||||
|
- **THEN** 从环境变量读取配置:
|
||||||
|
- `LLM_API_BASE`:API 基础 URL(默认 `https://api.openai.com/v1`)
|
||||||
|
- `LLM_API_KEY`:API 密钥(必需)
|
||||||
|
- `LLM_MODEL`:模型名称(默认 `gpt-4o-mini`)
|
||||||
|
- **AND** 设置超时时间为 30 秒
|
||||||
|
- **AND** 设置最大重试次数为 2
|
||||||
|
|
||||||
|
#### Scenario: 构建总结 Prompt
|
||||||
|
- **WHEN** 调用 `buildPrompt(data)` 方法
|
||||||
|
- **THEN** 将最近 30 分钟的价格数据格式化为易读的文本表格
|
||||||
|
- **AND** 包含时间、价格、变化、波动等信息
|
||||||
|
- **AND** 添加 LLM 任务说明:
|
||||||
|
- 提供最近 30 分钟的数据作为上下文
|
||||||
|
- 重点总结最近 10 分钟的价格趋势
|
||||||
|
- 不预测未来走势
|
||||||
|
- **AND** 要求返回 JSON 格式的结构化响应
|
||||||
|
- **AND** Prompt 长度控制在 1500 tokens 以内
|
||||||
|
|
||||||
|
#### Scenario: 调用 LLM API
|
||||||
|
- **WHEN** 调用 `callAPI(prompt)` 方法
|
||||||
|
- **THEN** 使用 POST 请求调用 `/chat/completions` 端点
|
||||||
|
- **AND** 设置 `Content-Type: application/json`
|
||||||
|
- **AND** 设置 `Authorization: Bearer {API_KEY}`
|
||||||
|
- **AND** 请求体包含 messages、model、temperature 等参数
|
||||||
|
- **AND** 等待响应,超时时间为 30 秒
|
||||||
|
- **AND** 返回响应中的 content 文本
|
||||||
|
|
||||||
|
#### Scenario: 解析 LLM 响应
|
||||||
|
- **WHEN** 调用 `parseResponse(response)` 方法
|
||||||
|
- **THEN** 尝试解析 JSON 格式的响应
|
||||||
|
- **AND** 验证包含必需字段:trend、confidence、summary、signals、risk
|
||||||
|
- **AND** 如果解析失败,抛出包含错误详情的异常
|
||||||
|
|
||||||
|
### Requirement: 趋势数据存储
|
||||||
|
系统 SHALL 在数据库中存储趋势总结记录。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 扩展 `DatabaseService` 添加趋势数据管理方法
|
||||||
|
- 创建 `src/data/silver-trends.json` 文件
|
||||||
|
- 存储分析记录、LLM 原始响应等信息
|
||||||
|
|
||||||
|
#### Scenario: 保存趋势分析记录
|
||||||
|
- **WHEN** 趋势总结完成
|
||||||
|
- **THEN** 创建包含以下字段的记录:
|
||||||
|
- `id`:唯一标识符(UUID)
|
||||||
|
- `timestamp`:分析时间戳
|
||||||
|
- `dataPoints`:使用的价格数据点
|
||||||
|
- `trend`:趋势类型(uptrend/downtrend/sideways/volatile)
|
||||||
|
- `confidence`:置信度(0-1)
|
||||||
|
- `summary`:趋势总结
|
||||||
|
- `signals`:关键信号列表
|
||||||
|
- `risk`:风险评估(low/medium/high)
|
||||||
|
- `triggered`:是否触发告警
|
||||||
|
- `llmResponseRaw`:LLM 原始响应
|
||||||
|
- **AND** 将记录追加到 `silver-trends.json` 的 `analyses` 数组
|
||||||
|
- **AND** 保持最多 1000 条记录(超过后删除最旧的记录)
|
||||||
|
|
||||||
|
#### Scenario: 加载历史趋势数据
|
||||||
|
- **WHEN** 系统启动或需要查询历史
|
||||||
|
- **THEN** 从 `silver-trends.json` 加载数据
|
||||||
|
- **AND** 如果文件不存在,返回空数据结构
|
||||||
|
- **AND** 如果文件格式错误,记录错误并使用空数据结构
|
||||||
|
|
||||||
|
#### Scenario: 获取最近的价格数据点
|
||||||
|
- **WHEN** 需要准备 LLM 总结数据
|
||||||
|
- **THEN** 从白银基线数据的 `prices` 数组获取最近的数据点
|
||||||
|
- **AND** 默认获取最近 30 个数据点(30 分钟,作为上下文)
|
||||||
|
- **AND** LLM 将重点分析最后 10 个数据点(最近 10 分钟)的趋势
|
||||||
|
- **AND** 如果数据不足,返回所有可用数据点
|
||||||
|
- **AND** 按时间戳升序排列
|
||||||
|
- **AND** 转换为 `PriceDataPoint` 格式(包含价格和时间戳)
|
||||||
|
|
||||||
|
### Requirement: 趋势告警判断
|
||||||
|
系统 SHALL 根据趋势分析结果智能判断是否需要发送告警。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 实现多条件告警触发逻辑
|
||||||
|
- 对比当前分析和上次分析,检测趋势变化
|
||||||
|
- 根据趋势类型、置信度、风险评估等综合判断
|
||||||
|
|
||||||
|
#### Scenario: 检测趋势反转
|
||||||
|
- **WHEN** 当前分析的趋势类型与上次分析相反
|
||||||
|
- **AND** 两次分析的置信度都大于 0.6
|
||||||
|
- **THEN** 判定为趋势反转
|
||||||
|
- **AND** 触发告警:"检测到趋势反转:从 {prev_trend} 变为 {current_trend}"
|
||||||
|
|
||||||
|
#### Scenario: 检测剧烈波动
|
||||||
|
- **WHEN** 当前分析的趋势类型为 `volatile`
|
||||||
|
- **AND** 置信度大于 0.7
|
||||||
|
- **THEN** 判定为剧烈波动
|
||||||
|
- **AND** 触发告警:"检测到价格剧烈波动,请谨慎操作"
|
||||||
|
|
||||||
|
#### Scenario: 检测高风险信号
|
||||||
|
- **WHEN** 当前分析的风险评估为 `high`
|
||||||
|
- **AND** 置信度大于 0.8
|
||||||
|
- **THEN** 判定为高风险
|
||||||
|
- **AND** 触发告警:"检测到高风险信号,建议密切关注"
|
||||||
|
|
||||||
|
#### Scenario: 无需告警
|
||||||
|
- **WHEN** 当前分析不满足任何告警条件
|
||||||
|
- **THEN** 不触发告警
|
||||||
|
- **AND** 在控制台输出简要信息:"趋势分析完成:{trend},置信度 {confidence},风险 {risk}"
|
||||||
|
|
||||||
|
### Requirement: 飞书趋势告警
|
||||||
|
系统 SHALL 在触发趋势告警时发送飞书通知。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `AlertService` 中添加 `sendTrendAlert()` 方法
|
||||||
|
- 使用飞书交互式卡片格式展示趋势分析结果
|
||||||
|
- 包含趋势标签、总结、信号列表、风险评估等信息
|
||||||
|
|
||||||
|
#### Scenario: 发送趋势告警卡片
|
||||||
|
- **WHEN** 趋势总结满足告警条件
|
||||||
|
- **THEN** 调用 `sendTrendAlert(analysis)` 方法
|
||||||
|
- **AND** 发送 POST 请求到配置的 Webhook URL
|
||||||
|
- **AND** 请求体包含飞书卡片消息,包含:
|
||||||
|
- 标题:"🤖 LLM 趋势总结告警"
|
||||||
|
- 趋势标签:
|
||||||
|
- 上涨趋势:📈 上涨趋势
|
||||||
|
- 下跌趋势:📉 下跌趋势
|
||||||
|
- 平稳波动:➡️ 平稳波动
|
||||||
|
- 剧烈波动:📊 剧烈波动
|
||||||
|
- 趋势总结:summary 字段内容
|
||||||
|
- 关键信号:signals 数组,每个信号一行
|
||||||
|
- 风险评估:
|
||||||
|
- low:绿色标签 "低风险"
|
||||||
|
- medium:黄色标签 "中等风险"
|
||||||
|
- high:红色标签 "高风险"
|
||||||
|
- 置信度:百分比显示(如 "85%")
|
||||||
|
- 分析时间:格式化为本地时间
|
||||||
|
- **AND** 记录发送结果日志
|
||||||
|
|
||||||
|
#### Scenario: Webhook URL 未配置
|
||||||
|
- **WHEN** 触发趋势告警但未配置 `WEBHOOK_URL`
|
||||||
|
- **THEN** 在控制台输出告警信息
|
||||||
|
- **AND** 记录日志:"未配置 Webhook URL,跳过飞书告警"
|
||||||
|
|
||||||
|
#### Scenario: Webhook 发送失败
|
||||||
|
- **WHEN** 飞书 Webhook 调用失败
|
||||||
|
- **THEN** 记录错误日志:"飞书告警发送失败:{error}"
|
||||||
|
- **AND** 不影响后续的分析和告警
|
||||||
|
|
||||||
|
### Requirement: 配置管理
|
||||||
|
系统 SHALL 支持通过环境变量配置 LLM 趋势分析功能。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `.env.example` 中添加 LLM 相关配置项
|
||||||
|
- 在主程序中读取配置并应用默认值
|
||||||
|
- 提供配置验证,确保必需的配置项存在
|
||||||
|
|
||||||
|
#### Scenario: 读取 LLM 配置
|
||||||
|
- **WHEN** 系统启动
|
||||||
|
- **THEN** 从环境变量读取以下配置:
|
||||||
|
- `LLM_API_BASE`:API 基础 URL(可选)
|
||||||
|
- `LLM_API_KEY`:API 密钥(必需)
|
||||||
|
- `LLM_MODEL`:模型名称(可选)
|
||||||
|
- `TREND_ANALYSIS_INTERVAL`:分析间隔(可选)
|
||||||
|
- **AND** 应用默认值:
|
||||||
|
- `LLM_API_BASE` 默认:`https://api.openai.com/v1`
|
||||||
|
- `LLM_MODEL` 默认:`gpt-4o-mini`
|
||||||
|
- `TREND_ANALYSIS_INTERVAL` 默认:`600000`(10 分钟)
|
||||||
|
|
||||||
|
#### Scenario: 验证必需配置
|
||||||
|
- **WHEN** 系统启动
|
||||||
|
- **THEN** 检查 `LLM_API_KEY` 是否存在
|
||||||
|
- **AND** 如果不存在:
|
||||||
|
- 记录警告日志:"未配置 LLM_API_KEY,跳过 LLM 趋势分析功能"
|
||||||
|
- 不启动趋势分析定时任务
|
||||||
|
- **AND** 如果存在:
|
||||||
|
- 初始化 LLMClient 和 TrendAnalyzer
|
||||||
|
- 启动趋势分析定时任务
|
||||||
|
|
||||||
|
#### Scenario: 配置 LLM API Base
|
||||||
|
- **WHEN** 用户使用非 OpenAI 的兼容服务(如 Azure OpenAI)
|
||||||
|
- **THEN** 可以通过 `LLM_API_BASE` 配置自定义 API 端点
|
||||||
|
- **AND** 示例:
|
||||||
|
- Azure OpenAI:`https://{resource}.openai.azure.com/openai/deployments/{deployment}`
|
||||||
|
- 其他兼容服务:`https://api.example.com/v1`
|
||||||
|
|
||||||
|
### Requirement: 主程序集成
|
||||||
|
系统 SHALL 在主程序中集成 LLM 趋势分析功能。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 在 `App` 类中添加 `trendAnalyzer` 成员
|
||||||
|
- 在构造函数中初始化趋势分析服务
|
||||||
|
- 在 `start()` 方法中启动定时分析任务
|
||||||
|
- 确保与白银基线监控并行运行
|
||||||
|
|
||||||
|
#### Scenario: 初始化趋势分析服务
|
||||||
|
- **WHEN** 创建 App 实例
|
||||||
|
- **THEN** 如果配置了 `LLM_API_KEY`:
|
||||||
|
- 创建 `LLMClient` 实例
|
||||||
|
- 创建 `SilverTrendAnalyzer` 实例
|
||||||
|
- 传递 `db`、`alertService`、`llmClient`、`webhookUrl` 参数
|
||||||
|
- **AND** 如果未配置 `LLM_API_KEY`:
|
||||||
|
- `trendAnalyzer` 保持为 `null`
|
||||||
|
- 不启动趋势分析功能
|
||||||
|
|
||||||
|
#### Scenario: 启动趋势总结定时任务
|
||||||
|
- **WHEN** 调用 `app.start()` 方法
|
||||||
|
- **THEN** 如果 `trendAnalyzer` 已初始化:
|
||||||
|
- 定义 `analyzeTrend()` 异步函数,调用 `trendAnalyzer.analyzeTrend()`
|
||||||
|
- 使用 `setTimeout` 延迟 600000 毫秒(10 分钟)后首次执行
|
||||||
|
- 使用 `setInterval` 按配置的间隔定期执行
|
||||||
|
- 在 `abortController.signal` 上监听 'abort' 事件,停止定时器
|
||||||
|
- **AND** 在控制台输出:"LLM 趋势总结已启动,分析间隔:{interval}ms"
|
||||||
|
|
||||||
|
#### Scenario: 优雅停止趋势分析
|
||||||
|
- **WHEN** 系统收到退出信号(SIGINT 或 SIGTERM)
|
||||||
|
- **THEN** 调用 `abortController.abort()`
|
||||||
|
- **AND** 停止趋势分析定时器
|
||||||
|
- **AND** 在控制台输出:"LLM 趋势分析已停止"
|
||||||
|
|
||||||
|
### Requirement: 错误处理和日志
|
||||||
|
系统 SHALL 提供完善的错误处理和日志记录。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 每个关键步骤都有日志记录
|
||||||
|
- 错误不应导致主程序崩溃
|
||||||
|
- 提供足够的调试信息
|
||||||
|
|
||||||
|
#### Scenario: 分析流程日志
|
||||||
|
- **WHEN** 执行趋势总结
|
||||||
|
- **THEN** 记录以下日志:
|
||||||
|
- 开始分析:"开始 LLM 趋势总结,使用 {count} 个数据点"
|
||||||
|
- API 调用:"调用 LLM API,模型:{model}"
|
||||||
|
- 响应接收:"LLM 响应成功,长度:{length} 字符"
|
||||||
|
- 分析完成:"趋势总结完成:{trend},置信度 {confidence},风险 {risk}"
|
||||||
|
|
||||||
|
#### Scenario: 错误日志
|
||||||
|
- **WHEN** 发生错误
|
||||||
|
- **THEN** 记录详细的错误信息:
|
||||||
|
- API 调用失败:"LLM API 调用失败:{error}"
|
||||||
|
- 响应解析失败:"LLM 响应解析失败:{error},原始响应:{response}"
|
||||||
|
- 数据保存失败:"趋势数据保存失败:{error}"
|
||||||
|
- 告警发送失败:"飞书告警发送失败:{error}"
|
||||||
|
|
||||||
|
#### Scenario: 错误不影响主程序
|
||||||
|
- **WHEN** 趋势分析过程中发生错误
|
||||||
|
- **THEN** 捕获异常并记录日志
|
||||||
|
- **AND** 不影响白银基线监控的运行
|
||||||
|
- **AND** 不影响下次定时分析任务的执行
|
||||||
|
- **AND** 确保主程序继续正常运行
|
||||||
|
|
||||||
|
### Requirement: 成本和性能优化
|
||||||
|
系统 SHALL 在设计和实现中考虑成本和性能优化。
|
||||||
|
|
||||||
|
**实施说明**:
|
||||||
|
- 使用成本较低的 LLM 模型
|
||||||
|
- 控制 Prompt 长度以减少 token 消耗
|
||||||
|
- 可配置分析间隔以平衡成本和实时性
|
||||||
|
- 仅在重要信号时发送告警
|
||||||
|
|
||||||
|
#### Scenario: 选择成本优化的模型
|
||||||
|
- **WHEN** 用户未指定 LLM 模型
|
||||||
|
- **THEN** 使用 `gpt-4o-mini` 作为默认模型
|
||||||
|
- **AND** 该模型成本约为 GPT-4 的 1/10
|
||||||
|
- **AND** 性能足够完成趋势分析任务
|
||||||
|
|
||||||
|
#### Scenario: 控制 Prompt 长度
|
||||||
|
- **WHEN** 构建 LLM Prompt
|
||||||
|
- **THEN** 包含最近 30 个价格数据点(作为上下文)
|
||||||
|
- **AND** 使用简洁的文本格式(不包含冗余信息)
|
||||||
|
- **AND** Prompt 长度控制在 1500 tokens 以内
|
||||||
|
- **AND** 预计每次总结成本约 $0.0003-0.0007
|
||||||
|
|
||||||
|
#### Scenario: 可配置分析间隔
|
||||||
|
- **WHEN** 用户需要平衡成本和实时性
|
||||||
|
- **THEN** 可以通过 `TREND_ANALYSIS_INTERVAL` 配置分析间隔
|
||||||
|
- **AND** 默认 10 分钟(每小时 6 次调用)
|
||||||
|
- **AND** 可调整为 5 分钟(每小时 12 次)或 30 分钟(每小时 2 次)
|
||||||
|
- **AND** 估计成本:默认配置下每天约 $0.03-0.07
|
||||||
|
|
||||||
|
#### Scenario: 减少不必要的告警
|
||||||
|
- **WHEN** 趋势分析结果变化不大
|
||||||
|
- **THEN** 如果连续两次分析结果相似(趋势类型相同、置信度相近)
|
||||||
|
- **AND** 且没有检测到新的风险信号
|
||||||
|
- **THEN** 不发送飞书告警,避免通知疲劳
|
||||||
|
- **AND** 仅在控制台输出简要信息
|
||||||
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"name": "rongtongjin-monitor",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "贵金属价格监控项目 - 监控美白银和伦敦银价格变化",
|
||||||
|
"type": "module",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"lint": "eslint src --ext .ts"
|
||||||
|
},
|
||||||
|
"keywords": [
|
||||||
|
"贵金属",
|
||||||
|
"价格监控",
|
||||||
|
"playwright"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"dotenv": "^17.2.3",
|
||||||
|
"playwright": "^1.49.0",
|
||||||
|
"uuid": "^13.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.19.28",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
|
"typescript": "^5.9.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
+253
@@ -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();
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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('监控已停止');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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')}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 地址
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { DatabaseService } from './src/services/database.js';
|
||||||
|
import { ScraperService } from './src/services/scraper.js';
|
||||||
|
import { SilverBaselineMonitor } from './src/services/silver-baseline-monitor.js';
|
||||||
|
import { AlertService } from './src/utils/alert.js';
|
||||||
|
import 'dotenv/config';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试并发获取价格(模拟实际运行场景)
|
||||||
|
*/
|
||||||
|
async function testConcurrentFetch(): Promise<void> {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试并发价格获取');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
const db = new DatabaseService();
|
||||||
|
const scraper = new ScraperService();
|
||||||
|
const alertService = new AlertService();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 初始化
|
||||||
|
console.log('1. 初始化服务...');
|
||||||
|
await db.init();
|
||||||
|
await alertService.init();
|
||||||
|
await scraper.init();
|
||||||
|
console.log('✅ 初始化完成\n');
|
||||||
|
|
||||||
|
// 创建监控服务
|
||||||
|
const threshold = Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2;
|
||||||
|
const monitor = new SilverBaselineMonitor(
|
||||||
|
db,
|
||||||
|
threshold,
|
||||||
|
alertService,
|
||||||
|
process.env.WEBHOOK_URL
|
||||||
|
);
|
||||||
|
|
||||||
|
// 模拟并发获取(就像实际运行时一样)
|
||||||
|
console.log('2. 并发获取价格(模拟实际场景)...');
|
||||||
|
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
scraper.fetchSilverPrices(),
|
||||||
|
scraper.fetchSilverPrice()
|
||||||
|
]);
|
||||||
|
|
||||||
|
console.log('\n结果:');
|
||||||
|
results.forEach((result, index) => {
|
||||||
|
const name = index === 0 ? '价差监控' : '白银基线监控';
|
||||||
|
if (result.status === 'fulfilled') {
|
||||||
|
console.log(`✅ ${name}: 成功`);
|
||||||
|
if (result.value) {
|
||||||
|
if (index === 0) {
|
||||||
|
const data = result.value as any;
|
||||||
|
console.log(` 美白银: ${data.usSilver}, 伦敦银: ${data.londonSilver}`);
|
||||||
|
} else {
|
||||||
|
const data = result.value as any;
|
||||||
|
console.log(` 白银销售价: ${data.sellPrice}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`❌ ${name}: 失败 - ${result.reason}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('\n3. 再次测试(确保可以重复执行)...');
|
||||||
|
const results2 = await Promise.allSettled([
|
||||||
|
scraper.fetchSilverPrices(),
|
||||||
|
scraper.fetchSilverPrice()
|
||||||
|
]);
|
||||||
|
|
||||||
|
console.log('\n第二次结果:');
|
||||||
|
results2.forEach((result, index) => {
|
||||||
|
const name = index === 0 ? '价差监控' : '白银基线监控';
|
||||||
|
if (result.status === 'fulfilled') {
|
||||||
|
console.log(`✅ ${name}: 成功`);
|
||||||
|
} else {
|
||||||
|
console.log(`❌ ${name}: 失败 - ${result.reason}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('测试完成!');
|
||||||
|
console.log('========================================');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('测试失败:', error);
|
||||||
|
} finally {
|
||||||
|
await scraper.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行测试
|
||||||
|
testConcurrentFetch();
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/**
|
||||||
|
* 测试数据库历史告警查询方法
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { DatabaseService } from './src/services/database.js';
|
||||||
|
|
||||||
|
// 初始化服务
|
||||||
|
const db = new DatabaseService();
|
||||||
|
await db.init();
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试数据库历史告警查询功能');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 测试获取最近已触发告警的记录
|
||||||
|
console.log('### 测试 getRecentTriggeredAnalyses() ###');
|
||||||
|
|
||||||
|
// 获取所有分析记录
|
||||||
|
const allAnalyses = db.getRecentTriggeredAnalyses(1000);
|
||||||
|
console.log(`\n总分析记录数: ${allAnalyses.length}`);
|
||||||
|
|
||||||
|
// 统计已触发告警的记录
|
||||||
|
const triggeredCount = allAnalyses.length;
|
||||||
|
console.log(`已触发告警的记录数: ${triggeredCount}`);
|
||||||
|
|
||||||
|
// 测试获取最近 3 条
|
||||||
|
console.log('\n### 获取最近 3 条已触发告警的记录 ###');
|
||||||
|
const recent3 = db.getRecentTriggeredAnalyses(3);
|
||||||
|
console.log(`获取到 ${recent3.length} 条记录:`);
|
||||||
|
|
||||||
|
if (recent3.length > 0) {
|
||||||
|
recent3.forEach((alert, index) => {
|
||||||
|
const time = new Date(alert.timestamp).toLocaleString('zh-CN');
|
||||||
|
console.log(`\n[${index + 1}] 时间: ${time}`);
|
||||||
|
console.log(` 趋势: ${alert.trend}`);
|
||||||
|
console.log(` 总结: ${alert.summary}`);
|
||||||
|
console.log(` 风险: ${alert.risk}`);
|
||||||
|
console.log(` 置信度: ${(alert.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 信号: ${alert.signals.slice(0, 2).join('; ')}...`);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log(' 没有已触发告警的记录');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试边界情况
|
||||||
|
console.log('\n### 测试边界情况 ###');
|
||||||
|
|
||||||
|
// 获取超过实际数量的记录
|
||||||
|
const largeCount = db.getRecentTriggeredAnalyses(10000);
|
||||||
|
console.log(`\n请求 10000 条,实际返回 ${largeCount.length} 条`);
|
||||||
|
|
||||||
|
// 获取 0 条
|
||||||
|
const zeroCount = db.getRecentTriggeredAnalyses(0);
|
||||||
|
console.log(`请求 0 条,实际返回 ${zeroCount.length} 条`);
|
||||||
|
|
||||||
|
// 获取 1 条
|
||||||
|
const oneCount = db.getRecentTriggeredAnalyses(1);
|
||||||
|
console.log(`请求 1 条,实际返回 ${oneCount.length} 条`);
|
||||||
|
if (oneCount.length > 0) {
|
||||||
|
const alert = oneCount[0];
|
||||||
|
console.log(` 最新告警: ${alert.trend} - ${alert.summary}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('测试完成');
|
||||||
|
console.log('========================================');
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ScraperService } from './src/services/scraper.js';
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const scraper = new ScraperService();
|
||||||
|
await scraper.init();
|
||||||
|
|
||||||
|
console.log('调用 debugFetchAllPrices...');
|
||||||
|
await scraper.debugFetchAllPrices();
|
||||||
|
|
||||||
|
await scraper.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
test();
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { AlertService } from './src/utils/alert.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试飞书汇总报告功能
|
||||||
|
*/
|
||||||
|
async function testFeishuSummary() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试飞书汇总报告功能');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 检查环境变量
|
||||||
|
const webhookUrl = process.env.WEBHOOK_URL;
|
||||||
|
if (!webhookUrl) {
|
||||||
|
console.error('❌ 错误: 未设置 WEBHOOK_URL 环境变量');
|
||||||
|
console.log('请在 .env 文件中配置 Webhook 地址');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('✅ 飞书 Webhook 已配置');
|
||||||
|
console.log(`Webhook URL: ${webhookUrl}\n`);
|
||||||
|
|
||||||
|
// 创建告警服务实例
|
||||||
|
const alertService = new AlertService();
|
||||||
|
await alertService.init();
|
||||||
|
|
||||||
|
// 模拟汇总数据
|
||||||
|
const summaryData = {
|
||||||
|
runCount: 60,
|
||||||
|
totalPrices: 1250,
|
||||||
|
totalChanges: 15,
|
||||||
|
riseCount: 8,
|
||||||
|
fallCount: 7,
|
||||||
|
currentPrice: {
|
||||||
|
usSilver: '32.50',
|
||||||
|
londonSilver: '32.20',
|
||||||
|
spread: 0.300
|
||||||
|
},
|
||||||
|
recentChanges: [
|
||||||
|
{
|
||||||
|
timestamp: Date.now() - 3600000, // 1小时前
|
||||||
|
changeType: 'RISE',
|
||||||
|
currentSpread: 0.250
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: Date.now() - 1800000, // 30分钟前
|
||||||
|
changeType: 'FALL',
|
||||||
|
currentSpread: -0.150
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: Date.now() - 900000, // 15分钟前
|
||||||
|
changeType: 'RISE',
|
||||||
|
currentSpread: 0.300
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('发送测试报告...\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await alertService.sendFeishuSummary(webhookUrl, summaryData);
|
||||||
|
console.log('\n✅ 测试完成!请检查飞书是否收到消息');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\n❌ 测试失败:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行测试
|
||||||
|
testFeishuSummary();
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ScraperService } from './src/services/scraper.js';
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const scraper = new ScraperService();
|
||||||
|
await scraper.init();
|
||||||
|
const prices = await scraper.fetchPrices();
|
||||||
|
console.log('找到的商品:');
|
||||||
|
for (const [name, price] of prices.entries()) {
|
||||||
|
console.log(' -', name);
|
||||||
|
}
|
||||||
|
await scraper.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
test();
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
/**
|
||||||
|
* 测试 LLM 历史上下文功能
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { DatabaseService } from './src/services/database.js';
|
||||||
|
import { LLMClient } from './src/utils/llm-client.js';
|
||||||
|
import type { PriceDataPoint, TrendAnalysisRecord } from './src/types/index.js';
|
||||||
|
|
||||||
|
// 初始化服务
|
||||||
|
const db = new DatabaseService();
|
||||||
|
await db.init();
|
||||||
|
|
||||||
|
// 创建 LLM 客户端
|
||||||
|
const llmClient = new LLMClient({
|
||||||
|
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'
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试 LLM 历史上下文功能');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 测试场景 1: 无历史告警记录
|
||||||
|
console.log('\n### 测试场景 1: 无历史告警记录 ###');
|
||||||
|
{
|
||||||
|
const dataPoints: PriceDataPoint[] = db.getRecentPricePoints(30);
|
||||||
|
console.log(`获取到 ${dataPoints.length} 个价格数据点`);
|
||||||
|
|
||||||
|
const historyAlerts: TrendAnalysisRecord[] = [];
|
||||||
|
console.log('历史告警记录: 0 条');
|
||||||
|
|
||||||
|
const result = await llmClient.analyzeTrendWithHistory(dataPoints, historyAlerts);
|
||||||
|
console.log('\n分析结果:');
|
||||||
|
console.log(` 趋势: ${result.trend}`);
|
||||||
|
console.log(` 置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 风险: ${result.risk}`);
|
||||||
|
console.log(` 通知决策: ${result.shouldNotify ? '发送' : '跳过'}`);
|
||||||
|
console.log(` 决策原因: ${result.notifyReason}`);
|
||||||
|
console.log(` 总结: ${result.summary}`);
|
||||||
|
console.log(` 信号: ${result.signals.join('; ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试场景 2: 有历史告警记录
|
||||||
|
console.log('\n\n### 测试场景 2: 有历史告警记录 ###');
|
||||||
|
{
|
||||||
|
const dataPoints: PriceDataPoint[] = db.getRecentPricePoints(30);
|
||||||
|
console.log(`获取到 ${dataPoints.length} 个价格数据点`);
|
||||||
|
|
||||||
|
const historyAlerts = db.getRecentTriggeredAnalyses(3);
|
||||||
|
console.log(`历史告警记录: ${historyAlerts.length} 条`);
|
||||||
|
|
||||||
|
if (historyAlerts.length > 0) {
|
||||||
|
console.log('\n历史告警详情:');
|
||||||
|
historyAlerts.forEach((alert, index) => {
|
||||||
|
console.log(` [${index + 1}] ${alert.trend} - ${alert.summary}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await llmClient.analyzeTrendWithHistory(dataPoints, historyAlerts);
|
||||||
|
console.log('\n分析结果:');
|
||||||
|
console.log(` 趋势: ${result.trend}`);
|
||||||
|
console.log(` 置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 风险: ${result.risk}`);
|
||||||
|
console.log(` 通知决策: ${result.shouldNotify ? '发送' : '跳过'}`);
|
||||||
|
console.log(` 决策原因: ${result.notifyReason}`);
|
||||||
|
console.log(` 总结: ${result.summary}`);
|
||||||
|
console.log(` 信号: ${result.signals.join('; ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试场景 3: 测试数据库方法
|
||||||
|
console.log('\n\n### 测试场景 3: 测试数据库方法 ###');
|
||||||
|
{
|
||||||
|
const recentAlerts = db.getRecentTriggeredAnalyses(3);
|
||||||
|
console.log(`获取最近 3 次已触发告警的记录:`);
|
||||||
|
console.log(` 总数: ${recentAlerts.length} 条`);
|
||||||
|
|
||||||
|
if (recentAlerts.length > 0) {
|
||||||
|
recentAlerts.forEach((alert, index) => {
|
||||||
|
const time = new Date(alert.timestamp).toLocaleString('zh-CN');
|
||||||
|
console.log(` [${index + 1}] ${time} - ${alert.trend} (${alert.risk})`);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log(' 没有已触发告警的记录');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('测试完成');
|
||||||
|
console.log('========================================');
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { LLMClient } from './src/utils/llm-client.js';
|
||||||
|
import type { PriceDataPoint } from './src/types/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试 LLM 趋势分析功能
|
||||||
|
*/
|
||||||
|
async function testLLMTrend() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('LLM 趋势分析测试');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 检查环境变量
|
||||||
|
const apiKey = process.env.LLM_API_KEY;
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error('❌ 错误:未配置 LLM_API_KEY 环境变量');
|
||||||
|
console.log('请在 .env 文件中设置 LLM_API_KEY');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建 LLM 客户端
|
||||||
|
const config = {
|
||||||
|
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
|
||||||
|
apiKey: apiKey,
|
||||||
|
model: process.env.LLM_MODEL || 'gpt-4o-mini',
|
||||||
|
timeout: 120000 // 智谱AI推理模型需要更长时间
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('配置信息:');
|
||||||
|
console.log(` API Base: ${config.apiBase}`);
|
||||||
|
console.log(` Model: ${config.model}`);
|
||||||
|
console.log(` Timeout: ${config.timeout}ms\n`);
|
||||||
|
|
||||||
|
const llmClient = new LLMClient(config);
|
||||||
|
|
||||||
|
// 准备测试数据(模拟最近 30 分钟的价格数据)
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 模拟价格上涨趋势
|
||||||
|
const price = basePrice + (Math.random() * 0.5 - 0.1) + (30 - i) * 0.01;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - (basePrice + (Math.random() * 0.5 - 0.1) + (29 - i) * 0.01)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({
|
||||||
|
price: parseFloat(price.toFixed(3)),
|
||||||
|
timestamp,
|
||||||
|
changeFromPrevious: changeFromPrevious ? parseFloat(changeFromPrevious.toFixed(3)) : undefined,
|
||||||
|
volatility: Math.random() * 0.01
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`准备了 ${testData.length} 个测试数据点`);
|
||||||
|
console.log('最后 5 个数据点:');
|
||||||
|
testData.slice(-5).forEach(point => {
|
||||||
|
console.log(` ${new Date(point.timestamp).toLocaleTimeString('zh-CN')} - ${point.price.toFixed(3)}`);
|
||||||
|
});
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 调用 LLM 分析
|
||||||
|
console.log('开始 LLM 分析...\n');
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
|
||||||
|
// 显示结果
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('分析结果');
|
||||||
|
console.log('========================================');
|
||||||
|
console.log(`趋势类型: ${result.trend}`);
|
||||||
|
console.log(`置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(`风险评估: ${result.risk}`);
|
||||||
|
console.log(`\n趋势总结:`);
|
||||||
|
console.log(` ${result.summary}`);
|
||||||
|
console.log(`\n关键信号:`);
|
||||||
|
result.signals.forEach((signal, index) => {
|
||||||
|
console.log(` ${index + 1}. ${signal}`);
|
||||||
|
});
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 显示完整的 JSON 结果
|
||||||
|
console.log('完整的 JSON 结果:');
|
||||||
|
console.log(JSON.stringify(result, null, 2));
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
console.log('✅ 测试成功!');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\n❌ 测试失败:');
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行测试
|
||||||
|
testLLMTrend();
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { LLMClient } from './src/utils/llm-client.js';
|
||||||
|
import type { PriceDataPoint } from './src/types/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试小幅波动场景(波动 < 0.2)
|
||||||
|
*/
|
||||||
|
async function testLowVolatility() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试小幅波动场景(波动 < 0.2)');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 检查环境变量
|
||||||
|
const apiKey = process.env.LLM_API_KEY;
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error('❌ 错误:未配置 LLM_API_KEY 环境变量');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
|
||||||
|
apiKey: apiKey,
|
||||||
|
model: process.env.LLM_MODEL || 'gpt-4o-mini',
|
||||||
|
timeout: 120000
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('配置信息:');
|
||||||
|
console.log(` API Base: ${config.apiBase}`);
|
||||||
|
console.log(` Model: ${config.model}`);
|
||||||
|
console.log(` Timeout: ${config.timeout}ms\n`);
|
||||||
|
|
||||||
|
const llmClient = new LLMClient(config);
|
||||||
|
|
||||||
|
// 准备小幅波动的测试数据(波动幅度约 0.12)
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 创建小幅波动:价格在 22.0 到 22.12 之间波动
|
||||||
|
const price = basePrice + Math.sin(i * 0.5) * 0.06 + Math.random() * 0.02;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - testData[testData.length - 1].price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const volatility = i > 0 && testData.length > 0
|
||||||
|
? Math.abs(changeFromPrevious!) / price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({
|
||||||
|
price,
|
||||||
|
timestamp,
|
||||||
|
changeFromPrevious,
|
||||||
|
volatility
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算实际波动幅度
|
||||||
|
const prices = testData.slice(-10).map(p => p.price);
|
||||||
|
const maxPrice = Math.max(...prices);
|
||||||
|
const minPrice = Math.min(...prices);
|
||||||
|
const range = maxPrice - minPrice;
|
||||||
|
|
||||||
|
console.log(`测试数据特征:`);
|
||||||
|
console.log(` 最近 10 分钟最高价: ${maxPrice.toFixed(3)}`);
|
||||||
|
console.log(` 最近 10 分钟最低价: ${minPrice.toFixed(3)}`);
|
||||||
|
console.log(` 波动幅度: ${range.toFixed(3)} ${range < 0.2 ? '(< 0.2)' : '(≥ 0.2)'}`);
|
||||||
|
console.log(`\n预期:LLM 应判定为 ${range < 0.2 ? 'sideways/uptrend/downtrend(非 volatile)' : 'volatile'}\n`);
|
||||||
|
|
||||||
|
console.log('开始 LLM 分析...\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('分析结果');
|
||||||
|
console.log('========================================');
|
||||||
|
console.log(`趋势类型: ${result.trend}`);
|
||||||
|
console.log(`置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(`风险评估: ${result.risk}`);
|
||||||
|
console.log(`\n趋势总结:`);
|
||||||
|
console.log(` ${result.summary}`);
|
||||||
|
console.log(`\n关键信号:`);
|
||||||
|
result.signals.forEach((signal, index) => {
|
||||||
|
console.log(` ${index + 1}. ${signal}`);
|
||||||
|
});
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 验证结果
|
||||||
|
const isCorrect = result.trend !== 'volatile' || range > 0.2;
|
||||||
|
if (isCorrect) {
|
||||||
|
console.log('✅ 测试通过!LLM 正确应用了 0.2 的波动阈值');
|
||||||
|
} else {
|
||||||
|
console.log('❌ 测试失败!LLM 误判为 volatile,但实际波动幅度 < 0.2');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\n❌ 测试失败:');
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testLowVolatility();
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { LLMClient } from './src/utils/llm-client.js';
|
||||||
|
import type { PriceDataPoint } from './src/types/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试不同风险等级的判断标准
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 检查环境变量
|
||||||
|
const apiKey = process.env.LLM_API_KEY;
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error('❌ 错误:未配置 LLM_API_KEY 环境变量');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
|
||||||
|
apiKey: apiKey,
|
||||||
|
model: process.env.LLM_MODEL || 'gpt-4o-mini',
|
||||||
|
timeout: 120000
|
||||||
|
};
|
||||||
|
|
||||||
|
const llmClient = new LLMClient(config);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 场景1:高风险(波动 > 0.3元)
|
||||||
|
*/
|
||||||
|
async function testHighRisk() {
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('场景 1: 高风险(波动 > 0.3 元)');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 创建剧烈波动:22.0 → 22.5 → 22.1 → 22.6,波动幅度 > 0.3
|
||||||
|
let price = basePrice;
|
||||||
|
if (i > 20) price = 22.0 + Math.random() * 0.1;
|
||||||
|
else if (i > 10) price = 22.5 + Math.random() * 0.1;
|
||||||
|
else price = 22.1 + Math.random() * 0.5;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - testData[testData.length - 1].price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const volatility = i > 0 && testData.length > 0
|
||||||
|
? Math.abs(changeFromPrevious!) / price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({ price, timestamp, changeFromPrevious, volatility });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prices = testData.slice(-10).map(p => p.price);
|
||||||
|
const range = Math.max(...prices) - Math.min(...prices);
|
||||||
|
|
||||||
|
console.log(`数据特征:`);
|
||||||
|
console.log(` 最近10分钟波动幅度: ${range.toFixed(3)} 元`);
|
||||||
|
console.log(` 预期风险: high ${range > 0.3 ? '✅' : '❌'}\n`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
console.log(`LLM 判断结果:`);
|
||||||
|
console.log(` 趋势: ${result.trend}`);
|
||||||
|
console.log(` 风险: ${result.risk} ${result.risk === 'high' ? '✅' : '⚠️'}`);
|
||||||
|
console.log(` 置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 总结: ${result.summary}`);
|
||||||
|
return result.risk === 'high';
|
||||||
|
} catch (error) {
|
||||||
|
console.error('测试失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 场景2:中等风险(波动 0.15-0.3元)
|
||||||
|
*/
|
||||||
|
async function testMediumRisk() {
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('场景 2: 中等风险(波动 0.15-0.3 元)');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 创建中等波动:22.0 → 22.25,波动幅度约 0.25
|
||||||
|
let price = basePrice + (i % 2) * 0.12 + Math.random() * 0.05;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - testData[testData.length - 1].price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const volatility = i > 0 && testData.length > 0
|
||||||
|
? Math.abs(changeFromPrevious!) / price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({ price, timestamp, changeFromPrevious, volatility });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prices = testData.slice(-10).map(p => p.price);
|
||||||
|
const range = Math.max(...prices) - Math.min(...prices);
|
||||||
|
|
||||||
|
console.log(`数据特征:`);
|
||||||
|
console.log(` 最近10分钟波动幅度: ${range.toFixed(3)} 元`);
|
||||||
|
console.log(` 预期风险: medium ${range >= 0.15 && range <= 0.3 ? '✅' : '❌'}\n`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
console.log(`LLM 判断结果:`);
|
||||||
|
console.log(` 趋势: ${result.trend}`);
|
||||||
|
console.log(` 风险: ${result.risk} ${result.risk === 'medium' ? '✅' : '⚠️'}`);
|
||||||
|
console.log(` 置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 总结: ${result.summary}`);
|
||||||
|
return result.risk === 'medium';
|
||||||
|
} catch (error) {
|
||||||
|
console.error('测试失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 场景3:低风险(波动 < 0.15元)
|
||||||
|
*/
|
||||||
|
async function testLowRisk() {
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('场景 3: 低风险(波动 < 0.15 元)');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 创建平稳上涨:波动幅度 < 0.15
|
||||||
|
const price = basePrice + (30 - i) * 0.01 + Math.random() * 0.02;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - testData[testData.length - 1].price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const volatility = i > 0 && testData.length > 0
|
||||||
|
? Math.abs(changeFromPrevious!) / price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({ price, timestamp, changeFromPrevious, volatility });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prices = testData.slice(-10).map(p => p.price);
|
||||||
|
const range = Math.max(...prices) - Math.min(...prices);
|
||||||
|
|
||||||
|
console.log(`数据特征:`);
|
||||||
|
console.log(` 最近10分钟波动幅度: ${range.toFixed(3)} 元`);
|
||||||
|
console.log(` 预期风险: low ${range < 0.15 ? '✅' : '❌'}\n`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
console.log(`LLM 判断结果:`);
|
||||||
|
console.log(` 趋势: ${result.trend}`);
|
||||||
|
console.log(` 风险: ${result.risk} ${result.risk === 'low' ? '✅' : '⚠️'}`);
|
||||||
|
console.log(` 置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(` 总结: ${result.summary}`);
|
||||||
|
return result.risk === 'low';
|
||||||
|
} catch (error) {
|
||||||
|
console.error('测试失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 运行所有测试
|
||||||
|
*/
|
||||||
|
async function runAllTests() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试风险评估标准');
|
||||||
|
console.log('========================================');
|
||||||
|
console.log(`配置信息:`);
|
||||||
|
console.log(` API Base: ${config.apiBase}`);
|
||||||
|
console.log(` Model: ${config.model}`);
|
||||||
|
|
||||||
|
const results = {
|
||||||
|
high: await testHighRisk(),
|
||||||
|
medium: await testMediumRisk(),
|
||||||
|
low: await testLowRisk()
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('测试结果汇总');
|
||||||
|
console.log('========================================');
|
||||||
|
console.log(`高风险场景: ${results.high ? '✅ 通过' : '❌ 失败'}`);
|
||||||
|
console.log(`中等风险场景: ${results.medium ? '✅ 通过' : '❌ 失败'}`);
|
||||||
|
console.log(`低风险场景: ${results.low ? '✅ 通过' : '❌ 失败'}`);
|
||||||
|
|
||||||
|
const allPassed = results.high && results.medium && results.low;
|
||||||
|
console.log(`\n${allPassed ? '✅ 所有测试通过!' : '⚠️ 部分测试未通过'}`);
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
process.exit(allPassed ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
runAllTests();
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { DatabaseService } from './src/services/database.js';
|
||||||
|
import { ScraperService } from './src/services/scraper.js';
|
||||||
|
import { SilverBaselineMonitor } from './src/services/silver-baseline-monitor.js';
|
||||||
|
import { AlertService } from './src/utils/alert.js';
|
||||||
|
import 'dotenv/config';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试白银基线监控功能
|
||||||
|
*/
|
||||||
|
async function testSilverBaseline(): Promise<void> {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('白银基线监控测试');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
const db = new DatabaseService();
|
||||||
|
const scraper = new ScraperService();
|
||||||
|
const alertService = new AlertService();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 初始化
|
||||||
|
console.log('1. 初始化服务...');
|
||||||
|
await db.init();
|
||||||
|
await alertService.init();
|
||||||
|
await scraper.init();
|
||||||
|
console.log('✅ 初始化完成\n');
|
||||||
|
|
||||||
|
// 创建监控服务
|
||||||
|
const threshold = Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2;
|
||||||
|
const monitor = new SilverBaselineMonitor(
|
||||||
|
db,
|
||||||
|
threshold,
|
||||||
|
alertService,
|
||||||
|
process.env.WEBHOOK_URL
|
||||||
|
);
|
||||||
|
|
||||||
|
// 获取白银价格
|
||||||
|
console.log('2. 获取白银价格...');
|
||||||
|
const silverPrice = await scraper.fetchSilverPrice();
|
||||||
|
|
||||||
|
if (!silverPrice) {
|
||||||
|
console.error('❌ 获取白银价格失败');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('✅ 获取成功:');
|
||||||
|
console.log(` 商品名称: ${silverPrice.name}`);
|
||||||
|
console.log(` 销售价格: ${silverPrice.sellPrice}`);
|
||||||
|
console.log(` 回购价格: ${silverPrice.buyPrice}`);
|
||||||
|
console.log(` 最高价: ${silverPrice.high}`);
|
||||||
|
console.log(` 最低价: ${silverPrice.low}\n`);
|
||||||
|
|
||||||
|
// 处理价格(测试基线初始化或告警触发)
|
||||||
|
console.log('3. 处理价格监控...');
|
||||||
|
await monitor.processPrice(silverPrice);
|
||||||
|
console.log('✅ 处理完成\n');
|
||||||
|
|
||||||
|
// 显示统计信息
|
||||||
|
console.log('4. 统计信息:');
|
||||||
|
const stats = monitor.getStats();
|
||||||
|
console.log(` 当前基线: ${stats.currentBaseline !== null ? stats.currentBaseline.toFixed(3) : '未初始化'}`);
|
||||||
|
console.log(` 总价格记录: ${stats.totalPrices}`);
|
||||||
|
console.log(` 总告警次数: ${stats.totalAlerts}`);
|
||||||
|
console.log(` 上涨告警: ${stats.riseCount}`);
|
||||||
|
console.log(` 下跌告警: ${stats.fallCount}\n`);
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试完成!');
|
||||||
|
console.log('========================================');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('测试失败:', error);
|
||||||
|
} finally {
|
||||||
|
await scraper.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行测试
|
||||||
|
testSilverBaseline();
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { LLMClient } from './src/utils/llm-client.js';
|
||||||
|
import type { PriceDataPoint } from './src/types/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试上涨趋势场景
|
||||||
|
*/
|
||||||
|
async function testUptrend() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试上涨趋势场景');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 检查环境变量
|
||||||
|
const apiKey = process.env.LLM_API_KEY;
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error('❌ 错误:未配置 LLM_API_KEY 环境变量');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
|
||||||
|
apiKey: apiKey,
|
||||||
|
model: process.env.LLM_MODEL || 'gpt-4o-mini',
|
||||||
|
timeout: 120000
|
||||||
|
};
|
||||||
|
|
||||||
|
const llmClient = new LLMClient(config);
|
||||||
|
|
||||||
|
// 准备上涨趋势的测试数据
|
||||||
|
const testData: PriceDataPoint[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
const basePrice = 22.0;
|
||||||
|
|
||||||
|
for (let i = 30; i >= 0; i--) {
|
||||||
|
const timestamp = new Date(now - i * 60000).toISOString();
|
||||||
|
// 创建缓慢上涨趋势
|
||||||
|
const price = basePrice + (30 - i) * 0.015 + Math.random() * 0.05;
|
||||||
|
|
||||||
|
const changeFromPrevious = i < 30
|
||||||
|
? price - testData[testData.length - 1].price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const volatility = i > 0 && testData.length > 0
|
||||||
|
? Math.abs(changeFromPrevious!) / price
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
testData.push({
|
||||||
|
price,
|
||||||
|
timestamp,
|
||||||
|
changeFromPrevious,
|
||||||
|
volatility
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算统计数据
|
||||||
|
const allPrices = testData.map(p => p.price);
|
||||||
|
const maxPrice = Math.max(...allPrices);
|
||||||
|
const minPrice = Math.min(...allPrices);
|
||||||
|
const totalRange = maxPrice - minPrice;
|
||||||
|
|
||||||
|
const recent10Prices = testData.slice(-10).map(p => p.price);
|
||||||
|
const currentPrice = recent10Prices[recent10Prices.length - 1];
|
||||||
|
const first10Price = recent10Prices[0];
|
||||||
|
const change10 = currentPrice - first10Price;
|
||||||
|
|
||||||
|
console.log(`测试数据特征:`);
|
||||||
|
console.log(` 当前价格: ${currentPrice.toFixed(3)} 元`);
|
||||||
|
console.log(` 30分钟总价差: ${totalRange.toFixed(3)} 元 (${minPrice.toFixed(3)} → ${maxPrice.toFixed(3)})`);
|
||||||
|
console.log(` 近10分钟变化: ${change10 > 0 ? '+' : ''}${change10.toFixed(3)} 元`);
|
||||||
|
console.log(`\n预期:LLM 应判定为 uptrend 并说明上涨幅度\n`);
|
||||||
|
|
||||||
|
console.log('开始 LLM 分析...\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await llmClient.analyzeTrend(testData);
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('分析结果');
|
||||||
|
console.log('========================================');
|
||||||
|
console.log(`趋势类型: ${result.trend}`);
|
||||||
|
console.log(`置信度: ${(result.confidence * 100).toFixed(0)}%`);
|
||||||
|
console.log(`风险评估: ${result.risk}`);
|
||||||
|
console.log(`\n趋势总结:`);
|
||||||
|
console.log(` ${result.summary}`);
|
||||||
|
console.log(`\n关键信号:`);
|
||||||
|
result.signals.forEach((signal, index) => {
|
||||||
|
console.log(` ${index + 1}. ${signal}`);
|
||||||
|
});
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 验证是否包含了所需信息
|
||||||
|
const hasCurrentPrice = result.summary.includes('元');
|
||||||
|
const hasTotalRange = result.summary.match(/总价差.*?\d+\.?\d*\s*元/);
|
||||||
|
const hasChangeAmount = result.trend === 'uptrend' &&
|
||||||
|
(result.summary.includes('上涨') || result.summary.includes('涨') ||
|
||||||
|
result.summary.includes('增加') || result.summary.includes('升'));
|
||||||
|
|
||||||
|
console.log('验证结果:');
|
||||||
|
console.log(` ✅ 包含单位"元": ${hasCurrentPrice}`);
|
||||||
|
console.log(` ✅ 包含总价差: ${hasTotalRange ? '是' : '否'}`);
|
||||||
|
console.log(` ✅ 说明上涨幅度: ${hasChangeAmount}`);
|
||||||
|
|
||||||
|
if (hasCurrentPrice && hasTotalRange) {
|
||||||
|
console.log('\n✅ 测试通过!LLM 正确包含了价格信息');
|
||||||
|
} else {
|
||||||
|
console.log('\n⚠️ 部分信息缺失,请检查summary');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\n❌ 测试失败:');
|
||||||
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testUptrend();
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import type { PriceDataPoint } from './src/types/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算最近 N 个数据点的价格波动幅度
|
||||||
|
*/
|
||||||
|
function 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试波动幅度阈值逻辑
|
||||||
|
*/
|
||||||
|
function testVolatilityThreshold() {
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('测试波动幅度阈值逻辑');
|
||||||
|
console.log('========================================\n');
|
||||||
|
|
||||||
|
// 测试场景 1:小幅波动(0.15)
|
||||||
|
console.log('场景 1: 小幅波动');
|
||||||
|
const scenario1: PriceDataPoint[] = Array.from({ length: 10 }, (_, i) => ({
|
||||||
|
price: 22.0 + (i % 3) * 0.05 + Math.random() * 0.02,
|
||||||
|
timestamp: new Date(Date.now() - (10 - i) * 60000).toISOString()
|
||||||
|
}));
|
||||||
|
const range1 = calculatePriceRange(scenario1, 10);
|
||||||
|
console.log(` 波动幅度: ${range1.toFixed(3)}`);
|
||||||
|
console.log(` 是否触发告警: ${range1 > 0.2 ? '是 ✅' : '否 ❌'}`);
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
// 测试场景 2:中等波动(0.25)
|
||||||
|
console.log('场景 2: 中等波动');
|
||||||
|
const scenario2: PriceDataPoint[] = Array.from({ length: 10 }, (_, i) => ({
|
||||||
|
price: 22.0 + (i % 5) * 0.06 + Math.random() * 0.02,
|
||||||
|
timestamp: new Date(Date.now() - (10 - i) * 60000).toISOString()
|
||||||
|
}));
|
||||||
|
const range2 = calculatePriceRange(scenario2, 10);
|
||||||
|
console.log(` 波动幅度: ${range2.toFixed(3)}`);
|
||||||
|
console.log(` 是否触发告警: ${range2 > 0.2 ? '是 ✅' : '否 ❌'}`);
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
// 测试场景 3:大幅波动(0.5)
|
||||||
|
console.log('场景 3: 大幅波动');
|
||||||
|
const scenario3: PriceDataPoint[] = Array.from({ length: 10 }, (_, i) => ({
|
||||||
|
price: 22.0 + (i % 7) * 0.08 + Math.random() * 0.02,
|
||||||
|
timestamp: new Date(Date.now() - (10 - i) * 60000).toISOString()
|
||||||
|
}));
|
||||||
|
const range3 = calculatePriceRange(scenario3, 10);
|
||||||
|
console.log(` 波动幅度: ${range3.toFixed(3)}`);
|
||||||
|
console.log(` 是否触发告警: ${range3 > 0.2 ? '是 ✅' : '否 ❌'}`);
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
// 测试场景 4:模拟真实剧烈波动
|
||||||
|
console.log('场景 4: 模拟真实剧烈波动(22.0 → 22.6 → 22.2)');
|
||||||
|
const scenario4: PriceDataPoint[] = [
|
||||||
|
{ price: 22.0, timestamp: new Date(Date.now() - 9 * 60000).toISOString() },
|
||||||
|
{ price: 22.1, timestamp: new Date(Date.now() - 8 * 60000).toISOString() },
|
||||||
|
{ price: 22.2, timestamp: new Date(Date.now() - 7 * 60000).toISOString() },
|
||||||
|
{ price: 22.35, timestamp: new Date(Date.now() - 6 * 60000).toISOString() },
|
||||||
|
{ price: 22.5, timestamp: new Date(Date.now() - 5 * 60000).toISOString() },
|
||||||
|
{ price: 22.6, timestamp: new Date(Date.now() - 4 * 60000).toISOString() },
|
||||||
|
{ price: 22.5, timestamp: new Date(Date.now() - 3 * 60000).toISOString() },
|
||||||
|
{ price: 22.35, timestamp: new Date(Date.now() - 2 * 60000).toISOString() },
|
||||||
|
{ price: 22.25, timestamp: new Date(Date.now() - 1 * 60000).toISOString() },
|
||||||
|
{ price: 22.2, timestamp: new Date().toISOString() }
|
||||||
|
];
|
||||||
|
const range4 = calculatePriceRange(scenario4, 10);
|
||||||
|
console.log(` 最高价: ${Math.max(...scenario4.map(p => p.price)).toFixed(3)}`);
|
||||||
|
console.log(` 最低价: ${Math.min(...scenario4.map(p => p.price)).toFixed(3)}`);
|
||||||
|
console.log(` 波动幅度: ${range4.toFixed(3)}`);
|
||||||
|
console.log(` 是否触发告警: ${range4 > 0.2 ? '是 ✅' : '否 ❌'}`);
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('✅ 测试完成!');
|
||||||
|
console.log('========================================');
|
||||||
|
}
|
||||||
|
|
||||||
|
testVolatilityThreshold();
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import 'dotenv/config';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试飞书 Webhook
|
||||||
|
*/
|
||||||
|
async function testFeishuWebhook() {
|
||||||
|
const webhookUrl = process.env.WEBHOOK_URL;
|
||||||
|
|
||||||
|
if (!webhookUrl) {
|
||||||
|
console.error('❌ 未配置 WEBHOOK_URL 环境变量');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('📡 Webhook URL:', webhookUrl);
|
||||||
|
console.log('🔍 开始测试...\n');
|
||||||
|
|
||||||
|
// 测试消息格式
|
||||||
|
const testMessages = [
|
||||||
|
{
|
||||||
|
name: '飞书文本消息',
|
||||||
|
message: {
|
||||||
|
msg_type: 'text',
|
||||||
|
content: {
|
||||||
|
text: '价格变化告警测试\n时间: 2026/1/13 00:31:21\n变化类型: 下跌\n美白银: 86.14\n伦敦银: 86.023\n价差: 0.117'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '自定义文本消息(当前代码格式)',
|
||||||
|
message: {
|
||||||
|
msgtype: 'text',
|
||||||
|
text: {
|
||||||
|
content: '价格变化告警\n时间: 2026/1/13 00:31:21\n变化类型: 下跌\n美白银: 86.14\n伦敦银: 86.023\n价差: 0.117'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const test of testMessages) {
|
||||||
|
console.log(`\n========================================`);
|
||||||
|
console.log(`测试: ${test.name}`);
|
||||||
|
console.log('========================================');
|
||||||
|
console.log('请求体:', JSON.stringify(test.message, null, 2));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(webhookUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(test.message)
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`\n状态码: ${response.status} ${response.statusText}`);
|
||||||
|
console.log(`ok: ${response.ok}`);
|
||||||
|
|
||||||
|
// 获取响应体
|
||||||
|
const responseText = await response.text();
|
||||||
|
console.log(`响应体: ${responseText || '(空)'}`);
|
||||||
|
|
||||||
|
// 尝试解析为 JSON
|
||||||
|
try {
|
||||||
|
const jsonResponse = JSON.parse(responseText);
|
||||||
|
console.log('响应 JSON:', JSON.stringify(jsonResponse, null, 2));
|
||||||
|
} catch {
|
||||||
|
// 不是 JSON
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示响应头
|
||||||
|
console.log('\n响应头:');
|
||||||
|
response.headers.forEach((value, key) => {
|
||||||
|
console.log(` ${key}: ${value}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error(`\n❌ 请求失败:`, error.message);
|
||||||
|
console.error('错误详情:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n========================================');
|
||||||
|
console.log('✅ 测试完成');
|
||||||
|
console.log('========================================');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行测试
|
||||||
|
testFeishuWebhook().catch(console.error);
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user