feat: AI analysis engine refactor, dark theme polish & virtual position management

Core changes:
- Refactor FastAnalysisService: single LLM multi-factor analysis replaces
  7-agent pipeline; add multi-timeframe consensus, threshold calibration,
  confidence calibration, multi-model ensemble voting
- Add RAG memory injection and reflection validation (analysis_memory +
  reflection worker)
- Simplify billing config: remove unused strategy_run/backtest/portfolio_monitor,
  add ai_code_gen separate billing (different token consumption scale)
- Settings hot-reload after save, no backend restart needed

Frontend:
- Global dark theme overhaul: pure black palette replacing blue-tinted colors
  across sidebar/header/dashboard/analysis/K-line/user-manage/profile/settings/billing
- Fix USDT payment modal dark theme (portal rendering broke CSS selectors)
- Refactor position modal: direction + quantity + entry price, remove add/reduce
  logic, show raw DB values on re-open, save exactly what user inputs
- Fix Polymarket prediction market dark text
- i18n for position modal title

Backend:
- Position management: one record per symbol (DELETE+INSERT replacing
  ON CONFLICT with side), fixes PnL showing 0 when switching long/short
- MarketDataCollector data fetching optimization
- portfolio_monitor scheduled monitoring improvements
- env.example reorganized: common config first, advanced config last

Documentation:
- README architecture diagram updated to FastAnalysisService flow
- Add virtual position, AI tuning config, billing items documentation
- Add INDICATOR_DEFINITIONS_CN.md, FRONTEND_FAST_ANALYSIS.md

Made-with: Cursor
This commit is contained in:
Dinger
2026-03-23 23:01:04 +08:00
parent 05f07ee544
commit 2e9c7cd69e
96 changed files with 2131 additions and 780 deletions
+62
View File
@@ -0,0 +1,62 @@
# 快速分析(Fast Analysis)前端对接说明
本开源仓库中的 **`frontend/` 仅包含构建产物 `dist/`**,Vue 源码在**私有前端仓库**(见根目录 `.github/workflows/update-frontend.yml`)。因此在本仓库内**无法直接修改** `FastAnalysisReport.vue` 等组件,需要在私有仓库中按下列说明调整。
## 1. 止盈 / 止损显示反了(BUY/SELL)
### 后端约定(`/api/fast-analysis/analyze`
- **`trading_plan.stop_loss` / `trading_plan.take_profit`** 已与 `decision` 对齐几何关系:
- **BUY**`stop_loss < 现价 < take_profit`
- **SELL(空)**`take_profit < 现价 < stop_loss`(止损在上方,止盈在下方)
- **`indicators.trading_levels.suggested_stop_loss / suggested_take_profit`** 在采集器里是**多单(做多)参考价**,**不能**在 SELL 时直接拿来当界面上的「止损/止盈」两行,否则会和空单几何相反。
### 前端常见错误
- 第一行写死绑定 `trading_levels.suggested_stop_loss`、第二行绑定 `suggested_take_profit`
- 或把 `stop_loss` / `take_profit` **标签写反**(模板里「止损」绑了 `take_profit`)。
### 推荐写法(私有仓库中修改)
只使用接口返回的 **`data.trading_plan`**(或兼容字段 **`stopLoss` / `takeProfit`**):
```text
止损(亏损离场价): trading_plan.stop_loss (或 stopLoss
止盈(盈利目标价): trading_plan.take_profit (或 takeProfit
```
可选:根据 `trading_plan.decision === 'SELL'` 在文案旁加一句「空单:止损在现价上方,止盈在现价下方」。
### API 兼容字段(后端已加)
`trading_plan` 内额外包含:
- `entryPrice`, `stopLoss`, `takeProfit`, `positionSizePct`
- `loss_exit_price`, `profit_target_price`(与止损/止盈数值一致,语义更清晰)
- `decision`:与主结果 `decision` 一致,便于组件内判断
根级另有驼峰:`trendOutlook`, `trendOutlookSummary`(与 `trend_outlook` 等相同内容)。
## 2. 「未来时间段预判」不显示
后端字段:
- **`trend_outlook`**:对象,含 `next_24h`, `next_3d`, `next_1w`, `next_1m`(每项含 `score`, `trend`, `strength`)。
- **`trend_outlook_summary`**:一行可读摘要(中文/英文随 `language`)。
- 若走 **`/api/fast-analysis/analyze-legacy`**`fast_analysis` 内同样有上述字段;`overview.report` 会追加 **【周期预判】** 段落;顶层也有 `trend_outlook` / `trend_outlook_summary`
### 前端需要做的
- 在快速分析结果页**单独渲染** `trend_outlook``trend_outlook_summary`(不要只读 `summary` 正文)。
- 若请求的是 legacy 接口,请读 **`data.fast_analysis.trend_outlook`** 或顶层 **`data.trend_outlook`**,不要假设只在某一嵌套路径下。
## 3. 自检清单
| 检查项 | 说明 |
|--------|------|
| 接口路径 | 确认用的是 `/analyze` 还是 `/analyze-legacy`,字段路径一致 |
| 绑定来源 | 止损/止盈是否来自 `trading_plan`,而非 `trading_levels` |
| SELL 几何 | 空单位:`take_profit < current < stop_loss` |
| 周期预判 | 模板是否包含 `trend_outlook``trend_outlook_summary` |
更新私有前端仓库后,通过 CI 或手动打包替换本仓库的 `frontend/dist/`(参见 `update-frontend.yml`)。
+18
View File
@@ -0,0 +1,18 @@
# 技术指标计算口径(与代码一致)
本文档与 `backend_api_python/app/services/market_data_collector.py``_calculate_indicators` 及子函数实现**严格对应**。
| 指标 | 实现要点 |
|------|-----------|
| **RSI(14)** | **Wilder RSI**:前 14 期涨跌分别取简单算术平均作为初始均幅;自第 15 期起 `avg = (avg_prev×13 + 当期) / 14`。RS = 均涨幅/均跌幅,RSI = 100 100/(1+RS)。 |
| **MACD(12,26,9)** | 收盘 **EMA12、EMA26**(首值=各自前 N 根 **SMA**,再按 α=2/(N+1) 递推)。**DIF** 从第 26 根 K 起有定义;对 DIF 子序列再算 **EMA9****DEA**;柱 = DIF − DEA。至少需要 **34** 根收盘才能稳定给出信号线(子序列长度≥9)。 |
| **MA5/10/20** | 最近 N 根收盘价的 **SMA**。 |
| **枢轴 Pivot** | **上一根 K** 的高、低、收:P=(H+L+C)/3R1/S1/R2/S2 标准式。 |
| **摆动高/低** | 最近 **20 根 K**`max(high)``min(low)`。 |
| **布林(20,2)** | 中轨 = 最近 20 收盘 **SMA**;方差 = Σ(x−μ)²/**20**(总体方差);σ=√方差;上下轨 = 中轨 ± 2σ;带宽% = (上轨−下轨)/中轨×100。合成支撑/阻力使用 **`BB_upper` / `BB_lower`** 字段。 |
| **ATR(14)** | **Wilder ATR**:TR 定义同经典;首 ATR = 前 14 个 TR 的简单平均;之后 `ATR_t = (ATR_{t-1}×13 + TR_t) / 14`,递推至**最后一根 K**(全序列,非仅尾窗)。 |
| **量比** | 当前根成交量 / 近 **20** 根成交量算术平均。 |
| **区间位置 %** | (当前收盘 − 近20低) / (近20高 − 近20低) × 100;高=低 时为 50。 |
| **合成支撑/阻力** | `(R1 + swing_high + BB_upper) / 3``(S1 + swing_low + BB_lower) / 3`,见 `levels.method`。 |
前端说明文案键:`fastAnalysis.indicatorsProSubtitle`(应与上表同步维护)。
+57 -36
View File
@@ -264,6 +264,7 @@ IMAGE_PREFIX=docker.xuanyuan.me/library/
- **🧠 记忆增强** — 智能体从过去的分析中学习(本地RAG,非云端)
- **🔌 5+ LLM提供商**OpenRouter100+模型)、OpenAI、Gemini、DeepSeek、Grok
- **📊 Polymarket预测市场** — 预测市场按需AI分析。输入市场链接或标题 → AI分析概率差异、机会评分和交易建议。完整历史跟踪和计费集成。
- **📋 虚拟持仓管理** — 自选股中直接创建虚拟持仓,支持做多/做空方向、数量、买入单价,实时计算盈亏。无需连接真实交易所即可跟踪模拟投资组合。
### 📈 完整交易生命周期
@@ -310,7 +311,7 @@ IMAGE_PREFIX=docker.xuanyuan.me/library/
- **💳 会员计划** — 月度/年度/终身层级,可配置定价和积分
- **₿ USDT链上支付** — TRC20扫码支付,每订单地址的HD钱包(xpub),通过TronGrid自动对账
- **🏪 指标市场** — 用户发布和销售Python指标,您收取佣金
- **⚙️ 管理员仪表板** — 订单管理、AI使用统计、用户分析
- **⚙️ 管理员仪表板** — 订单管理、AI使用统计、用户分析;系统设置保存后热重载,无需重启服务
### 🔐 企业级安全
@@ -320,49 +321,67 @@ IMAGE_PREFIX=docker.xuanyuan.me/library/
- **演示模式** — 公共展示的只读模式
<details>
<summary><b>🧠 AI智能体架构图(点击展开)</b></summary>
<summary><b>🧠 AI 分析架构图(点击展开)</b></summary>
当前采用 **FastAnalysisService** 单次 LLM 流程,兼顾速度与多因子决策:
```mermaid
flowchart TB
subgraph Entry["🌐 API入口"]
A["📡 POST /api/analysis/multi"]
A2["🔄 POST /api/analysis/reflect"]
subgraph Entry["🌐 API 入口"]
A["📡 POST /api/fast-analysis/analyze"]
A2["📜 GET /api/fast-analysis/history"]
A3["📊 GET /api/fast-analysis/similar-patterns"]
end
subgraph Service["⚙️ 服务编排"]
B[AnalysisService]
C[AgentCoordinator]
D["📊 构建上下文<br/>价格 · K线 · 新闻 · 指标"]
subgraph Data["📊 数据采集层"]
D1[MarketDataCollector]
D2["价格 · K线 · 宏观 · 新闻 · 基本面"]
D3["多周期共识 1D / 4H / 1H"]
end
subgraph Agents["🤖 7智能体工作流"]
subgraph P1["📈 阶段1 · 并行分析"]
E1["🔍 MarketAnalyst"]
E2["📑 FundamentalAnalyst"]
E3["📰 NewsAnalyst"]
E4["💭 SentimentAnalyst"]
E5["⚠️ RiskAnalyst"]
end
subgraph P2["🎯 阶段2 · 多头vs空头辩论"]
F1["🐂 BullResearcher"]
F2["🐻 BearResearcher"]
end
subgraph P3["💹 阶段3 · 最终决策"]
G["🎰 TraderAgent → 买入 / 卖出 / 持有"]
end
subgraph Analysis["⚙️ 分析层"]
B["FastAnalysisService"]
C["单次 LLM 调用<br/>强约束 Prompt"]
E["客观评分 + 多周期共识"]
F["AICalibration 阈值校准"]
G["买入 / 卖出 / 持有"]
end
subgraph Memory["🧠 本地记忆存储"]
M1[("智能体记忆(PostgreSQL")]
subgraph Memory["🧠 记忆层"]
M1[("qd_analysis_memory<br/>PostgreSQL")]
M2["RAG 相似模式检索<br/>(可选注入 Prompt"]
end
subgraph Reflect["🔄 反思循环"]
R[ReflectionService]
W["⏰ ReflectionWorker → 验证 + 学习"]
end
A --> B --> C --> D
D --> P1 --> P2 --> P3
Agents <-.->|"RAG检索"| M1
C --> R
W -.->|"更新记忆"| M1
A --> B
B --> D1 --> D2 --> D3
D3 --> C --> E --> F --> G
B -.->|"存储"| M1
M1 -.->|"相似模式"| M2
M2 -.->|"可选上下文"| C
A2 --> M1
A3 --> M1
```
**流程概要:**
1. **数据采集** — 统一 `MarketDataCollector` 拉取价格、K 线、宏观、新闻、基本面
2. **多周期共识** — 主周期 + 4H/1D 等技术周期,计算加权客观评分
3. **单次 LLM** — 强约束 Prompt,综合技术 / 宏观 / 新闻 / 基本面
4. **共识校准** — 当客观评分显著时,可覆盖 LLM 决策;数据质量差时倾向 HOLD
5. **记忆存储** — 写入 `qd_analysis_memory`,支持历史查询与相似模式检索
<details>
<summary><b>📈 AI 分析优化(已实现)</b></summary>
| 功能 | 说明 | 配置 |
|------|------|------|
| **RAG 记忆注入** | 相似历史模式注入 Prompt | 默认启用 |
| **多指标相似度** | RSI、MACD、MA 趋势、波动率加权相似度 | 默认启用 |
| **反思验证** | 验证历史决策,更新 `was_correct` | `ENABLE_REFLECTION_WORKER=true` |
| **阈值自校准** | 定期校准 BUY/SELL 阈值 | `scripts/run_calibration.py``scripts/run_reflection_task.py` |
| **置信度校准** | 按置信度分桶统计准确率并调整 | `ENABLE_CONFIDENCE_CALIBRATION=true` |
| **市场状态感知** | 趋势/震荡市使用不同阈值(震荡市更保守) | 默认启用 |
| **多模型投票** | 2–3 模型投票降低单点偏差 | `ENABLE_AI_ENSEMBLE=true` + `AI_ENSEMBLE_MODELS=model1,model2` |
详见 `backend_api_python/env.example` 中的 AI analysis optimizations 部分。
</details>
</details>
---
@@ -466,10 +485,12 @@ QuantDinger/
| **AI / LLM** | `LLM_PROVIDER``OPENROUTER_API_KEY``OPENAI_API_KEY` |
| **OAuth** | `GOOGLE_CLIENT_ID``GITHUB_CLIENT_ID` |
| **安全** | `TURNSTILE_SITE_KEY``ENABLE_REGISTRATION` |
| **计费** | `BILLING_ENABLED``BILLING_COST_AI_ANALYSIS``BILLING_COST_AI_CODE_GEN` |
| **会员** | `MEMBERSHIP_MONTHLY_PRICE_USD``MEMBERSHIP_MONTHLY_CREDITS` |
| **USDT支付** | `USDT_PAY_ENABLED``USDT_TRC20_XPUB``TRONGRID_API_KEY` |
| **代理** | `PROXY_URL` |
| **工作器** | `ENABLE_PENDING_ORDER_WORKER``ENABLE_PORTFOLIO_MONITOR` |
| **工作器** | `ENABLE_PENDING_ORDER_WORKER``ENABLE_PORTFOLIO_MONITOR``ENABLE_REFLECTION_WORKER` |
| **AI调优** | `ENABLE_AI_ENSEMBLE``ENABLE_CONFIDENCE_CALIBRATION``AI_ENSEMBLE_MODELS` |
</details>