Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 65b911994c | |||
| 9deb58a38a | |||
| eb975b0133 | |||
| df28e6dfb8 | |||
| 4923b32bbe | |||
| 9f67de3677 |
@@ -23,6 +23,7 @@ manual_trading_hub/hub_ai_summaries.json
|
||||
manual_trading_hub/hub_ai_chat.json
|
||||
manual_trading_hub/hub_ai_fund_history.json
|
||||
manual_trading_hub/data/
|
||||
backups/
|
||||
|
||||
# 数据库与上传(运行时生成)
|
||||
**/*.sqlite
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
# AI 复盘与模型配置说明
|
||||
|
||||
四个 `crypto_monitor_*` 实例共用仓库根目录 **`ai_client.py`**(通过 `PYTHONPATH=..` 导入)。用于 **交易记录与复盘** 页的 AI 点评、短评建议,以及从复盘截图提取结构化 JSON。
|
||||
|
||||
---
|
||||
|
||||
## 一、二选一:`AI_PROVIDER`
|
||||
|
||||
| 值 | 说明 |
|
||||
|----|------|
|
||||
| **`openai`**(默认) | OpenAI 兼容 **Chat Completions** 接口 |
|
||||
| **`ollama`** | 本机 Ollama **`/api/generate`**(流式 NDJSON) |
|
||||
|
||||
在对应子目录 **`.env`** 中设置(各所 `.env.example` 已含模板):
|
||||
|
||||
```bash
|
||||
AI_PROVIDER=openai
|
||||
AI_TIMEOUT_SECONDS=120
|
||||
|
||||
# OpenAI 兼容网关(默认)
|
||||
OPENAI_API_BASE=https://op.bz121.com/v1
|
||||
OPENAI_API_KEY=你的密钥
|
||||
OPENAI_MODEL=gemma4:e4b
|
||||
|
||||
# 本机 Ollama(仅当 AI_PROVIDER=ollama)
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
```
|
||||
|
||||
### OpenAI 兼容网关
|
||||
|
||||
- **Base URL**:`https://op.bz121.com/v1`(请求路径为 `{base}/chat/completions`)。
|
||||
- **API Key**:在 [op.bz121.com](https://op.bz121.com/) 登录后,于 **`gateway.json`** 页面复制(与网关账号一致)。
|
||||
- **默认模型**:`gemma4:e4b`(可通过 `OPENAI_MODEL` 覆盖)。
|
||||
|
||||
### Ollama
|
||||
|
||||
- 需本机已安装并拉取对应模型;`AI_PROVIDER=ollama` 时使用 `OLLAMA_API` 与 `AI_MODEL`。
|
||||
- 四所 `app.py` **不再** 直连 Ollama;统一走 `ai_client.ai_generate` / `ai_review` / `ai_short_advice`。
|
||||
|
||||
---
|
||||
|
||||
## 二、部署注意
|
||||
|
||||
1. **PM2 / 手工启动**:`ecosystem.config.cjs` 中 **`PYTHONPATH=..`** 必须包含仓库根,否则无法 `from ai_client import ...`。
|
||||
2. 修改 `.env` 后重启对应实例,例如:`pm2 restart crypto_binance`(名称以你机器为准)。
|
||||
3. **`git pull`** 不会改 `.env`;若 `.env.example` 新增 AI 变量,请手动补进本机 `.env`。
|
||||
4. **勿** 将含真实 `OPENAI_API_KEY` 的 `.env` 提交 Git。
|
||||
|
||||
---
|
||||
|
||||
## 三、功能入口(网页)
|
||||
|
||||
登录后进入 **「交易记录与复盘」**:
|
||||
|
||||
- 单条记录 **AI 复盘** / **短评**(依赖上述配置)。
|
||||
- 上传复盘图后 **从图片提取** 字段(内部调用 `ai_generate`,与所选 provider 一致)。
|
||||
|
||||
若请求超时或返回错误,请检查:密钥是否有效、网关是否可达、`AI_TIMEOUT_SECONDS` 是否过短、Ollama 是否已启动(仅 ollama 模式)。
|
||||
|
||||
---
|
||||
|
||||
## 四、相关文件
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `ai_client.py` | 统一封装 OpenAI / Ollama |
|
||||
| `crypto_monitor_*/.env.example` | 各所环境变量模板 |
|
||||
| 各所《部署文档.md》§ AI 复盘 | 与本文一致的简表 |
|
||||
| 各所《使用说明.md》 | 运行前配置中的 AI 项 |
|
||||
# AI 复盘与模型配置说明
|
||||
|
||||
三个 `crypto_monitor_*` 实例共用仓库根目录 **`ai_client.py`**(通过 `PYTHONPATH=..` 导入)。用于 **交易记录与复盘** 页的 AI 点评、短评建议,以及从复盘截图提取结构化 JSON。
|
||||
|
||||
---
|
||||
|
||||
## 一、二选一:`AI_PROVIDER`
|
||||
|
||||
| 值 | 说明 |
|
||||
|----|------|
|
||||
| **`openai`**(默认) | OpenAI 兼容 **Chat Completions** 接口 |
|
||||
| **`ollama`** | 本机 Ollama **`/api/generate`**(流式 NDJSON) |
|
||||
|
||||
在对应子目录 **`.env`** 中设置(各所 `.env.example` 已含模板):
|
||||
|
||||
```bash
|
||||
AI_PROVIDER=openai
|
||||
AI_TIMEOUT_SECONDS=120
|
||||
|
||||
# OpenAI 兼容网关(默认)
|
||||
OPENAI_API_BASE=https://op.bz121.com/v1
|
||||
OPENAI_API_KEY=你的密钥
|
||||
OPENAI_MODEL=gemma4:e4b
|
||||
|
||||
# 本机 Ollama(仅当 AI_PROVIDER=ollama)
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
```
|
||||
|
||||
### OpenAI 兼容网关
|
||||
|
||||
- **Base URL**:`https://op.bz121.com/v1`(请求路径为 `{base}/chat/completions`)。
|
||||
- **API Key**:在 [op.bz121.com](https://op.bz121.com/) 登录后,于 **`gateway.json`** 页面复制(与网关账号一致)。
|
||||
- **默认模型**:`gemma4:e4b`(可通过 `OPENAI_MODEL` 覆盖)。
|
||||
|
||||
### Ollama
|
||||
|
||||
- 需本机已安装并拉取对应模型;`AI_PROVIDER=ollama` 时使用 `OLLAMA_API` 与 `AI_MODEL`。
|
||||
- 三所 `app.py` **不再** 直连 Ollama;统一走 `ai_client.ai_generate` / `ai_review` / `ai_short_advice`。
|
||||
|
||||
---
|
||||
|
||||
## 二、部署注意
|
||||
|
||||
1. **PM2 / 手工启动**:`ecosystem.config.cjs` 中 **`PYTHONPATH=..`** 必须包含仓库根,否则无法 `from ai_client import ...`。
|
||||
2. 修改 `.env` 后重启对应实例,例如:`pm2 restart crypto_binance`(名称以你机器为准)。
|
||||
3. **`git pull`** 不会改 `.env`;若 `.env.example` 新增 AI 变量,请手动补进本机 `.env`。
|
||||
4. **勿** 将含真实 `OPENAI_API_KEY` 的 `.env` 提交 Git。
|
||||
|
||||
---
|
||||
|
||||
## 三、功能入口(网页)
|
||||
|
||||
登录后进入 **「交易记录与复盘」**:
|
||||
|
||||
- 单条记录 **AI 复盘** / **短评**(依赖上述配置)。
|
||||
- 上传复盘图后 **从图片提取** 字段(内部调用 `ai_generate`,与所选 provider 一致)。
|
||||
|
||||
若请求超时或返回错误,请检查:密钥是否有效、网关是否可达、`AI_TIMEOUT_SECONDS` 是否过短、Ollama 是否已启动(仅 ollama 模式)。
|
||||
|
||||
---
|
||||
|
||||
## 四、相关文件
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `ai_client.py` | 统一封装 OpenAI / Ollama |
|
||||
| `crypto_monitor_*/.env.example` | 各所环境变量模板 |
|
||||
| 各所《部署文档.md》§ AI 复盘 | 与本文一致的简表 |
|
||||
| 各所《使用说明.md》 | 运行前配置中的 AI 项 |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 复盘交易系统(crypto_monitor)
|
||||
|
||||
多交易所 **USDT 永续** 的下单监控、**关键位**、**策略交易**、**止盈止损 / 移动保本** 与 **AI 复盘**,四所独立部署 + 可选 **中控** 聚合监控。
|
||||
多交易所 **USDT 永续** 的下单监控、**关键位**、**策略交易**、**止盈止损 / 移动保本** 与 **AI 复盘**,三所独立部署 + 可选 **中控** 聚合监控。
|
||||
|
||||
**远程仓库**:[https://git.bz121.com/dekun/crypto_monitor.git](https://git.bz121.com/dekun/crypto_monitor.git)
|
||||
|
||||
@@ -35,7 +35,7 @@ bash deploy/setup_env.sh --install-system-deps
|
||||
|------|------|------|
|
||||
| **关键位监控** | 箱体/收敛自动开仓、阻力支撑提醒、斐波限价;止盈止损方案与 **移动保本** 开关 | 各所 [关键位自动下单说明.md](./crypto_monitor_binance/关键位自动下单说明.md)(Gate/OKX 目录内同名);方案细则 **[关键位止盈止损与移动保本更新说明.md](./关键位止盈止损与移动保本更新说明.md)** |
|
||||
| **实盘下单 / 下单监控** | 首仓、以损定仓;监控内 **止盈 / 止损**、**移动保本**(步进 R、偏移%) | 各所 [使用说明.md](./crypto_monitor_binance/使用说明.md) · 顶栏「实盘下单」`/trade` |
|
||||
| **策略交易** | **趋势回调** + **顺势加仓**(`/strategy` 双栏) | **[策略交易说明.md](./策略交易说明.md)** · 趋势细则 [crypto_monitor_gate_bot/趋势回调策略说明.md](./crypto_monitor_gate_bot/趋势回调策略说明.md) |
|
||||
| **策略交易** | **趋势回调** + **顺势加仓**(`/strategy` 双栏) | **[策略交易说明.md](./策略交易说明.md)** · 趋势细则 [docs/trend-pullback-strategy.md](./docs/trend-pullback-strategy.md) |
|
||||
| **策略交易记录** | 已结束计划快照(最近 100 条)、筛选与展开详情 | [策略交易说明.md §五](./策略交易说明.md) · 顶栏 `/strategy/records` |
|
||||
| **交易复盘** | 平仓记录、错过机会、图表;**AI 点评** | **[AI复盘与模型配置说明.md](./AI复盘与模型配置说明.md)** · 顶栏「交易记录与复盘」`/records` |
|
||||
| **中控** | 多账户持仓/委托聚合、行情 K 线、紧急全平(**不在中控网页下单**) | [manual_trading_hub/使用说明.md](./manual_trading_hub/使用说明.md) · [部署文档.md](./manual_trading_hub/部署文档.md) |
|
||||
@@ -49,8 +49,7 @@ bash deploy/setup_env.sh --install-system-deps
|
||||
| 目录 | 交易所 / 角色 | 部署文档 |
|
||||
|------|----------------|----------|
|
||||
| `crypto_monitor_binance/` | Binance U 本位永续 | [部署文档.md](./crypto_monitor_binance/部署文档.md) |
|
||||
| `crypto_monitor_gate/` | Gate 主号 | [部署文档.md](./crypto_monitor_gate/部署文档.md) |
|
||||
| `crypto_monitor_gate_bot/` | Gate 机器人 / 趋势户 | [部署文档.md](./crypto_monitor_gate_bot/部署文档.md) |
|
||||
| `crypto_monitor_gate/` | Gate | [部署文档.md](./crypto_monitor_gate/部署文档.md) |
|
||||
| `crypto_monitor_okx/` | OKX 永续 | [部署文档.md](./crypto_monitor_okx/部署文档.md) |
|
||||
| `manual_trading_hub/` | 中控 + 子代理 | [部署文档.md](./manual_trading_hub/部署文档.md) |
|
||||
| `lib/` | **共用模块**(策略、关键位、交易、中控库、AI、静态与模板) | **[docs/lib-structure.md](./docs/lib-structure.md)** |
|
||||
@@ -64,7 +63,7 @@ bash deploy/setup_env.sh --install-system-deps
|
||||
## 技术要点
|
||||
|
||||
- **Python 3.10+**、Flask、ccxt、SQLite(`crypto.db`)
|
||||
- 四所 `.env` 前缀不同(`BINANCE_*` / `GATE_*` / `OKX_*`),**不可混用**
|
||||
- 三所 `.env` 前缀不同(`BINANCE_*` / `GATE_*` / `OKX_*`),**不可混用**
|
||||
- 实盘须 `LIVE_TRADING_ENABLED=true` 且理解 API 权限与 IP 白名单风险
|
||||
- 经 **SOCKS** 访问交易所时配置各所 `*_SOCKS_PROXY` 并安装 PySocks
|
||||
|
||||
@@ -72,7 +71,7 @@ bash deploy/setup_env.sh --install-system-deps
|
||||
|
||||
## 推荐阅读顺序
|
||||
|
||||
1. [docs/ubuntu-server.md](./docs/ubuntu-server.md) — 装 Python / Node / PM2,PM2 启动四所 + 中控
|
||||
1. [docs/ubuntu-server.md](./docs/ubuntu-server.md) — 装 Python / Node / PM2,PM2 启动三所 + 中控
|
||||
2. 各所 **`.env`**(从 `.env.example` 复制)
|
||||
3. 所用功能对应上表 **功能导航** 文档
|
||||
4. [备份与恢复.md](./备份与恢复.md) — 生产机备份习惯
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
{
|
||||
"name": "复盘系统中控",
|
||||
"short_name": "中控",
|
||||
"description": "四所交易监控与行情中控",
|
||||
"start_url": "/monitor",
|
||||
"display": "standalone",
|
||||
"background_color": "#0b0e18",
|
||||
"theme_color": "#0b0e18",
|
||||
"icons": [
|
||||
{
|
||||
"src": "__ICON_PREFIX__/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "__ICON_PREFIX__/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
{
|
||||
"name": "复盘系统中控",
|
||||
"short_name": "中控",
|
||||
"description": "三所交易监控与行情中控",
|
||||
"start_url": "/monitor",
|
||||
"display": "standalone",
|
||||
"background_color": "#0b0e18",
|
||||
"theme_color": "#0b0e18",
|
||||
"icons": [
|
||||
{
|
||||
"src": "__ICON_PREFIX__/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "__ICON_PREFIX__/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -130,6 +130,9 @@ from lib.key_monitor.trigger_entry_key_monitor_lib import (
|
||||
TRIGGER_ENTRY_VALIDITY_HOURS,
|
||||
check_trigger_entry_intent_limit,
|
||||
count_pending_trigger_entries,
|
||||
acquire_trigger_entry_exec_lock,
|
||||
is_trigger_entry_in_flight_row,
|
||||
release_trigger_entry_exec_lock,
|
||||
is_breakout_trigger_entry_key_monitor_type,
|
||||
is_trigger_entry_expired,
|
||||
is_trigger_entry_key_monitor_type,
|
||||
@@ -3469,6 +3472,40 @@ def ensure_markets_loaded(force=False):
|
||||
MARKETS_LOADED = True
|
||||
|
||||
|
||||
def _abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, planned_amount):
|
||||
from lib.trade.compensating_close_lib import run_compensating_close
|
||||
|
||||
def _close():
|
||||
ensure_markets_loaded()
|
||||
try:
|
||||
cancel_binance_futures_open_orders(exchange_symbol)
|
||||
except Exception:
|
||||
pass
|
||||
live = get_live_position_contracts(exchange_symbol, direction)
|
||||
amt = live if live is not None and live > 0 else _filled_amount_for_tpsl(order, planned_amount)
|
||||
if amt is None or float(amt) <= 0:
|
||||
return
|
||||
side = "sell" if direction == "long" else "buy"
|
||||
try:
|
||||
amount = float(exchange.amount_to_precision(exchange_symbol, float(amt)))
|
||||
except Exception:
|
||||
amount = float(amt)
|
||||
last_err = None
|
||||
for params in _binance_market_close_param_candidates(direction):
|
||||
try:
|
||||
exchange.create_order(exchange_symbol, "market", side, amount, None, params)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
if _is_binance_close_param_retryable(str(e)):
|
||||
continue
|
||||
raise
|
||||
if last_err:
|
||||
raise last_err
|
||||
|
||||
run_compensating_close(_close, log_prefix="binance_compensating_close")
|
||||
|
||||
|
||||
def place_exchange_order(exchange_symbol, direction, amount, leverage, stop_loss=None, take_profit=None):
|
||||
ensure_markets_loaded()
|
||||
mm = "cross" if BINANCE_MARGIN_MODE in ("cross", "cross_margin") else "isolated"
|
||||
@@ -3487,8 +3524,10 @@ def place_exchange_order(exchange_symbol, direction, amount, leverage, stop_loss
|
||||
_binance_place_tp_sl_orders(exchange_symbol, direction, pos_amt, stop_loss, take_profit)
|
||||
order["tpsl_attached"] = True
|
||||
except RuntimeError:
|
||||
_abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, amount)
|
||||
raise
|
||||
except Exception as e:
|
||||
_abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, amount)
|
||||
raise RuntimeError(f"交易所未接受条件止盈/止损委托,已拒绝开仓:{str(e)}") from e
|
||||
return order
|
||||
|
||||
@@ -4495,6 +4534,72 @@ def resolve_synced_flat_close(row, opened_at_str, opened_at_ms=None):
|
||||
)
|
||||
|
||||
|
||||
def _finalize_hub_flat_monitor_binance(conn, r, *, result, pnl_amount, closed_at, miss_reason):
|
||||
opened_at = get_opened_at_value(r)
|
||||
closed_at_dt = parse_dt_for_trading_day(closed_at) or app_now()
|
||||
hold_seconds = calc_hold_seconds(opened_at, closed_at_dt)
|
||||
session_date = r["session_date"] or get_trading_day(closed_at_dt)
|
||||
update_session_capital(conn, session_date, pnl_amount)
|
||||
insert_trade_record(
|
||||
conn,
|
||||
symbol=r["symbol"],
|
||||
monitor_type=trade_record_monitor_type(conn, r),
|
||||
trend_plan_id=trend_plan_id_from_monitor_row(r),
|
||||
key_signal_type=order_row_key_signal_type(r),
|
||||
direction=r["direction"],
|
||||
trigger_price=r["trigger_price"],
|
||||
stop_loss=r["stop_loss"],
|
||||
initial_stop_loss=r["initial_stop_loss"] or r["stop_loss"],
|
||||
take_profit=r["take_profit"],
|
||||
margin_capital=r["margin_capital"],
|
||||
leverage=r["leverage"],
|
||||
pnl_amount=pnl_amount,
|
||||
hold_seconds=hold_seconds,
|
||||
trade_style=r["trade_style"],
|
||||
risk_amount=r["risk_amount"],
|
||||
planned_rr=calc_rr_ratio(
|
||||
r["direction"],
|
||||
r["trigger_price"],
|
||||
r["initial_stop_loss"] or r["stop_loss"],
|
||||
r["take_profit"],
|
||||
),
|
||||
actual_rr=calc_actual_rr(pnl_amount, r["risk_amount"]),
|
||||
result=result,
|
||||
miss_reason=handoff_trade_miss_reason(miss_reason, r),
|
||||
opened_at=opened_at,
|
||||
closed_at=closed_at,
|
||||
)
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (r["id"],))
|
||||
clear_key_sizing_snapshot_if_flat(conn, r["session_date"] or get_trading_day())
|
||||
|
||||
|
||||
def reconcile_hub_external_close(conn, symbol, direction):
|
||||
from lib.hub.hub_reconcile_flat_lib import reconcile_hub_external_close_impl
|
||||
from lib.hub.hub_symbol_lib import symbols_match
|
||||
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
|
||||
return reconcile_hub_external_close_impl(
|
||||
conn,
|
||||
symbol,
|
||||
direction,
|
||||
exchange_configured=exchange_private_api_configured,
|
||||
not_configured_msg="未配置 BINANCE_API_KEY / BINANCE_API_SECRET",
|
||||
symbols_match=symbols_match,
|
||||
get_opened_at_value=get_opened_at_value,
|
||||
resolve_monitor_exchange_symbol=resolve_monitor_exchange_symbol,
|
||||
get_live_position_contracts=get_live_position_contracts,
|
||||
cancel_conditional_orders=cancel_binance_futures_open_orders,
|
||||
resolve_synced_flat_close=resolve_synced_flat_close,
|
||||
finalize_stopped_monitor=_finalize_hub_flat_monitor_binance,
|
||||
sync_trade_records=None,
|
||||
reconcile_flat_streak=_RECONCILE_FLAT_STREAK,
|
||||
to_ms_with_fallback=_to_ms_with_fallback,
|
||||
prefer_manual_resolve=False,
|
||||
order_row_monitor_type=order_row_monitor_type,
|
||||
)
|
||||
|
||||
|
||||
def reconcile_external_closes(conn, days=None):
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
if not exchange_private_api_configured():
|
||||
@@ -5777,7 +5882,7 @@ def _market_open_for_trigger_entry(
|
||||
|
||||
|
||||
def _execute_trigger_entry_cross(conn, row):
|
||||
"""标记价触达计划入场:先删监控行防重复触发,再市价开仓。"""
|
||||
"""标记价触达计划入场:加锁防重复触发,成交成功后再删监控行。"""
|
||||
symbol = row["symbol"]
|
||||
direction = (row["direction"] or "long").lower()
|
||||
ex_sym = normalize_exchange_symbol(symbol)
|
||||
@@ -5788,7 +5893,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
tc_en, tc_h, _ = time_close_settings_from_row(row)
|
||||
|
||||
kid = int(row["id"])
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
if not acquire_trigger_entry_exec_lock(conn, kid):
|
||||
return False, "触价开仓进行中"
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
@@ -5806,6 +5912,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
time_close_hours=tc_h,
|
||||
)
|
||||
except Exception as e:
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = friendly_exchange_error(e)
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓异常\n"
|
||||
@@ -5817,6 +5925,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
return False, fail_msg
|
||||
|
||||
if ok and det:
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
conn.commit()
|
||||
rr_txt = format_wechat_scalar_2dp(det.get("planned_rr_fill")) if det.get("planned_rr_fill") is not None else "-"
|
||||
msg = (
|
||||
f"# ✅ {symbol} 触价开仓成交\n"
|
||||
@@ -5833,6 +5943,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
send_wechat_msg(msg)
|
||||
insert_key_monitor_history(conn, row, 0, msg, TRIGGER_ENTRY_CLOSE_FILLED)
|
||||
return True, None
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = err or "触价触发后开仓失败"
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓失败\n"
|
||||
@@ -5860,6 +5972,8 @@ def check_trigger_entry_key_monitors():
|
||||
sl = float(_sqlite_row_val(r, "fib_stop_loss") or 0)
|
||||
tp = float(_sqlite_row_val(r, "fib_take_profit") or 0)
|
||||
kid = int(r["id"])
|
||||
if is_trigger_entry_in_flight_row(r):
|
||||
continue
|
||||
if entry <= 0 or sl <= 0 or tp <= 0:
|
||||
_finalize_key_monitor_one_shot(conn, r, "触价计划价位无效", "fib_plan_invalid")
|
||||
continue
|
||||
@@ -6388,7 +6502,7 @@ def check_order_monitors():
|
||||
new_sl = round_price_to_exchange(ex_sym, new_sl)
|
||||
tp_ex = float(take_profit or 0)
|
||||
ok_live, _live_reason = ensure_exchange_live_ready()
|
||||
synced_ex = not ok_live
|
||||
synced_ex = False
|
||||
if ok_live and tp_ex > 0:
|
||||
try:
|
||||
replace_active_monitor_tpsl_on_exchange(r, new_sl, tp_ex)
|
||||
@@ -6818,8 +6932,8 @@ def background_task():
|
||||
from lib.strategy.strategy_trend_register import check_trend_pullback_plans
|
||||
|
||||
check_trend_pullback_plans(cfg)
|
||||
except:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[monitor_loop] {e}", flush=True)
|
||||
time.sleep(MONITOR_POLL_SECONDS)
|
||||
|
||||
|
||||
@@ -9667,6 +9781,7 @@ try:
|
||||
ohlcv_fn=_hub_fetch_ohlcv,
|
||||
volume_rank_fn=_hub_fetch_volume_rank,
|
||||
market_fn=_hub_fetch_market,
|
||||
reconcile_hub_flat_fn=reconcile_hub_external_close,
|
||||
risk_status_fn=hub_account_risk_status,
|
||||
user_close_fn=hub_user_initiated_close,
|
||||
render_main_page_fn=render_main_page,
|
||||
|
||||
@@ -140,7 +140,7 @@
|
||||
## 升级步骤
|
||||
|
||||
1. `git pull` 后对比 `.env.example`,把新增变量合并进本地 `.env`。
|
||||
2. 在 VPS 上为 Binance / Gate / Gate Bot **各执行一次** `bash scripts/install_backup_cron.sh`(若尚未安装)。
|
||||
2. 在 VPS 上为 Binance / Gate / **各执行一次** `bash scripts/install_backup_cron.sh`(若尚未安装)。
|
||||
3. 重启 Binance 实例(如 `pm2 restart crypto_binance`);SQLite 会自动 `ALTER` 缺列(斐波、交易所盈亏、`entry_reason` 等)。
|
||||
4. 浏览器强刷(Ctrl+F5)避免旧版 `index.html` 缓存。
|
||||
5. 打开任意页确认顶栏出现 **「列表筛选(UTC)」**;`/stats` 可见分品类统计与「北京 8:00 切日」说明。
|
||||
|
||||
@@ -149,7 +149,7 @@ cp .env .env.backup.$(date +%Y%m%d)
|
||||
|
||||
### 5.3 AI 复盘与模型(可选)
|
||||
|
||||
四所共用仓库根目录 **`ai_client.py`**(PM2 的 **`PYTHONPATH=..`** 须包含仓库根)。在 `.env` 中配置 **`AI_PROVIDER`**:
|
||||
三所共用仓库根目录 **`ai_client.py`**(PM2 的 **`PYTHONPATH=..`** 须包含仓库根)。在 `.env` 中配置 **`AI_PROVIDER`**:
|
||||
|
||||
| 模式 | 主要变量 |
|
||||
|------|----------|
|
||||
@@ -191,10 +191,10 @@ cd /opt/crypto_monitor/crypto_monitor_gate
|
||||
bash scripts/install_backup_cron.sh
|
||||
```
|
||||
|
||||
Gate Bot 实例(趋势回调等):
|
||||
实例(趋势回调等):
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate
|
||||
bash scripts/install_backup_cron.sh
|
||||
```
|
||||
|
||||
|
||||
@@ -131,6 +131,9 @@ from lib.key_monitor.trigger_entry_key_monitor_lib import (
|
||||
TRIGGER_ENTRY_VALIDITY_HOURS,
|
||||
check_trigger_entry_intent_limit,
|
||||
count_pending_trigger_entries,
|
||||
acquire_trigger_entry_exec_lock,
|
||||
is_trigger_entry_in_flight_row,
|
||||
release_trigger_entry_exec_lock,
|
||||
is_breakout_trigger_entry_key_monitor_type,
|
||||
is_trigger_entry_expired,
|
||||
is_trigger_entry_key_monitor_type,
|
||||
@@ -394,8 +397,10 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
||||
os.makedirs(ORDER_CHART_DIR, exist_ok=True)
|
||||
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
|
||||
|
||||
from lib.exchange.gate_ccxt_lib import gate_ccxt_class
|
||||
|
||||
# Gate.io USDT 永续(swap)
|
||||
exchange = ccxt.gateio({
|
||||
exchange = gate_ccxt_class()({
|
||||
"enableRateLimit": True,
|
||||
"options": {
|
||||
"defaultType": "swap",
|
||||
@@ -3133,7 +3138,7 @@ def _gate_place_tp_sl_orders_position_price_orders(exchange_symbol, direction, s
|
||||
try:
|
||||
exchange.privateFuturesPostSettlePriceOrders(_payload(tp_s, tp_rule))
|
||||
except Exception:
|
||||
cancel_gate_swap_trigger_orders(exchange_symbol)
|
||||
# 保留已挂止损,仅放弃本次 TP;上层可补偿平仓或重试
|
||||
raise
|
||||
return
|
||||
except Exception as e:
|
||||
@@ -3250,6 +3255,27 @@ def ensure_markets_loaded(force=False):
|
||||
MARKETS_LOADED = True
|
||||
|
||||
|
||||
def _abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, planned_amount):
|
||||
"""TP/SL 挂失败时市价平掉刚开的仓并撤残留条件单。"""
|
||||
from lib.trade.compensating_close_lib import run_compensating_close
|
||||
|
||||
def _close():
|
||||
ensure_markets_loaded()
|
||||
try:
|
||||
cancel_gate_swap_trigger_orders(exchange_symbol)
|
||||
except Exception:
|
||||
pass
|
||||
live = get_live_position_contracts(exchange_symbol, direction)
|
||||
amt = live if live is not None and live > 0 else _gate_contracts_amount_for_tpsl(order, planned_amount)
|
||||
if amt is None or float(amt) <= 0:
|
||||
return
|
||||
side = "sell" if direction == "long" else "buy"
|
||||
params = build_gate_order_params(direction, reduce_only=True)
|
||||
exchange.create_order(exchange_symbol, "market", side, float(amt), None, params)
|
||||
|
||||
run_compensating_close(_close, log_prefix="gate_compensating_close")
|
||||
|
||||
|
||||
def place_exchange_order(exchange_symbol, direction, amount, leverage, stop_loss=None, take_profit=None):
|
||||
ensure_markets_loaded()
|
||||
exchange.set_leverage(leverage, exchange_symbol)
|
||||
@@ -3263,22 +3289,48 @@ def place_exchange_order(exchange_symbol, direction, amount, leverage, stop_loss
|
||||
_gate_place_tp_sl_orders(exchange_symbol, direction, contracts_amt, stop_loss, take_profit)
|
||||
order["tpsl_attached"] = True
|
||||
except RuntimeError:
|
||||
_abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, amount)
|
||||
raise
|
||||
except Exception as e:
|
||||
_abort_market_open_after_tpsl_failure(exchange_symbol, direction, order, amount)
|
||||
raise RuntimeError(f"交易所未接受条件止盈/止损委托,已拒绝开仓:{str(e)}") from e
|
||||
return order
|
||||
|
||||
|
||||
def close_exchange_order(order_row):
|
||||
"""
|
||||
市价全平。数量优先取交易所当前持仓张数,避免仅用入库 order_amount 导致平不干净。
|
||||
"""
|
||||
ensure_markets_loaded()
|
||||
exchange_symbol = order_row["exchange_symbol"] or normalize_exchange_symbol(order_row["symbol"])
|
||||
amount = float(order_row["order_amount"] or 0)
|
||||
if amount <= 0:
|
||||
raise ValueError("平仓失败:缺少有效下单数量")
|
||||
direction = order_row["direction"]
|
||||
db_amt = float(order_row["order_amount"] or 0)
|
||||
side = "sell" if direction == "long" else "buy"
|
||||
params = build_gate_order_params(direction, reduce_only=True)
|
||||
return exchange.create_order(exchange_symbol, "market", side, amount, None, params)
|
||||
last_resp = None
|
||||
for _ in range(3):
|
||||
live = get_live_position_contracts(exchange_symbol, direction)
|
||||
if live is not None and live > 0:
|
||||
raw_amt = live
|
||||
else:
|
||||
raw_amt = db_amt
|
||||
if raw_amt <= 0:
|
||||
if last_resp is not None:
|
||||
return last_resp
|
||||
raise ValueError("平仓失败:缺少有效下单数量")
|
||||
try:
|
||||
amount = float(exchange.amount_to_precision(exchange_symbol, raw_amt))
|
||||
except Exception:
|
||||
amount = float(raw_amt)
|
||||
if amount <= 0:
|
||||
if last_resp is not None:
|
||||
return last_resp
|
||||
raise ValueError("平仓失败:数量经精度舍入后为 0")
|
||||
params = build_gate_order_params(direction, reduce_only=True)
|
||||
last_resp = exchange.create_order(exchange_symbol, "market", side, amount, None, params)
|
||||
live_after = get_live_position_contracts(exchange_symbol, direction)
|
||||
if live_after is None or live_after <= 0:
|
||||
return last_resp
|
||||
return last_resp
|
||||
|
||||
|
||||
def _gate_swap_trigger_order_params():
|
||||
@@ -4111,89 +4163,71 @@ def resolve_synced_flat_close(row, opened_at_str, opened_at_ms=None, *, prefer_m
|
||||
)
|
||||
|
||||
|
||||
def _finalize_hub_flat_monitor(conn, r, *, result, pnl_amount, closed_at, miss_reason):
|
||||
opened_at = get_opened_at_value(r)
|
||||
closed_at_dt = parse_dt_for_trading_day(closed_at) or app_now()
|
||||
hold_seconds = calc_hold_seconds(opened_at, closed_at_dt)
|
||||
session_date = r["session_date"] or get_trading_day(closed_at_dt)
|
||||
update_session_capital(conn, session_date, pnl_amount)
|
||||
insert_trade_record(
|
||||
conn,
|
||||
symbol=r["symbol"],
|
||||
monitor_type=trade_record_monitor_type(conn, r),
|
||||
trend_plan_id=trend_plan_id_from_monitor_row(r),
|
||||
key_signal_type=order_row_key_signal_type(r),
|
||||
direction=r["direction"],
|
||||
trigger_price=r["trigger_price"],
|
||||
stop_loss=r["stop_loss"],
|
||||
initial_stop_loss=r["initial_stop_loss"] or r["stop_loss"],
|
||||
take_profit=r["take_profit"],
|
||||
margin_capital=margin_capital_for_trade_record(r),
|
||||
leverage=r["leverage"],
|
||||
pnl_amount=pnl_amount,
|
||||
hold_seconds=hold_seconds,
|
||||
trade_style=r["trade_style"],
|
||||
risk_amount=r["risk_amount"],
|
||||
planned_rr=calc_rr_ratio(
|
||||
r["direction"],
|
||||
r["trigger_price"],
|
||||
r["initial_stop_loss"] or r["stop_loss"],
|
||||
r["take_profit"],
|
||||
),
|
||||
actual_rr=calc_actual_rr(pnl_amount, r["risk_amount"]),
|
||||
result=result,
|
||||
miss_reason=handoff_trade_miss_reason(miss_reason, r),
|
||||
opened_at=opened_at,
|
||||
closed_at=closed_at,
|
||||
)
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (r["id"],))
|
||||
clear_key_sizing_snapshot_if_flat(conn, r["session_date"] or get_trading_day())
|
||||
|
||||
|
||||
def reconcile_hub_external_close(conn, symbol, direction):
|
||||
"""中控市价全平后:立即同步匹配 order_monitor,并读 Gate 平仓历史。"""
|
||||
if not exchange_private_api_configured():
|
||||
return {"ok": False, "msg": "未配置 GATE_API_KEY / GATE_API_SECRET", "synced": 0}
|
||||
from lib.exchange.gate_position_history_lib import unified_symbol_for_match
|
||||
from lib.hub.hub_reconcile_flat_lib import reconcile_hub_external_close_impl
|
||||
from lib.hub.hub_symbol_lib import symbols_match
|
||||
|
||||
sym_u = unified_symbol_for_match(symbol)
|
||||
dir_l = (direction or "").strip().lower()
|
||||
if dir_l not in ("long", "short"):
|
||||
return {"ok": False, "msg": "side 须为 long 或 short", "synced": 0}
|
||||
synced = 0
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM order_monitors WHERE status IN ('active', 'error')"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
if unified_symbol_for_match(r["symbol"]) != sym_u:
|
||||
continue
|
||||
if (r["direction"] or "").strip().lower() != dir_l:
|
||||
continue
|
||||
oid = int(r["id"])
|
||||
if r["status"] == "error":
|
||||
opened_at_chk = get_opened_at_value(r)
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM trade_records WHERE symbol=? AND opened_at=? AND monitor_type=? LIMIT 1",
|
||||
(r["symbol"], opened_at_chk, order_row_monitor_type(r)),
|
||||
).fetchone()
|
||||
if existing:
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (oid,))
|
||||
synced += 1
|
||||
continue
|
||||
exchange_symbol = resolve_monitor_exchange_symbol(r)
|
||||
live_contracts = get_live_position_contracts(exchange_symbol, r["direction"])
|
||||
if live_contracts is None:
|
||||
continue
|
||||
if live_contracts > 0:
|
||||
time.sleep(0.6)
|
||||
live_contracts = get_live_position_contracts(exchange_symbol, r["direction"])
|
||||
if live_contracts is None or live_contracts > 0:
|
||||
continue
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
_RECONCILE_FLAT_STREAK.pop(oid, None)
|
||||
cancel_gate_swap_trigger_orders(exchange_symbol)
|
||||
opened_at = get_opened_at_value(r)
|
||||
opened_at_ms = _to_ms_with_fallback(r["opened_at_ms"] if "opened_at_ms" in r.keys() else None, opened_at)
|
||||
result, pnl_amount, closed_at, miss_reason = resolve_synced_flat_close(
|
||||
r, opened_at, opened_at_ms=opened_at_ms, prefer_manual=True
|
||||
)
|
||||
closed_at_dt = parse_dt_for_trading_day(closed_at) or app_now()
|
||||
hold_seconds = calc_hold_seconds(opened_at, closed_at_dt)
|
||||
session_date = r["session_date"] or get_trading_day(closed_at_dt)
|
||||
update_session_capital(conn, session_date, pnl_amount)
|
||||
insert_trade_record(
|
||||
conn,
|
||||
symbol=r["symbol"],
|
||||
monitor_type=trade_record_monitor_type(conn, r),
|
||||
trend_plan_id=trend_plan_id_from_monitor_row(r),
|
||||
key_signal_type=order_row_key_signal_type(r),
|
||||
direction=r["direction"],
|
||||
trigger_price=r["trigger_price"],
|
||||
stop_loss=r["stop_loss"],
|
||||
initial_stop_loss=r["initial_stop_loss"] or r["stop_loss"],
|
||||
take_profit=r["take_profit"],
|
||||
margin_capital=margin_capital_for_trade_record(r),
|
||||
leverage=r["leverage"],
|
||||
pnl_amount=pnl_amount,
|
||||
hold_seconds=hold_seconds,
|
||||
trade_style=r["trade_style"],
|
||||
risk_amount=r["risk_amount"],
|
||||
planned_rr=calc_rr_ratio(r["direction"], r["trigger_price"], r["initial_stop_loss"] or r["stop_loss"], r["take_profit"]),
|
||||
actual_rr=calc_actual_rr(pnl_amount, r["risk_amount"]),
|
||||
result=result,
|
||||
miss_reason=handoff_trade_miss_reason(miss_reason, r),
|
||||
opened_at=opened_at,
|
||||
closed_at=closed_at,
|
||||
)
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (r["id"],))
|
||||
clear_key_sizing_snapshot_if_flat(conn, r["session_date"] or get_trading_day())
|
||||
synced += 1
|
||||
try:
|
||||
sync_trade_records_from_exchange(conn, force=True)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "synced": synced}
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
|
||||
return reconcile_hub_external_close_impl(
|
||||
conn,
|
||||
symbol,
|
||||
direction,
|
||||
exchange_configured=exchange_private_api_configured,
|
||||
not_configured_msg="未配置 GATE_API_KEY / GATE_API_SECRET",
|
||||
symbols_match=symbols_match,
|
||||
get_opened_at_value=get_opened_at_value,
|
||||
resolve_monitor_exchange_symbol=resolve_monitor_exchange_symbol,
|
||||
get_live_position_contracts=get_live_position_contracts,
|
||||
cancel_conditional_orders=cancel_gate_swap_trigger_orders,
|
||||
resolve_synced_flat_close=resolve_synced_flat_close,
|
||||
finalize_stopped_monitor=_finalize_hub_flat_monitor,
|
||||
sync_trade_records=sync_trade_records_from_exchange,
|
||||
reconcile_flat_streak=_RECONCILE_FLAT_STREAK,
|
||||
to_ms_with_fallback=_to_ms_with_fallback,
|
||||
prefer_manual_resolve=True,
|
||||
order_row_monitor_type=order_row_monitor_type,
|
||||
)
|
||||
|
||||
|
||||
def reconcile_external_closes(conn, days=None):
|
||||
@@ -5489,7 +5523,7 @@ def _market_open_for_trigger_entry(
|
||||
|
||||
|
||||
def _execute_trigger_entry_cross(conn, row):
|
||||
"""标记价触达计划入场:先删监控行防重复触发,再市价开仓。"""
|
||||
"""标记价触达计划入场:加锁防重复触发,成交成功后再删监控行。"""
|
||||
symbol = row["symbol"]
|
||||
direction = (row["direction"] or "long").lower()
|
||||
ex_sym = normalize_exchange_symbol(symbol)
|
||||
@@ -5500,7 +5534,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
tc_en, tc_h, _ = time_close_settings_from_row(row)
|
||||
|
||||
kid = int(row["id"])
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
if not acquire_trigger_entry_exec_lock(conn, kid):
|
||||
return False, "触价开仓进行中"
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
@@ -5518,6 +5553,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
time_close_hours=tc_h,
|
||||
)
|
||||
except Exception as e:
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = friendly_exchange_error(e)
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓异常\n"
|
||||
@@ -5529,6 +5566,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
return False, fail_msg
|
||||
|
||||
if ok and det:
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
conn.commit()
|
||||
rr_txt = format_wechat_scalar_2dp(det.get("planned_rr_fill")) if det.get("planned_rr_fill") is not None else "-"
|
||||
msg = (
|
||||
f"# ✅ {symbol} 触价开仓成交\n"
|
||||
@@ -5545,6 +5584,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
send_wechat_msg(msg)
|
||||
insert_key_monitor_history(conn, row, 0, msg, TRIGGER_ENTRY_CLOSE_FILLED)
|
||||
return True, None
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = err or "触价触发后开仓失败"
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓失败\n"
|
||||
@@ -5572,6 +5613,8 @@ def check_trigger_entry_key_monitors():
|
||||
sl = float(_sqlite_row_val(r, "fib_stop_loss") or 0)
|
||||
tp = float(_sqlite_row_val(r, "fib_take_profit") or 0)
|
||||
kid = int(r["id"])
|
||||
if is_trigger_entry_in_flight_row(r):
|
||||
continue
|
||||
if entry <= 0 or sl <= 0 or tp <= 0:
|
||||
_finalize_key_monitor_one_shot(conn, r, "触价计划价位无效", "fib_plan_invalid")
|
||||
continue
|
||||
@@ -6115,7 +6158,7 @@ def check_order_monitors():
|
||||
new_sl = round_price_to_exchange(ex_sym, new_sl)
|
||||
tp_ex = float(take_profit or 0)
|
||||
ok_live, _live_reason = ensure_exchange_live_ready()
|
||||
synced_ex = not ok_live
|
||||
synced_ex = False
|
||||
if ok_live and tp_ex > 0:
|
||||
try:
|
||||
replace_active_monitor_tpsl_on_exchange(r, new_sl, tp_ex)
|
||||
@@ -6524,8 +6567,8 @@ def background_task():
|
||||
from lib.strategy.strategy_trend_register import check_trend_pullback_plans
|
||||
|
||||
check_trend_pullback_plans(cfg)
|
||||
except:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[monitor_loop] {e}", flush=True)
|
||||
time.sleep(MONITOR_POLL_SECONDS)
|
||||
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
## 升级步骤
|
||||
|
||||
1. `git pull` 后对比 `.env.example`,把新增变量合并进本地 `.env`。
|
||||
2. 在 VPS 上为 Binance / Gate / Gate Bot **各执行一次** `bash scripts/install_backup_cron.sh`(若尚未安装)。
|
||||
2. 在 VPS 上为 Binance / Gate / **各执行一次** `bash scripts/install_backup_cron.sh`(若尚未安装)。
|
||||
3. 重启 Gate 实例服务(如 `pm2 restart crypto_gate`);首次启动会自动 `ALTER TABLE` 缺列(斐波、交易所盈亏、`entry_reason` 等)。
|
||||
4. 浏览器强刷(Ctrl+F5)避免旧版 `index.html` 缓存。
|
||||
5. 打开任意页确认顶栏出现 **「列表筛选(UTC)」**;`/stats` 可见分品类统计与「北京 8:00 切日」说明。
|
||||
|
||||
@@ -157,7 +157,7 @@ bash scripts/backup_data.sh # 试跑
|
||||
|
||||
备份目录:`/root/backups/crypto_monitor_gate/YYYY-MM-DD/`。详见 Binance 项目 `部署文档.md` 第 5.4 节(恢复步骤、可选 `.env` 变量相同)。
|
||||
|
||||
若还部署了 **`crypto_monitor_gate_bot`**,请在该目录同样执行 `bash scripts/install_backup_cron.sh`。
|
||||
若还部署了 **`crypto_monitor_okx`**,请在该目录同样执行 `bash scripts/install_backup_cron.sh`。
|
||||
|
||||
### 5.5 必填项检查(Gate + 代理)
|
||||
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
# =============================================================================
|
||||
# 环境配置模板(可提交 Git)。程序运行时只读取同目录下的 .env。
|
||||
#
|
||||
# 首次部署 / 新机:
|
||||
# cp .env.example .env
|
||||
# nano .env # 填入真实密钥、端口、代理等
|
||||
#
|
||||
# 升级代码(git pull)前建议备份(.env 不在 Git 中,pull 不会覆盖):
|
||||
# cp .env .env.backup.$(date +%Y%m%d)
|
||||
#
|
||||
# 从备份恢复:
|
||||
# cp .env.backup.YYYYMMDD .env
|
||||
# =============================================================================
|
||||
|
||||
APP_ENV=production
|
||||
# 服务监听地址(云服务器通常用 0.0.0.0)
|
||||
APP_HOST=0.0.0.0
|
||||
# 服务端口
|
||||
APP_PORT=5002
|
||||
# 是否开启调试模式(生产建议 false)
|
||||
APP_DEBUG=false
|
||||
|
||||
# 登录账号
|
||||
APP_USERNAME=admin
|
||||
# 登录密码(请改成你自己的强密码)
|
||||
APP_PASSWORD=admin123
|
||||
# 是否关闭登录校验(局域网可设 true;公网务必 false)
|
||||
APP_AUTH_DISABLED=true
|
||||
# --- 多账户交易中控 manual_trading_hub ---
|
||||
# 中控请求本实例 /api/hub/* 时携带请求头 X-Hub-Token,须与中控启动环境变量 HUB_BRIDGE_TOKEN 一致
|
||||
# 未设置且 APP_AUTH_DISABLED=false 时,仅网页登录后可访问;本机联调可保持 APP_AUTH_DISABLED=true
|
||||
# HUB_BRIDGE_TOKEN=your-long-random-token
|
||||
# Flask 会话密钥(必须替换为长随机字符串)
|
||||
FLASK_SECRET_KEY=CHANGE_TO_LONG_RANDOM_SECRET
|
||||
|
||||
# 企业微信机器人 Webhook(用于行情/风控推送)
|
||||
WECHAT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=REPLACE_WITH_REAL_KEY
|
||||
|
||||
# 数据库文件路径(相对路径会自动按项目目录解析)
|
||||
DB_PATH=crypto.db
|
||||
# 交易截图上传目录
|
||||
UPLOAD_DIR=static/images
|
||||
|
||||
# 自动备份(scripts/backup_data.sh + cron,可选;默认即可)
|
||||
# BACKUP_ROOT=/root/backups
|
||||
# BACKUP_RETENTION_DAYS=30
|
||||
# BACKUP_INSTANCE=crypto_monitor_gate_bot
|
||||
|
||||
# 已废弃:资金账户仅显示交易所 funding 余额,不再读取此变量
|
||||
# TOTAL_CAPITAL=100
|
||||
# 计仓:risk=以损定仓(默认);full_margin=合约可用×FULL_MARGIN_BUFFER_RATIO 全仓杠杆(须无仓后重启)
|
||||
POSITION_SIZING_MODE=risk
|
||||
# 每天起始基数(U)
|
||||
DAILY_START_CAPITAL=30
|
||||
# 日内回撤后基数(U)
|
||||
DAILY_LOSS_CAPITAL=20
|
||||
# 日内盈利后基数(U)
|
||||
DAILY_PROFIT_CAPITAL=50
|
||||
# BTC 默认杠杆倍数
|
||||
BTC_LEVERAGE=10
|
||||
# 山寨币默认杠杆倍数
|
||||
ALT_LEVERAGE=5
|
||||
# 交易日重置小时(北京时间)
|
||||
TRADING_DAY_RESET_HOUR=8
|
||||
# 整点前禁止新开仓:true=启用(默认),false=关闭(仍可保留 8 点作为交易日划分)
|
||||
TRADING_DAY_RESET_OPEN_GUARD_ENABLED=true
|
||||
|
||||
# 是否开启 Gate 实盘下单(false=只做本地流程,true=真实下单)
|
||||
LIVE_TRADING_ENABLED=true
|
||||
# Gate API Key(实盘)
|
||||
GATE_API_KEY=REPLACE_WITH_GATE_API_KEY
|
||||
# Gate API Secret(实盘)
|
||||
GATE_API_SECRET=REPLACE_WITH_GATE_API_SECRET
|
||||
# 保证金模式:cross=全仓,isolated=逐仓
|
||||
GATE_TD_MODE=cross
|
||||
# 持仓筛选:hedge=双向持仓下按多空腿过滤;其它值(如 single)不按腿过滤
|
||||
GATE_POS_MODE=hedge
|
||||
# 永续止盈止损:是否优先用官方仓位类触发单(POST price_orders,close-*-position);false=仅用旧版两张 ccxt 条件单
|
||||
GATE_TPSL_USE_POSITION_ORDER=true
|
||||
# 触发单超时(秒),默认 604800=7 天;设为 0 或负数则不向 API 传 expiration
|
||||
GATE_TPSL_TRIGGER_EXPIRATION=604800
|
||||
# 触发参考价:0=最新成交 1=标记价 2=指数价(非法值按 0)
|
||||
GATE_TPSL_PRICE_TYPE=0
|
||||
# 仓位类 TP/SL 相对现价的最小间距(%),避免 Gate 1026「触发价须高于/低于现价」
|
||||
GATE_TPSL_LAST_PRICE_GAP_PCT=0.05
|
||||
# 页面与浏览器标签展示的交易所名称(多环境区分时可改成例如 Gate·模拟)
|
||||
# EXCHANGE_DISPLAY_NAME=Gate.io
|
||||
|
||||
# =============================================================================
|
||||
# 关键位门控(页面「关键位监控」规则条与 _key_hard_checks 共用)
|
||||
# =============================================================================
|
||||
# 【周期】门控 K 线周期,如 5m、15m
|
||||
KLINE_TIMEFRAME=5m
|
||||
# 【确认K】闭合 K 序列中的棒偏移:突破棒默认 -2,确认棒默认 -1
|
||||
KEY_CONFIRM_BREAKOUT_BAR=-2
|
||||
KEY_CONFIRM_BAR=-1
|
||||
# 【量能】突破棒成交量 > 前 N 根均量 × 倍数
|
||||
KEY_VOLUME_MA_BARS=20
|
||||
KEY_VOLUME_RATIO_MIN=1.3
|
||||
# 【突破K实体幅度】占开盘价百分比区间
|
||||
# 【箱体/收敛】突破K收盘越过关键位下限%;无上限(过猛由计划RR过滤)
|
||||
KEY_BREAKOUT_AMP_MIN_PCT=0.03
|
||||
KEY_BREAKOUT_AMP_MAX_PCT=0.5
|
||||
# 【阻力/支撑】突破后微信提醒
|
||||
KEY_ALERT_MAX_TIMES=3
|
||||
KEY_ALERT_INTERVAL_MINUTES=5
|
||||
# 【日成交量排名】品种须在该排名前 N 名
|
||||
KEY_DAILY_VOLUME_RANK_MAX=30
|
||||
# 【关键位自动开仓盈亏比】严格大于该值才市价开仓
|
||||
KEY_AUTO_MIN_PLANNED_RR=1.5
|
||||
# 止损:突破 K 极值向外缓冲的百分比(默认 0.5 即 0.5%)
|
||||
KEY_STOP_OUTSIDE_BREAKOUT_PCT=0.5
|
||||
# 趋势单方案:止损在突破 K 极值外侧的百分比(默认 1 即 1%)
|
||||
KEY_TREND_STOP_OUTSIDE_PCT=1
|
||||
KEY_ALERT_MAX_TIMES=3
|
||||
KEY_ALERT_INTERVAL_MINUTES=5
|
||||
|
||||
# =============================================================================
|
||||
# 交易执行 / 人工风控(页面「实盘下单」)
|
||||
# =============================================================================
|
||||
# 【最大同时持仓】默认 1=单仓
|
||||
MAX_ACTIVE_POSITIONS=1
|
||||
# 【人工下单最低盈亏比】低于该值前后端均拒绝(默认 1.4,即须 >=1.4:1)
|
||||
MANUAL_MIN_PLANNED_RR=1.4
|
||||
# 【关键位连开计仓】已有持仓时按无仓时资金快照算基数
|
||||
KEY_SIZING_USE_ZERO_POSITION_SNAPSHOT=true
|
||||
# 【单日开仓 AI 提醒】本交易日开仓达到该次数时推送企业微信 AI 克制提醒(不拦单)
|
||||
DAILY_OPEN_ALERT_THRESHOLD=5
|
||||
# 【单日开仓硬上限】本交易日开仓次数>=该值后禁止一切新开仓直至下一交易日(北京时间 TRADING_DAY_RESET_HOUR 切日);0=不启用
|
||||
DAILY_OPEN_HARD_LIMIT=0
|
||||
|
||||
# =============================================================================
|
||||
# 账户冷静期 / 日冻结风控(手动平仓、外部平仓、复盘情绪标签)
|
||||
# 详见 docs/account-risk-cooldown.md
|
||||
# =============================================================================
|
||||
# RISK_CONTROL_ENABLED=true
|
||||
# RISK_COOLING_HOURS_MANUAL=4
|
||||
# RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
# RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
# RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
|
||||
# 资金与仓位刷新周期(秒)
|
||||
BALANCE_REFRESH_SECONDS=60
|
||||
# 前端价格快照轮询(秒)
|
||||
PRICE_REFRESH_SECONDS=5
|
||||
# 后台监控轮询周期(秒)
|
||||
MONITOR_POLL_SECONDS=3
|
||||
# 重启后多少秒内不做「外部平仓」同步(避免 API 未就绪误判)
|
||||
RECONCILE_STARTUP_GRACE_SEC=90
|
||||
# 连续多少次轮询确认交易所空仓后,才记为外部平仓(默认 3 次 ≈ 9 秒)
|
||||
RECONCILE_FLAT_CONFIRM_POLLS=3
|
||||
# 使用可用资金时的缓冲比例(如0.98代表用98%)
|
||||
FULL_MARGIN_BUFFER_RATIO=0.98
|
||||
|
||||
# =============================================================================
|
||||
# 自动划转(页顶「将 swap 补足到 XU」;与 DAILY_START_CAPITAL 独立,需一致时请设为相同值)
|
||||
# =============================================================================
|
||||
AUTO_TRANSFER_ENABLED=false
|
||||
# 交易账户(swap)目标余额 U:每日 8 点(北京)自动划入或划出至 funding;持仓中不划转
|
||||
AUTO_TRANSFER_AMOUNT=30
|
||||
AUTO_TRANSFER_FROM=funding
|
||||
AUTO_TRANSFER_TO=swap
|
||||
TRANSFER_CCY=USDT
|
||||
# 北京时间该整点小时内尝试;账簿按 UTC 自然日去重
|
||||
AUTO_TRANSFER_BJ_HOUR=8
|
||||
# 强制清仓整点(北京时间,默认 0=凌晨00点)
|
||||
FORCE_CLOSE_BJ_HOUR=0
|
||||
# 是否启用强制清仓(默认关闭,true 才会在整点执行)
|
||||
FORCE_CLOSE_ENABLED=false
|
||||
|
||||
# 推送与AI超时(秒)
|
||||
WECHAT_TIMEOUT_SECONDS=10
|
||||
AI_TIMEOUT_SECONDS=120
|
||||
|
||||
# AI 提供方:openai(默认)| ollama
|
||||
AI_PROVIDER=openai
|
||||
OPENAI_API_BASE=https://op.bz121.com/v1
|
||||
OPENAI_API_KEY=你的密钥
|
||||
OPENAI_MODEL=gemma4:e4b
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
|
||||
# Gate 代理(可选):本机网络不稳定时通过 SSH 动态转发 SOCKS5 出口
|
||||
# 1) 先在本机建立隧道(示例):
|
||||
# ssh -N -D 127.0.0.1:1080 root@你的VPS_IP -o ServerAliveInterval=30 -o ExitOnForwardFailure=yes
|
||||
# 2) 再启用下面这一行(推荐 socks5h,让远端解析域名):
|
||||
# GATE_SOCKS_PROXY=socks5h://127.0.0.1:1080
|
||||
#
|
||||
# 如你更偏向 HTTP 代理(VPS 上跑 tinyproxy 之类),可用:
|
||||
# GATE_HTTP_PROXY=http://127.0.0.1:3128
|
||||
# GATE_HTTPS_PROXY=http://127.0.0.1:3128
|
||||
|
||||
# 开仓多周期K线图(可选)
|
||||
# ORDER_CHART_ENABLED=true
|
||||
# ORDER_CHART_TFS=4h,1h,15m,5m
|
||||
# ORDER_CHART_LIMIT=100
|
||||
# ORDER_CHART_DIR=static/images/order_charts
|
||||
# 详见 DAILY_OPEN_ALERT_THRESHOLD / DAILY_OPEN_HARD_LIMIT;说明文档 docs/daily-open-limit.md
|
||||
# 以损定仓(按交易账户资金的百分比)
|
||||
# RISK_PERCENT=2
|
||||
# 移动保本触发(达到多少R触发)与偏移(百分比)
|
||||
# BREAKEVEN_RR_TRIGGER=1.0
|
||||
# 移动保本阶梯(每多少R继续上移一次,默认1R)
|
||||
# BREAKEVEN_STEP_R=1.0
|
||||
# BREAKEVEN_OFFSET_PCT=0.02
|
||||
# 开单风格默认值:trend / swing
|
||||
# DEFAULT_TRADE_STYLE=trend
|
||||
|
||||
APP_TIMEZONE=Asia/Shanghai
|
||||
# TRADING_DAY_RESET_HOUR 现在表示「北京时间」整点,默认 8 点起算新交易日;开仓整点限制见 TRADING_DAY_RESET_OPEN_GUARD_ENABLED
|
||||
@@ -1,90 +0,0 @@
|
||||
# crypto_monitor_gate
|
||||
|
||||
基于 **Flask** 的加密货币 **下单监控 / 关键位监控 / 交易复盘** 小系统,行情与实盘接口统一走 **Gate.io USDT 永续**,通过 **ccxt** 访问。
|
||||
|
||||
## 文档导航
|
||||
|
||||
| 文档 | 说明 |
|
||||
|------|------|
|
||||
| **[使用说明.md](./使用说明.md)** | 日常怎么用:登录、关键位四类、手工开仓、单仓与微信等 |
|
||||
| **[关键位自动下单说明.md](./关键位自动下单说明.md)** | 关键位自动开仓的 RR、止盈止损、结案原因与 `.env` |
|
||||
| **[部署文档.md](./部署文档.md)** | Ubuntu、PM2、**SSH SOCKS** 访问 Gate API 等 |
|
||||
|
||||
另:**Binance U 本位** 对等实现见同级的 **`crypto_monitor_binance`** 仓库。
|
||||
|
||||
---
|
||||
|
||||
## 功能概要
|
||||
|
||||
- **关键位监控**:5m 收线硬条件、企业微信推送;**箱体 / 收敛** 在 RR 达标时可 **自动市价开仓**(见专门文档);**阻力 / 支撑** 仅单次提醒结案
|
||||
- **下单监控**:本地风控(含移动保本)、止盈/止损触达后轮询尝试平仓并记账
|
||||
- **实盘(可选)**:`LIVE_TRADING_ENABLED=true` 且配置 **`GATE_API_KEY` / `GATE_API_SECRET`** 时,支持开仓、挂单 TP/SL、余额与划转(权限依账户而定)
|
||||
- **止盈止损(Gate)**:市价成交后经 **`_gate_place_tp_sl_orders`** 挂单;优先 **仓位类 `price_orders`**(受 `GATE_TPSL_USE_POSITION_ORDER`、`GATE_TPSL_PRICE_TYPE`、`GATE_POS_MODE` 等影响)
|
||||
|
||||
---
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Python 3.10+(建议)
|
||||
- 依赖:`flask`、`requests`、`ccxt`、`werkzeug`、`PySocks`(经 SOCKS 代理时);`Pillow`(K 线导出等可选用)
|
||||
|
||||
安装示例:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate
|
||||
source .venv/bin/activate
|
||||
pip install -r ../requirements.txt
|
||||
```
|
||||
|
||||
## 配置(`.env.example` → `.env`)
|
||||
|
||||
- **`.env.example`**:模板(可提交 Git);首次:`cp .env.example .env` 后编辑。
|
||||
- **`.env`**:本机真实配置(勿提交);`git pull` 不覆盖;升级前建议备份(见《部署文档》§5.2)。
|
||||
|
||||
项目启动时加载**仓库根目录**下的 `.env`。常用项:
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `GATE_API_KEY` / `GATE_API_SECRET` | Gate API(需合约与对应权限) |
|
||||
| `LIVE_TRADING_ENABLED` | `true` 允许真实下单;`false` 仅本地与推送逻辑 |
|
||||
| `GATE_MARGIN_MODE` / `GATE_POS_MODE` | 保证金与持仓模式 |
|
||||
| `GATE_TPSL_USE_POSITION_ORDER` / `GATE_TPSL_PRICE_TYPE` 等 | 条件止盈止损行为 |
|
||||
| `GATE_SOCKS_PROXY` | 可选;直连不稳时 SSH 动态转发(详见部署文档) |
|
||||
| `APP_PASSWORD` / `FLASK_SECRET_KEY` | Web 登录与 Session |
|
||||
| `WECHAT_WEBHOOK` | 企业微信机器人 |
|
||||
| `EXCHANGE_DISPLAY_NAME` / `GATE_ACCOUNT_LABEL` | 页面与推送展示的账户文案 |
|
||||
|
||||
其余见 **`.env.example` 内注释** 或 **`app.py` 顶部默认值**。
|
||||
|
||||
## 运行
|
||||
|
||||
生产使用 **PM2**(`ecosystem.config.cjs`)。调试:
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate && python app.py
|
||||
```
|
||||
|
||||
见 [docs/ubuntu-server.md](../docs/ubuntu-server.md)。
|
||||
|
||||
端口由 **`APP_PORT`** 控制(未设置默认 **5000**)。浏览器登录 **`/login`**,口令为 **`APP_PASSWORD`**。
|
||||
|
||||
## 部署(Linux / PM2 / SSH SOCKS)
|
||||
|
||||
见 **[部署文档.md](./部署文档.md)**。
|
||||
|
||||
## 自检脚本
|
||||
|
||||
```bash
|
||||
python scripts/verify_gate_funding.py
|
||||
```
|
||||
|
||||
用于核对密钥前缀(不落 Secret)、资金/合约可读性等(需网络与权限)。
|
||||
|
||||
## 数据与脚本
|
||||
|
||||
- 默认 SQLite:由 **`DB_PATH`** 指定(常见为项目下 `crypto.db`)
|
||||
- `scripts/fix_breakeven_labels.py`:修正「止损」但盈亏为正的记录标签(参见部署文档说明)
|
||||
|
||||
## 风险与合规
|
||||
|
||||
实盘有亏损风险。请确认 API 权限、IP 白名单、杠杆与保证金模式与 **Gate.io** 后台一致,并遵守当地法律法规与交易所用户协议。
|
||||
@@ -1,34 +0,0 @@
|
||||
/**
|
||||
* PM2 进程定义(Ubuntu / Linux)。
|
||||
*
|
||||
* 仅托管 Flask 应用。**SSH SOCKS 隧道**用 `ssh -D` 常驻(可用 tmux / autossh),勿交给 PM2。
|
||||
* 与 `.env` 里 `GATE_SOCKS_PROXY` 端口一致即可;不必交给 PM2。
|
||||
*
|
||||
* 使用前:项目根目录存在 `.venv`,且已安装依赖(走 SOCKS 时需 PySocks)。
|
||||
*
|
||||
* 启动:
|
||||
* pm2 start ecosystem.config.cjs
|
||||
* 保存开机列表:
|
||||
* pm2 save && pm2 startup
|
||||
*/
|
||||
const path = require("path");
|
||||
|
||||
const ROOT = __dirname;
|
||||
const REPO_ROOT = path.join(ROOT, "..");
|
||||
const PY = path.join(ROOT, ".venv", "bin", "python");
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "crypto_gate_bot",
|
||||
cwd: ROOT,
|
||||
script: path.join(ROOT, "app.py"),
|
||||
interpreter: PY,
|
||||
instances: 1,
|
||||
autorestart: true,
|
||||
watch: false,
|
||||
max_memory_restart: "800M",
|
||||
env: { PYTHONPATH: REPO_ROOT },
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,109 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Daily backup: SQLite DB + static/images → /root/backups/<instance>/<YYYY-MM-DD>/
|
||||
# Prune backup folders older than RETENTION_DAYS (default 30).
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
BACKUP_ROOT="${BACKUP_ROOT:-/root/backups}"
|
||||
RETENTION_DAYS="${RETENTION_DAYS:-30}"
|
||||
INSTANCE_NAME="${BACKUP_INSTANCE:-$(basename "$PROJECT_DIR")}"
|
||||
TZ_NAME="${BACKUP_TZ:-Asia/Shanghai}"
|
||||
|
||||
log() {
|
||||
printf '[%s] %s\n' "$(TZ="$TZ_NAME" date '+%Y-%m-%d %H:%M:%S %Z')" "$*"
|
||||
}
|
||||
|
||||
read_env_var() {
|
||||
local key="$1"
|
||||
local default="$2"
|
||||
local line
|
||||
if [[ ! -f .env ]]; then
|
||||
printf '%s' "$default"
|
||||
return
|
||||
fi
|
||||
line="$(grep -E "^${key}=" .env 2>/dev/null | tail -1 || true)"
|
||||
if [[ -z "$line" ]]; then
|
||||
printf '%s' "$default"
|
||||
return
|
||||
fi
|
||||
printf '%s' "${line#*=}" | tr -d '\r'
|
||||
}
|
||||
|
||||
resolve_project_path() {
|
||||
local p="$1"
|
||||
if [[ "$p" == /* ]]; then
|
||||
printf '%s' "$p"
|
||||
else
|
||||
printf '%s' "$PROJECT_DIR/$p"
|
||||
fi
|
||||
}
|
||||
|
||||
prune_old_backups() {
|
||||
local base="$BACKUP_ROOT/$INSTANCE_NAME"
|
||||
[[ -d "$base" ]] || return 0
|
||||
local cutoff
|
||||
cutoff="$(TZ="$TZ_NAME" date -d "-${RETENTION_DAYS} days" +%Y-%m-%d 2>/dev/null || true)"
|
||||
if [[ -z "$cutoff" ]]; then
|
||||
find "$base" -mindepth 1 -maxdepth 1 -type d -mtime +"$RETENTION_DAYS" -print0 |
|
||||
xargs -r -0 rm -rf
|
||||
return 0
|
||||
fi
|
||||
local dir name
|
||||
for dir in "$base"/*/; do
|
||||
[[ -d "$dir" ]] || continue
|
||||
name="$(basename "$dir")"
|
||||
[[ "$name" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || continue
|
||||
if [[ "$name" < "$cutoff" ]]; then
|
||||
log "prune: remove $dir (older than ${RETENTION_DAYS} days)"
|
||||
rm -rf "$dir"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
DB_REL="$(read_env_var DB_PATH crypto.db)"
|
||||
UPLOAD_REL="$(read_env_var UPLOAD_DIR static/images)"
|
||||
BACKUP_ROOT="$(read_env_var BACKUP_ROOT "$BACKUP_ROOT")"
|
||||
RETENTION_DAYS="$(read_env_var BACKUP_RETENTION_DAYS "$RETENTION_DAYS")"
|
||||
INSTANCE_NAME="$(read_env_var BACKUP_INSTANCE "$INSTANCE_NAME")"
|
||||
|
||||
DB_PATH="$(resolve_project_path "$DB_REL")"
|
||||
UPLOAD_DIR="$(resolve_project_path "$UPLOAD_REL")"
|
||||
DATE_TAG="$(TZ="$TZ_NAME" date +%Y-%m-%d)"
|
||||
DEST="$BACKUP_ROOT/$INSTANCE_NAME/$DATE_TAG"
|
||||
|
||||
if [[ ! -f "$DB_PATH" ]]; then
|
||||
log "error: database not found: $DB_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$DEST"
|
||||
log "start backup instance=$INSTANCE_NAME dest=$DEST"
|
||||
|
||||
if command -v sqlite3 >/dev/null 2>&1; then
|
||||
sqlite3 "$DB_PATH" ".backup '$DEST/crypto.db'"
|
||||
log "db: sqlite3 backup -> $DEST/crypto.db"
|
||||
else
|
||||
cp -a "$DB_PATH" "$DEST/crypto.db"
|
||||
log "db: cp -> $DEST/crypto.db (sqlite3 not installed)"
|
||||
fi
|
||||
|
||||
if [[ -d "$UPLOAD_DIR" ]]; then
|
||||
tar -czf "$DEST/static_images.tar.gz" -C "$(dirname "$UPLOAD_DIR")" "$(basename "$UPLOAD_DIR")"
|
||||
log "images: $UPLOAD_DIR -> $DEST/static_images.tar.gz"
|
||||
else
|
||||
log "warn: upload dir missing, skip images: $UPLOAD_DIR"
|
||||
fi
|
||||
|
||||
{
|
||||
echo "instance=$INSTANCE_NAME"
|
||||
echo "project_dir=$PROJECT_DIR"
|
||||
echo "backup_date=$DATE_TAG"
|
||||
echo "db_path=$DB_PATH"
|
||||
echo "upload_dir=$UPLOAD_DIR"
|
||||
} >"$DEST/manifest.txt"
|
||||
|
||||
prune_old_backups
|
||||
log "done"
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot SQLite backup before code deploy. Reads DB_PATH from .env (default crypto.db)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _read_env_db_path() -> Path:
|
||||
env_file = PROJECT_DIR / ".env"
|
||||
default = PROJECT_DIR / "crypto.db"
|
||||
if not env_file.is_file():
|
||||
return default
|
||||
for line in env_file.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, val = line.split("=", 1)
|
||||
if key.strip() != "DB_PATH":
|
||||
continue
|
||||
val = val.strip().strip('"').strip("'")
|
||||
p = Path(val)
|
||||
return p if p.is_absolute() else PROJECT_DIR / p
|
||||
return default
|
||||
|
||||
|
||||
def main() -> int:
|
||||
db_path = _read_env_db_path()
|
||||
if not db_path.is_file():
|
||||
print(f"error: database not found: {db_path}")
|
||||
return 1
|
||||
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
dest_dir = PROJECT_DIR / "backups" / stamp
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest = dest_dir / db_path.name
|
||||
try:
|
||||
src = sqlite3.connect(str(db_path))
|
||||
dst = sqlite3.connect(str(dest))
|
||||
src.backup(dst)
|
||||
dst.close()
|
||||
src.close()
|
||||
method = "sqlite3 backup"
|
||||
except Exception:
|
||||
shutil.copy2(db_path, dest)
|
||||
method = "file copy"
|
||||
manifest = dest_dir / "manifest.txt"
|
||||
manifest.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
f"project_dir={PROJECT_DIR}",
|
||||
f"source_db={db_path}",
|
||||
f"backup_file={dest}",
|
||||
f"method={method}",
|
||||
f"created_at={stamp}",
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f"ok: {dest} ({method})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
一次性修复历史交易记录标签:
|
||||
将 trade_records 里“止损但实际盈利”的记录改为“保本止盈”。
|
||||
|
||||
默认条件(可通过参数修改):
|
||||
- monitor_type = 下单监控
|
||||
- result = 止损
|
||||
- pnl_amount > 0
|
||||
|
||||
用法示例:
|
||||
1) 仅预览(不落库):
|
||||
python scripts/fix_breakeven_labels.py --db ./crypto.db --dry-run
|
||||
|
||||
2) 执行修复:
|
||||
python scripts/fix_breakeven_labels.py --db ./crypto.db --apply
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Fix historical stop-loss records with positive pnl.")
|
||||
parser.add_argument("--db", required=True, help="Path to sqlite db file, e.g. ./crypto.db")
|
||||
parser.add_argument("--monitor-type", default="下单监控", help="Filter by monitor_type (default: 下单监控)")
|
||||
parser.add_argument("--from-result", default="止损", help="Source result label (default: 止损)")
|
||||
parser.add_argument("--to-result", default="保本止盈", help="Target result label (default: 保本止盈)")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Preview only, no write")
|
||||
parser.add_argument("--apply", action="store_true", help="Execute update")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
db_path = Path(args.db).expanduser().resolve()
|
||||
if not db_path.exists():
|
||||
print(f"[ERR] DB not found: {db_path}")
|
||||
return 1
|
||||
|
||||
if args.dry_run and args.apply:
|
||||
print("[ERR] --dry-run and --apply are mutually exclusive.")
|
||||
return 1
|
||||
if not args.dry_run and not args.apply:
|
||||
print("[INFO] No mode provided, defaulting to --dry-run.")
|
||||
args.dry_run = True
|
||||
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
|
||||
where_sql = """
|
||||
monitor_type = ?
|
||||
AND result = ?
|
||||
AND CAST(COALESCE(pnl_amount, 0) AS REAL) > 0
|
||||
"""
|
||||
params = (args.monitor_type, args.from_result)
|
||||
|
||||
cur.execute(f"SELECT COUNT(*) AS c FROM trade_records WHERE {where_sql}", params)
|
||||
will_change = int(cur.fetchone()["c"])
|
||||
print(f"[INFO] Candidate rows: {will_change}")
|
||||
|
||||
if will_change == 0:
|
||||
print("[INFO] Nothing to update.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, symbol, result, pnl_amount, closed_at
|
||||
FROM trade_records
|
||||
WHERE {where_sql}
|
||||
ORDER BY id DESC
|
||||
LIMIT 10
|
||||
""",
|
||||
params,
|
||||
)
|
||||
sample = cur.fetchall()
|
||||
print("[INFO] Sample (latest 10):")
|
||||
for r in sample:
|
||||
print(
|
||||
f" id={r['id']} symbol={r['symbol']} result={r['result']} "
|
||||
f"pnl={r['pnl_amount']} closed_at={r['closed_at']}"
|
||||
)
|
||||
|
||||
if args.dry_run:
|
||||
print("[DRY-RUN] No write executed.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
cur.execute(
|
||||
f"UPDATE trade_records SET result=? WHERE {where_sql}",
|
||||
(args.to_result, *params),
|
||||
)
|
||||
changed = int(cur.rowcount)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"[DONE] Updated rows: {changed}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install daily backup cron: Beijing 00:00 (CRON_TZ=Asia/Shanghai).
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
BACKUP_SCRIPT="$SCRIPT_DIR/backup_data.sh"
|
||||
INSTANCE_NAME="${BACKUP_INSTANCE:-$(basename "$PROJECT_DIR")}"
|
||||
LOG_FILE="${BACKUP_CRON_LOG:-/var/log/crypto-monitor-backup-${INSTANCE_NAME}.log}"
|
||||
|
||||
if [[ ! -x "$BACKUP_SCRIPT" ]]; then
|
||||
chmod +x "$BACKUP_SCRIPT"
|
||||
fi
|
||||
|
||||
TMP="$(mktemp)"
|
||||
trap 'rm -f "$TMP"' EXIT
|
||||
|
||||
{
|
||||
crontab -l 2>/dev/null | grep -vF "$BACKUP_SCRIPT" || true
|
||||
echo "CRON_TZ=Asia/Shanghai"
|
||||
echo "0 0 * * * $BACKUP_SCRIPT >> $LOG_FILE 2>&1"
|
||||
} >"$TMP"
|
||||
|
||||
awk '
|
||||
BEGIN { tz = 0 }
|
||||
/^CRON_TZ=Asia\/Shanghai$/ {
|
||||
if (tz++) next
|
||||
}
|
||||
{ print }
|
||||
' "$TMP" >"${TMP}.2"
|
||||
mv "${TMP}.2" "$TMP"
|
||||
|
||||
crontab "$TMP"
|
||||
echo "Installed cron for $INSTANCE_NAME"
|
||||
echo " Schedule : daily 00:00 Asia/Shanghai"
|
||||
echo " Script : $BACKUP_SCRIPT"
|
||||
echo " Log : $LOG_FILE"
|
||||
crontab -l | grep -F "$BACKUP_SCRIPT" || true
|
||||
@@ -1,93 +0,0 @@
|
||||
"""
|
||||
在项目根目录执行(会加载根目录 .env):
|
||||
python scripts/verify_gate_funding.py
|
||||
|
||||
依次探测:[0] swap 余额(与 App「交易账户」同源);[1]–[3] 现货 / 统一账户资金路径。
|
||||
打印 GATE_API_KEY 前 8 位便于与 Gate 控制台核对(不含 Secret)。用于服务器自检。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
def _load_app():
|
||||
path = os.path.join(ROOT, "app.py")
|
||||
spec = importlib.util.spec_from_file_location("crypto_app", path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def main():
|
||||
os.chdir(ROOT)
|
||||
mod = _load_app()
|
||||
print("LIVE_TRADING_ENABLED =", os.getenv("LIVE_TRADING_ENABLED"))
|
||||
ok, reason = mod.ensure_exchange_live_ready()
|
||||
print("ensure_exchange_live_ready =", ok, repr(reason))
|
||||
if not ok:
|
||||
print("跳过私有接口探测")
|
||||
return 1
|
||||
|
||||
mod.ensure_markets_loaded()
|
||||
|
||||
k = (os.getenv("GATE_API_KEY") or "").strip()
|
||||
s = (os.getenv("GATE_API_SECRET") or "").strip()
|
||||
if not k or "REPLACE" in k.upper():
|
||||
print("WARN: GATE_API_KEY 为空或仍像占位符,请核对 .env")
|
||||
if not s or "REPLACE" in s.upper():
|
||||
print("WARN: GATE_API_SECRET 为空或仍像占位符,请核对 .env")
|
||||
print("GATE_API_KEY prefix (8 chars):", (k[:8] + "…") if len(k) > 8 else "(short)")
|
||||
|
||||
# 0) swap — 与 App「交易账户」余额同源(优先看此项是否与网页一致)
|
||||
try:
|
||||
bal = mod.exchange.fetch_balance({"type": "swap"})
|
||||
v0 = mod._extract_usdt_total(bal)
|
||||
print("[0] fetch_balance(swap) USDT total =", v0)
|
||||
except Exception as e:
|
||||
print("[0] fetch_balance(swap) FAILED:", type(e).__name__, e)
|
||||
|
||||
# 1) fetch_balance spot + marginMode spot
|
||||
try:
|
||||
bal = mod.exchange.fetch_balance({"type": "spot", "marginMode": "spot"})
|
||||
v = mod._extract_usdt_total(bal)
|
||||
print("[1] fetch_balance(spot,marginMode=spot) USDT total =", v)
|
||||
except Exception as e:
|
||||
print("[1] fetch_balance(spot) FAILED:", type(e).__name__, e)
|
||||
|
||||
# 2) raw spot accounts
|
||||
try:
|
||||
resp = mod.exchange.privateSpotGetAccounts({})
|
||||
v2 = mod._parse_gate_spot_accounts_response_usdt(resp)
|
||||
print("[2] privateSpotGetAccounts USDT =", v2)
|
||||
except Exception as e:
|
||||
print("[2] privateSpotGetAccounts FAILED:", type(e).__name__, e)
|
||||
|
||||
# 3) unified accounts raw
|
||||
try:
|
||||
raw = mod.exchange.privateUnifiedGetAccounts({})
|
||||
body = raw
|
||||
if isinstance(body, dict) and isinstance(body.get("result"), dict):
|
||||
body = body["result"]
|
||||
if isinstance(body, dict):
|
||||
keys = sorted(body.keys())
|
||||
print("[3] unified top-level keys (sample):", keys[:25], "..." if len(keys) > 25 else "")
|
||||
v3 = mod._parse_usdt_from_gate_unified_accounts_body(body) if isinstance(body, dict) else None
|
||||
print("[3] parsed unified USDT =", v3)
|
||||
except Exception as e:
|
||||
print("[3] privateUnifiedGetAccounts FAILED:", type(e).__name__, e)
|
||||
|
||||
fu = mod._fetch_gate_funding_usdt()
|
||||
print(">>> _fetch_gate_funding_usdt() =", fu)
|
||||
f, t = mod.get_exchange_capitals(force=True)
|
||||
print(">>> get_exchange_capitals(force=True) funding, trading =", f, t)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 181 B |
|
Before Width: | Height: | Size: 162 B |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 497 B |
|
Before Width: | Height: | Size: 5.9 KiB |
@@ -1,17 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stop-color="#22d3ee"/>
|
||||
<stop offset="100%" stop-color="#34d399"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="512" height="512" rx="108" fill="#0c1019"/>
|
||||
<rect x="36" y="36" width="440" height="440" rx="88" fill="#141b2d"/>
|
||||
<rect x="36" y="36" width="440" height="440" rx="88" fill="none" stroke="url(#g)" stroke-width="12"/>
|
||||
<path d="M120 320 L200 248 L280 272 L392 168" fill="none" stroke="url(#g)" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="392" cy="168" r="18" fill="#34d399"/>
|
||||
<rect x="168" y="268" width="28" height="64" rx="6" fill="#f87171"/>
|
||||
<line x1="182" y1="248" x2="182" y2="340" stroke="#f87171" stroke-width="10" stroke-linecap="round"/>
|
||||
<rect x="268" y="220" width="28" height="96" rx="6" fill="#34d399"/>
|
||||
<line x1="282" y1="200" x2="282" y2="340" stroke="#34d399" stroke-width="10" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"name": "交易监控复盘",
|
||||
"short_name": "监控",
|
||||
"description": "加密货币永续交易监控与复盘",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#0b0d14",
|
||||
"theme_color": "#0b0d14",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/static/icons/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/static/icons/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
ok2
|
||||
@@ -1,136 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<script src="/static/instance_theme.js?v=4"></script>
|
||||
|
||||
<title>登录 · {{ exchange_display }}</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
background: #0a0a10;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
color: #fff;
|
||||
}
|
||||
.login-box {
|
||||
background: #12121a;
|
||||
padding: 2.5rem;
|
||||
border-radius: 16px;
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
border: 1px solid #242435;
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,0.3);
|
||||
}
|
||||
.login-box h2 {
|
||||
margin-bottom: 2rem;
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
background: linear-gradient(90deg, #4cc2ff, #7b42ff);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
color: #a9a9ff;
|
||||
}
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #2e2e45;
|
||||
background: #1a1a29;
|
||||
color: #fff;
|
||||
font-size: 0.95rem;
|
||||
outline: none;
|
||||
}
|
||||
.form-group input:focus {
|
||||
border-color: #4cc2ff;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.9rem;
|
||||
border-radius: 10px;
|
||||
border: none;
|
||||
background: linear-gradient(90deg, #4285f4, #7b42ff);
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: 0.2s;
|
||||
}
|
||||
button:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
.flash {
|
||||
padding: 0.8rem;
|
||||
margin-bottom: 1rem;
|
||||
background: #331e24;
|
||||
color: #ff6666;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.exchange-line {
|
||||
text-align: center;
|
||||
font-size: 0.82rem;
|
||||
color: #8892b0;
|
||||
margin: -0.5rem 0 1.25rem;
|
||||
}
|
||||
.exchange-line strong {
|
||||
color: #b8f5d0;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="/static/instance_theme.css?v=4">
|
||||
|
||||
</head>
|
||||
<div class="login-theme-bar">
|
||||
<div class="theme-toggle instance-theme-toggle" role="group" aria-label="界面主题">
|
||||
<button type="button" class="theme-toggle-btn is-active" data-theme-value="dark" aria-pressed="true" title="暗色主题">
|
||||
<svg class="theme-icon" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
|
||||
<path fill="currentColor" d="M12.1 3a9 9 0 1 0 8.9 11 6.5 6.5 0 1 1-8.9-11z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button" class="theme-toggle-btn" data-theme-value="light" aria-pressed="false" title="亮色主题">
|
||||
<svg class="theme-icon" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
||||
<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<body>
|
||||
<div class="login-box">
|
||||
<h2>交易监控系统登录</h2>
|
||||
<p class="exchange-line">交易所:<strong>{{ exchange_display }}</strong></p>
|
||||
{% with messages = get_flashed_messages() %}
|
||||
{% if messages %}
|
||||
<div class="flash">{{ messages[0] }}</div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
<form method="POST" autocomplete="off">
|
||||
<div class="form-group">
|
||||
<label>账号</label>
|
||||
<input type="text" name="username" required placeholder="请输入账号" autocomplete="off" autocapitalize="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码</label>
|
||||
<input type="password" name="password" required placeholder="请输入密码" autocomplete="new-password">
|
||||
</div>
|
||||
<button type="submit">登录</button>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,194 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>实盘下单放大 | 100根K线</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;background:#0b0d14;color:#eaeaea;padding:14px}
|
||||
.container{width:min(98vw,1900px);margin:0 auto}
|
||||
.card{background:#121726;border-radius:10px;padding:12px;border:1px solid #2a3150;margin-bottom:12px}
|
||||
.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
||||
.btn{padding:7px 10px;border-radius:8px;text-decoration:none;border:1px solid #304164;background:#151a2a;color:#8fc8ff;cursor:pointer}
|
||||
.btn:hover{background:#1f2740}
|
||||
select,button{padding:8px 10px;border-radius:8px;border:1px solid #2e2e45;background:#1a1a29;color:#fff}
|
||||
.meta{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:8px;margin-top:10px}
|
||||
.meta-item{background:#141b2f;border:1px solid #27324e;border-radius:8px;padding:8px}
|
||||
.meta-item .k{font-size:.76rem;color:#9fb0d8}
|
||||
.meta-item .v{font-size:1rem;margin-top:4px;word-break:break-all}
|
||||
.status{font-size:.84rem;color:#95a2c2}
|
||||
.status.err{color:#ff8080}
|
||||
#chart-wrap{height:560px;background:#0f1320;border:1px solid #2a3150;border-radius:10px;padding:8px}
|
||||
#chart{width:100%;height:100%}
|
||||
.empty{padding:18px;color:#95a2c2}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="row" style="justify-content:space-between">
|
||||
<div class="row">
|
||||
<a class="btn" href="/">返回首页</a>
|
||||
<strong style="color:#dbe4ff">实盘下单放大(100根K线)</strong>
|
||||
</div>
|
||||
<div class="status">最近刷新:<span id="updated-at">--</span></div>
|
||||
</div>
|
||||
{% if orders %}
|
||||
<div class="row" style="margin-top:10px">
|
||||
<label>订单</label>
|
||||
<select id="order-id">
|
||||
{% for o in orders %}
|
||||
<option value="{{ o.id }}" {% if selected_order and o.id == selected_order.id %}selected{% endif %}>
|
||||
#{{ o.id }} {{ o.symbol }} {{ '做多' if o.direction == 'long' else '做空' }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<label>周期</label>
|
||||
<select id="timeframe">
|
||||
{% for tf in ['1m','3m','5m','15m','30m','1h','4h','1d'] %}
|
||||
<option value="{{ tf }}" {% if tf == default_timeframe %}selected{% endif %}>{{ tf }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button id="manual-refresh" type="button">刷新</button>
|
||||
<span id="load-status" class="status"></span>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty">当前没有激活订单,无法展示放大K线。</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if orders %}
|
||||
<div class="card">
|
||||
<div class="meta">
|
||||
<div class="meta-item"><div class="k">交易对</div><div class="v" id="m-symbol">-</div></div>
|
||||
<div class="meta-item"><div class="k">方向</div><div class="v" id="m-direction">-</div></div>
|
||||
<div class="meta-item"><div class="k">成交价</div><div class="v" id="m-entry">-</div></div>
|
||||
<div class="meta-item"><div class="k">止损</div><div class="v" id="m-sl">-</div></div>
|
||||
<div class="meta-item"><div class="k">止盈</div><div class="v" id="m-tp">-</div></div>
|
||||
<div class="meta-item"><div class="k">盈亏比</div><div class="v" id="m-rr">-</div></div>
|
||||
<div class="meta-item"><div class="k">现价</div><div class="v" id="m-price">-</div></div>
|
||||
<div class="meta-item"><div class="k">浮盈亏</div><div class="v" id="m-pnl">-</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div id="chart-wrap"><div id="chart"></div></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if orders %}
|
||||
<script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
|
||||
<script>
|
||||
const refreshMs = Math.max({{ price_refresh_seconds * 1000 }}, 5000);
|
||||
const orderSelect = document.getElementById("order-id");
|
||||
const tfSelect = document.getElementById("timeframe");
|
||||
const statusEl = document.getElementById("load-status");
|
||||
const updatedAtEl = document.getElementById("updated-at");
|
||||
const chartHost = document.getElementById("chart");
|
||||
const fmt = (v, d=6) => (v === null || typeof v === "undefined" || Number.isNaN(Number(v))) ? "-" : Number(v).toFixed(d);
|
||||
|
||||
let chart = null;
|
||||
let candleSeries = null;
|
||||
let priceLines = [];
|
||||
|
||||
function ensureChart(){
|
||||
if(chart){ return true; }
|
||||
if(!window.LightweightCharts){
|
||||
statusEl.className = "status err";
|
||||
statusEl.innerText = "图表库加载失败";
|
||||
return false;
|
||||
}
|
||||
chart = LightweightCharts.createChart(chartHost, {
|
||||
layout: { background: { color: "#0f1320" }, textColor: "#d6deff" },
|
||||
grid: { vertLines: { color: "#1e263d" }, horzLines: { color: "#1e263d" } },
|
||||
rightPriceScale: { borderColor: "#2a3150" },
|
||||
timeScale: { borderColor: "#2a3150", timeVisible: true, secondsVisible: false },
|
||||
crosshair: { mode: 0 }
|
||||
});
|
||||
candleSeries = chart.addCandlestickSeries({
|
||||
upColor: "#4cd97f",
|
||||
downColor: "#ff6666",
|
||||
borderVisible: false,
|
||||
wickUpColor: "#4cd97f",
|
||||
wickDownColor: "#ff6666"
|
||||
});
|
||||
window.addEventListener("resize", () => {
|
||||
chart.applyOptions({ width: chartHost.clientWidth, height: chartHost.clientHeight });
|
||||
});
|
||||
chart.applyOptions({ width: chartHost.clientWidth, height: chartHost.clientHeight });
|
||||
return true;
|
||||
}
|
||||
|
||||
function resetPriceLines(){
|
||||
if(!candleSeries){ return; }
|
||||
priceLines.forEach(line => {
|
||||
try { candleSeries.removePriceLine(line); } catch (_) {}
|
||||
});
|
||||
priceLines = [];
|
||||
}
|
||||
|
||||
function addLine(price, title, color){
|
||||
if(!candleSeries || typeof price === "undefined" || price === null){ return; }
|
||||
const p = Number(price);
|
||||
if(Number.isNaN(p) || p <= 0){ return; }
|
||||
priceLines.push(candleSeries.createPriceLine({
|
||||
price: p, color, lineWidth: 1, lineStyle: 0, axisLabelVisible: true, title
|
||||
}));
|
||||
}
|
||||
|
||||
function paintOrder(order){
|
||||
document.getElementById("m-symbol").innerText = order.symbol || "-";
|
||||
document.getElementById("m-direction").innerText = (order.direction === "short") ? "做空" : "做多";
|
||||
document.getElementById("m-entry").innerText = order.trigger_price_display || fmt(order.trigger_price, 8);
|
||||
document.getElementById("m-sl").innerText = order.stop_loss_display || fmt(order.stop_loss, 8);
|
||||
document.getElementById("m-tp").innerText = order.take_profit_display || fmt(order.take_profit, 8);
|
||||
document.getElementById("m-rr").innerText = (order.rr_ratio === null || typeof order.rr_ratio === "undefined") ? "-" : `1:${Number(order.rr_ratio).toFixed(2)}`;
|
||||
document.getElementById("m-price").innerText = order.current_price_display || fmt(order.current_price, 8);
|
||||
const pnlEl = document.getElementById("m-pnl");
|
||||
pnlEl.innerText = `${fmt(order.float_pnl, 2)}U (${fmt(order.float_pct, 2)}%)`;
|
||||
pnlEl.style.color = Number(order.float_pnl || 0) > 0 ? "#4cd97f" : (Number(order.float_pnl || 0) < 0 ? "#ff6666" : "#d6deff");
|
||||
}
|
||||
|
||||
async function loadOrderKline(){
|
||||
if(!ensureChart()){ return; }
|
||||
const orderId = orderSelect.value;
|
||||
const timeframe = tfSelect.value;
|
||||
if(!orderId){ return; }
|
||||
statusEl.className = "status";
|
||||
statusEl.innerText = "加载中...";
|
||||
try{
|
||||
const resp = await fetch(`/api/order_kline?order_id=${encodeURIComponent(orderId)}&timeframe=${encodeURIComponent(timeframe)}`);
|
||||
const data = await resp.json();
|
||||
if(!resp.ok || !data.ok){ throw new Error(data.msg || "请求失败"); }
|
||||
const candles = Array.isArray(data.candles) ? data.candles : [];
|
||||
if(!candles.length){
|
||||
statusEl.className = "status err";
|
||||
statusEl.innerText = "暂无K线数据";
|
||||
return;
|
||||
}
|
||||
candleSeries.setData(candles);
|
||||
resetPriceLines();
|
||||
addLine(data.order.trigger_price, "成交价", "#42a5f5");
|
||||
addLine(data.order.stop_loss, "止损", "#ff6666");
|
||||
addLine(data.order.take_profit, "止盈", "#4cd97f");
|
||||
chart.timeScale().fitContent();
|
||||
paintOrder(data.order || {});
|
||||
updatedAtEl.innerText = data.updated_at || "--";
|
||||
statusEl.className = "status";
|
||||
statusEl.innerText = `已加载 ${candles.length} 根K线`;
|
||||
}catch(err){
|
||||
statusEl.className = "status err";
|
||||
statusEl.innerText = err && err.message ? err.message : "加载失败";
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("manual-refresh").addEventListener("click", loadOrderKline);
|
||||
orderSelect.addEventListener("change", loadOrderKline);
|
||||
tfSelect.addEventListener("change", loadOrderKline);
|
||||
loadOrderKline();
|
||||
setInterval(loadOrderKline, refreshMs);
|
||||
</script>
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,147 +0,0 @@
|
||||
# 使用说明
|
||||
|
||||
**本文件对应仓库:`crypto_monitor_gate`(Gate.io USDT 永续)。**
|
||||
功能、界面与 **Binance U 本位版**(目录 `crypto_monitor_binance`)基本一致,差异主要在 **`.env` 里交易所密钥与部分参数名**(`GATE_*` / `BINANCE_*`),文末有对照。
|
||||
|
||||
**更细的部署(SSH 代理、PM2、依赖安装)** 见同目录 **`部署文档.md`**。
|
||||
**关键位自动开仓的规则、RR、结案原因** 见 **`关键位自动下单说明.md`**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 它能做什么
|
||||
|
||||
面向个人盘面的 **Web 控制台**,主要能力包括:
|
||||
|
||||
| 模块 | 说明 |
|
||||
|------|------|
|
||||
| **关键位监控** | 录入上/下沿与类型,按 **5m 收线** 做硬条件过滤;符合条件后 **企业微信** 提醒,部分类型可 **自动市价开仓**(见第 4 节与专门文档)。 |
|
||||
| **实盘下单监控** | 手工填止损/止盈,**以损定仓** 市价开单,挂上条件止盈止损,并在页面跟踪浮盈亏、保本逻辑等。 |
|
||||
| **交易记录 / 复盘** | 平仓结果、盈亏、错过的单等归档与导出;可选 **AI 复盘**(见 [AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md))。 |
|
||||
| **策略交易** | 顶栏 `/strategy`:趋势回调 + 顺势加仓双栏;见 [策略交易说明.md](../策略交易说明.md)。 |
|
||||
|
||||
后台按 **`MONITOR_POLL_SECONDS`**(默认几秒)轮询行情与监控逻辑。**切勿**在未理解规则时同时运行两套程序共用一个实盘账户。
|
||||
|
||||
---
|
||||
|
||||
## 2. 运行前必须配置(`.env`)
|
||||
|
||||
首次在本目录执行 **`cp .env.example .env`**,再编辑 `.env`(`.env` 勿提交 Git;`git pull` 不会改你的 `.env`,升级前建议 `cp .env .env.backup.$(date +%Y%m%d)`)。
|
||||
|
||||
至少检查以下项(具体键名以 **`.env.example`** 为准):
|
||||
|
||||
| 类别 | 说明 |
|
||||
|------|------|
|
||||
| **登录网页** | `APP_PASSWORD`:打开站点后的登录口令。`FLASK_SECRET_KEY`:Session 密钥,请勿使用默认值。 |
|
||||
| **企业微信** | `WECHAT_WEBHOOK`:告警与关键位推送机器人的 Webhook。 |
|
||||
| **是否真下单** | `LIVE_TRADING_ENABLED=false`:**不会**向交易所发送开仓指令(适合测试流程)。改为 `true` 且密钥正确才会实盘。 |
|
||||
| **交易所 API** | **本仓库:** `GATE_API_KEY`、`GATE_API_SECRET`;合约相关见 `GATE_MARGIN_MODE`、`GATE_POS_MODE`、`GATE_TPSL_*` 等。**勿**把 `.env` 提交到 Git。 |
|
||||
| **关键位 RR / 止损外扩** | `KEY_AUTO_MIN_PLANNED_RR`、`KEY_STOP_OUTSIDE_BREAKOUT_PCT`(详见 `关键位自动下单说明.md`)。 |
|
||||
| **AI 复盘** | `AI_PROVIDER=openai`(默认)或 `ollama`;变量见 `.env.example` 与 [AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)。 |
|
||||
|
||||
网络不稳定时可为 Gate 配置 **`GATE_SOCKS_PROXY`** 等(见 **`部署文档.md`**)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 如何启动与登录
|
||||
|
||||
1. 按 **`部署文档.md`** 建好虚拟环境、安装依赖(如 `flask`、`requests`、`ccxt`、按需 `Pillow`、`PySocks` 等),配置好 `.env`。
|
||||
2. 启动 Flask 应用(本仓库可用 **`ecosystem.config.cjs`** 交给 PM2,或本地 `python app.py` / `flask run`,以你当前脚本为准)。
|
||||
3. 浏览器访问站点,打开 **`/login`**,使用 **`.env` 里的 `APP_PASSWORD`** 登录。
|
||||
|
||||
登录后顶栏:**关键位监控** | **实盘下单** | **策略交易**(`/strategy`)| **策略交易记录**(`/strategy/records`)| **交易记录与复盘** | **统计分析**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 关键位监控(顶栏「关键位监控」→ `/key_monitor`)
|
||||
|
||||
### 4.1 添加一条关键位
|
||||
|
||||
1. **币种**:如 `BTC` 或 `BTC/USDT`(会规范成内部符号)。
|
||||
2. **类型**(必选其一):
|
||||
|
||||
| 类型 | 行为摘要 |
|
||||
|------|----------|
|
||||
| **箱体突破** | 通过门控且计划 RR 达标 → **自动市价开仓**(需 `LIVE_TRADING_ENABLED=true` 且无其他持仓占位)。结案后本条从列表消失并记入历史。 |
|
||||
| **收敛突破** | 同上(自动开仓类)。 |
|
||||
| **关键阻力位** | **不自动开仓**;触发后 **发 1 次微信**,然后本条 **结案进历史**。 |
|
||||
| **关键支撑位** | 同上(仅提醒)。 |
|
||||
| **回调触价开仓** | **不挂交易所限价**;标记价回调触达 E 后 **下一轮询市价开仓**(RR 门槛同 `KEY_AUTO_MIN_PLANNED_RR`);有效期 **24h** |
|
||||
| **突破触价开仓** | **不挂交易所限价**;标记价 **穿越 E 立即市价开仓**;先触 SL/TP 侧失效;有效期 **24h** |
|
||||
|
||||
3. **方向**:做多 / 做空(触价开仓 / 箱体 / 收敛 / 斐波必选;阻力/支撑不选)。
|
||||
4. **价位**:箱体/收敛/阻力/支撑填 **上沿 / 下沿**;触价开仓填 **入场 E / 止损 SL / 止盈 TP**。
|
||||
|
||||
**限制:**
|
||||
活跃持仓数达到 **`MAX_ACTIVE_POSITIONS`**(默认 1)时,**不允许**再添加「**箱体突破** / **收敛突破**」;仍可添加「**关键阻力位 / 支撑位**」。
|
||||
若 **4h EMA55** 与你的方向逆势,页面会 **额外 Flash 提示**,**不阻挡**提交。
|
||||
|
||||
### 4.2 触发后会发生什么(简版)
|
||||
|
||||
- **箱体 / 收敛**:门控通过后计算计划 SL/TP 与 RR;不达标则 **微信说明 + `rr_insufficient` 结案**;达标则尝试 **市价开仓**,成功 **`auto_opened`**,失败 **`exchange_failed`**——均 **不重试同一关键位**。
|
||||
- **阻力 / 支撑**:仅 **单次推送** → **`key_level_alert_only`** 结案。
|
||||
|
||||
详细公式、结案字段、与企业微信文案口径见 **`关键位自动下单说明.md`**。
|
||||
|
||||
### 4.3 列表与历史
|
||||
|
||||
- 当前条目可 **删除**(会按规则记入历史的情形见页面说明)。
|
||||
- **关键位历史**:已结案记录;可配合导出链接(若有)做备份。
|
||||
|
||||
---
|
||||
|
||||
## 5. 实盘下单(顶栏「实盘下单」→ `/trade`)
|
||||
|
||||
用于 **自己点按钮** 开单:
|
||||
|
||||
- 持仓上限由 **`MAX_ACTIVE_POSITIONS`** 控制(默认 1,与关键位自动单共用)。
|
||||
- **人工开仓**时计划盈亏比不得低于 **`MANUAL_MIN_PLANNED_RR`**(默认 1.4:1),否则页面弹窗且后端拒绝。
|
||||
- 填写币种、方向、杠杆(可选)、止损/止盈(价格或百分比按表单说明)。
|
||||
- 勾选是否启用 **移动保本** 等行为以 `.env`/页面默认值为准。
|
||||
|
||||
平仓通过页面 **平仓**(或等价入口),会从交易所市价处理并更新记录。**删除/误操作可能造成真实盈亏**,请先确认环境与方向。
|
||||
|
||||
开仓成功后持仓卡片上会显示 **「来源」**:手工单一般为 **下单监控**;来自关键位自动单的为 **关键位监控**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 企业微信会看到什么
|
||||
|
||||
- 关键位:按类型与结案结果推送(RR 不足、下单失败、自动开仓成功、仅阻力支撑提醒等),**每条关键位结案路径原则上一条主推送**(详见 `关键位自动下单说明.md`)。
|
||||
- 手工开仓、平仓、部分异常也会在规则满足时推送(以代码与配置为准)。
|
||||
|
||||
若未配置 **`WECHAT_WEBHOOK`** 或网络失败,可能只是看不到推送,不代表逻辑未执行;要紧操作请以 **交易所端持仓与挂单** 为准核对。
|
||||
|
||||
---
|
||||
|
||||
## 7. 强烈建议的风险与运维习惯
|
||||
|
||||
1. **先用 `LIVE_TRADING_ENABLED=false`** 验证页面、录入、推送,再开小资金开实盘。
|
||||
2. **API 权限**:仅开所需合约权限;勿泄露密钥;定期轮换。
|
||||
3. **单进程控盘**:同一账户避免本程序与其他机器人 **重复开仓**。
|
||||
4. **自动备份**:服务器上执行 `bash scripts/install_backup_cron.sh`(每天北京时间 0:00 → `/root/backups`,保留 30 天);升级前也可 `bash scripts/backup_data.sh` 手动跑一次。
|
||||
5. **升级代码后**:启动时会跑 **数据库迁移**(如新列 `order_monitors.monitor_type`);首次启动关注一下日志或无报错页面。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见问题(简要)
|
||||
|
||||
| 现象 | 可自查 |
|
||||
|------|--------|
|
||||
| 关键位永远不触发 | 5m 门控是否全通过(页面门控摘要)、币种日成交量是否在规则内、`KLINE_TIMEFRAME`。 |
|
||||
| 有信号但不自动开仓 | `LIVE_TRADING_ENABLED`、`KEY_AUTO_MIN_PLANNED_RR`、计划 RR、是否已有持仓、API/余额报错(微信或日志)。 |
|
||||
| 加不了箱体/收敛 | 是否已有活跃持仓;先平仓或改用「阻力/支撑位」仅提醒。 |
|
||||
| 推送收不到 | `WECHAT_WEBHOOK`、企业微信机器人配额与网络。 |
|
||||
|
||||
---
|
||||
|
||||
## 9. Binance 版(`crypto_monitor_binance`)差异速查
|
||||
|
||||
| 项目 | Gate 本仓库 | Binance 版 |
|
||||
|------|-------------|------------|
|
||||
| API 变量 | `GATE_API_KEY`、`GATE_API_SECRET`、`GATE_*` | `BINANCE_API_KEY`、`BINANCE_API_SECRET`、`BINANCE_*` |
|
||||
| 实盘开关 | `LIVE_TRADING_ENABLED`(通用) | 同上 |
|
||||
| 止盈止损挂载路径 | `_gate_place_tp_sl_orders` 与 `GATE_TPSL_*` | `_binance_place_tp_sl_orders`(U 本位条件单) |
|
||||
| 资金显示舍入 | 以本仓库为准 | 与 **`FUNDS_DECIMALS`** 等一致 |
|
||||
| 专门文档 | **`关键位自动下单说明.md`**(各仓库有一份,开头标明交易所) | 同左 |
|
||||
|
||||
操作流程(登录、关键位四类、手工单、单仓)**两份程序一致**:换目录、换 `.env` 即可对照使用。
|
||||
@@ -1,143 +0,0 @@
|
||||
# 关键位监控说明(自动开仓 + 人工盯盘)
|
||||
|
||||
**适用:`crypto_monitor_gate`(Gate U 本位永续)**
|
||||
Binance / OKX 见各自目录下同名文档;共享逻辑在仓库根目录 `key_monitor_lib.py`。
|
||||
|
||||
本文档与 `.env`、`check_key_monitors`、`add_key`、`_key_hard_checks`、`_process_key_rs_level_alert` 一致。
|
||||
|
||||
---
|
||||
|
||||
## 一、监控类型总览
|
||||
|
||||
| 录入类型 | 录入时选方向 | 自动市价开仓 | 触发与结案 |
|
||||
|----------|--------------|--------------|------------|
|
||||
| **箱体突破** | **必选** 多/空 | **是**(门控 + RR) | 条件满足 → 开仓或 `rr_insufficient` / `exchange_failed` → **一次性删除** |
|
||||
| **收敛突破** | **必选** 多/空 | **是**(同上) | 同上 |
|
||||
| **关键阻力位** | **不选**(`direction=watch`) | **否** | 5m 收盘突破上/下沿 → 微信 **3 次** → `key_level_alert_done` |
|
||||
| **关键支撑位** | **不选** | **否** | 同上(与阻力位**相同规则**:填上沿+下沿,程序双向监控) |
|
||||
| 斐波回调 0.618 / 0.786 | 必选 | 限价挂单逻辑 | 见斐波说明(**不在下文展开**) |
|
||||
|
||||
**添加时(所有类型):** 品种须 **日成交量排名前 `KEY_DAILY_VOLUME_RANK_MAX`(默认 30)**;上沿 **>** 下沿。
|
||||
|
||||
---
|
||||
|
||||
## 二、关键阻力位 / 关键支撑位(人工盯盘)
|
||||
|
||||
### 2.1 录入
|
||||
|
||||
- 填写 **上沿 `upper`** 与 **下沿 `lower`**(程序同时监控两侧,**无法预先判定**做多还是做空)。
|
||||
- 页面 **不显示、不要求** 方向;库中 `direction` 初始为 `watch`,**首次突破后** 写入 `long`(向上突破上沿)或 `short`(向下突破下沿)。
|
||||
|
||||
### 2.2 触发(极简)
|
||||
|
||||
- 周期:**`KLINE_TIMEFRAME`(默认 5m)最近一根已闭合 K** 的 **收盘价**(非影线)。
|
||||
- **向上突破上沿:** `收盘 > upper` → 推断方向 **多 / 向上**,本次监控任务开始按节奏提醒。
|
||||
- **向下突破下沿:** `收盘 < lower` → 推断方向 **空 / 向下**,本次任务同样开始提醒。
|
||||
- **任一侧突破即结束本条监控周期**(不会在突破后再等待另一侧;上沿、下沿谁先满足用谁,同根 K 仅可能满足一侧)。
|
||||
|
||||
**不参与:** 量能、二确 K、越过幅度下限、日成交排名(运行时)、计划 RR、自动开仓。
|
||||
|
||||
### 2.3 微信提醒次数
|
||||
|
||||
| 配置 | 默认 | 含义 |
|
||||
|------|------|------|
|
||||
| `KEY_ALERT_MAX_TIMES` | `3` | 突破后最多推送 3 次 |
|
||||
| `KEY_ALERT_INTERVAL_MINUTES` | `5` | 相邻两次推送至少间隔 5 分钟 |
|
||||
|
||||
- 第 1 次:首次检测到突破的当次轮询(若已闭合 5m 满足条件)。
|
||||
- 第 2、3 次:仅按间隔推送(**不要求**价格仍在箱外)。
|
||||
- 第 3 次推送后:写入 `key_monitor_history`,`close_reason=**key_level_alert_done**`,从 `key_monitors` **删除**。
|
||||
|
||||
### 2.4 与箱体/收敛的区别
|
||||
|
||||
| 项目 | 阻力/支撑 | 箱体/收敛 |
|
||||
|------|-----------|-----------|
|
||||
| 方向 | 程序推断 | 人工选择 |
|
||||
| K 线根数 | 1 根闭合 5m | 2 根(突破 K + 确认 K) |
|
||||
| 提醒次数 | 3 次后结案 | 自动单:触发后 1 次业务推送并结案 |
|
||||
|
||||
---
|
||||
|
||||
## 三、箱体突破 / 收敛突破(自动开仓)
|
||||
|
||||
### 3.1 K 线结构(默认索引)
|
||||
|
||||
| 角色 | 环境变量 | 默认 | 含义 |
|
||||
|------|----------|------|------|
|
||||
| 突破 K | `KEY_CONFIRM_BREAKOUT_BAR` | `-2` | 倒数第 2 根闭合 K |
|
||||
| 确认 K | `KEY_CONFIRM_BAR` | `-1` | 倒数第 1 根闭合 K |
|
||||
|
||||
### 3.2 硬门控(须全部通过)
|
||||
|
||||
1. **有效突破(收盘越界)**
|
||||
- 多:`突破 K 收盘 > upper`
|
||||
- 空:`突破 K 收盘 < lower`
|
||||
|
||||
2. **突破越过幅度(仅下限)**
|
||||
- 多:`(突破 K 收盘 − upper) / upper × 100 > KEY_BREAKOUT_AMP_MIN_PCT`(默认 **0.03%**)
|
||||
- 空:`(lower − 突破 K 收盘) / lower × 100 >` 同上
|
||||
- **无上限**;突破过猛由 **计划 RR** 过滤。
|
||||
- **不再**使用 K 线实体占开盘价比例;`KEY_BREAKOUT_AMP_MAX_PCT` **已不参与门控**。
|
||||
|
||||
3. **确认 K 不进箱体**
|
||||
- 多:确认 K 收盘 **`> upper`**(不得在 `[lower, upper]` 内)
|
||||
- 空:确认 K 收盘 **`< lower`**
|
||||
|
||||
4. **量能:** 突破 K 成交量 > 前 `KEY_VOLUME_MA_BARS`(默认 20)根均量 × `KEY_VOLUME_RATIO_MIN`(默认 1.3)
|
||||
|
||||
5. **日成交量排名:** 运行时仍须前 `KEY_DAILY_VOLUME_RANK_MAX`(默认 30)
|
||||
|
||||
6. **计划 RR(最后经济门控):** 按确认 K 收盘 **E** 计算 SL/TP 后,`RR` **严格大于** `KEY_AUTO_MIN_PLANNED_RR`(默认 1.5)才市价开仓
|
||||
|
||||
### 3.3 止损 / 止盈(确认 K 收盘为 E)
|
||||
|
||||
箱体高 **H = |upper − lower|**。止损锚在 **突破 K 极值** 外侧:
|
||||
|
||||
| 方向 | 止损(标准/趋势方案) |
|
||||
|------|------------------------|
|
||||
| 多 | 突破 K **最低价** × (1 − `KEY_STOP_OUTSIDE_BREAKOUT_PCT`%) |
|
||||
| 空 | 突破 K **最高价** × (1 + `KEY_STOP_OUTSIDE_BREAKOUT_PCT`%) |
|
||||
|
||||
止盈方案见下表(与改版前一致):
|
||||
|
||||
| 方案 | `sl_tp_mode` | 多:SL / TP | 空:SL / TP |
|
||||
|------|--------------|-------------|-------------|
|
||||
| 标准突破 | `standard` | 突破 K 低外侧% / **E+H** | 突破 K 高外侧% / **E−H** |
|
||||
| 箱体 1R·止盈 1.5H | `box_1p5` | **E−H** / **E+1.5×H** | **E+H** / **E−1.5×H** |
|
||||
| 趋势单·自填止盈 | `trend_manual` | 突破 K 低 × (1−`KEY_TREND_STOP_OUTSIDE_PCT`%) / **录入止盈** | 突破 K 高外侧% / **录入止盈** |
|
||||
|
||||
### 3.4 一次性结案(`close_reason`)
|
||||
|
||||
| `close_reason` | 含义 |
|
||||
|----------------|------|
|
||||
| `box_opposite_break` | 标记价先突破反向边界(多:≤下沿;空:≥上沿) |
|
||||
| `rr_insufficient` | 门控通过但 RR 不达标或 SL/TP 几何无效 |
|
||||
| `exchange_failed` | RR 达标但实盘/交易所等原因未开仓 |
|
||||
| `auto_opened` | RR 达标且市价开仓成功 |
|
||||
| `key_level_alert_done` | 阻力/支撑 **3 次提醒** 完成 |
|
||||
|
||||
---
|
||||
|
||||
## 四、环境与参数(`.env` 摘要)
|
||||
|
||||
| 变量 | 箱体/收敛 | 阻力/支撑 |
|
||||
|------|-----------|-----------|
|
||||
| `KEY_BREAKOUT_AMP_MIN_PCT` | 突破越过下限(默认 0.03) | 不用 |
|
||||
| `KEY_BREAKOUT_AMP_MAX_PCT` | **已废弃门控** | 不用 |
|
||||
| `KEY_VOLUME_*` / `KEY_CONFIRM_*` | 用 | 不用 |
|
||||
| `KEY_AUTO_MIN_PLANNED_RR` | 用 | 不用 |
|
||||
| `KEY_ALERT_MAX_TIMES` / `KEY_ALERT_INTERVAL_MINUTES` | 不用 | 用(默认 3 次 / 5 分钟) |
|
||||
| `KEY_DAILY_VOLUME_RANK_MAX` | 添加时 + 运行时 | **仅添加时** |
|
||||
|
||||
---
|
||||
|
||||
## 五、相关代码
|
||||
|
||||
| 说明 | 位置 |
|
||||
|------|------|
|
||||
| 共享判定 | `key_monitor_lib.py` |
|
||||
| 主循环 | `check_key_monitors` |
|
||||
| 自动门控 | `_key_hard_checks` |
|
||||
| 阻力/支撑提醒 | `_process_key_rs_level_alert` |
|
||||
| 录入 | `add_key` |
|
||||
| 开仓 | `_market_open_for_key_monitor` |
|
||||
@@ -1,148 +0,0 @@
|
||||
# 界面与风控更新说明(Gate 实例)
|
||||
|
||||
## 顶栏导航(4 项)
|
||||
|
||||
| 顺序 | 名称 | 路由 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 1 | 关键位监控 | `/key_monitor` | 关键位添加、实时门控、历史 |
|
||||
| 2 | 实盘下单 | `/trade` | 人工开仓、划转、实时持仓(**默认首页** `/` → `/trade`) |
|
||||
| 3 | 交易记录与复盘 | `/records` | 交易记录、复盘表单、AI 历史(受顶栏 UTC 时间窗筛选) |
|
||||
| 4 | 统计分析 | `/stats` | 按北京时间交易日切日 + 分品类统计块 |
|
||||
|
||||
## 关键位监控页
|
||||
|
||||
- 标题去掉「5m」;规则条从 `.env` 读取(周期、确认K、量能、自动开仓盈亏比、日成交量排名)。
|
||||
- 左列:活跃关键位,**pos-card** 样式展示现价/距上沿/距下沿/门控。
|
||||
- 右列:关键位历史(失效/结案),与左列等高滚动;**受顶栏 UTC 列表时间窗筛选**(默认 UTC 当日)。
|
||||
- 监控类型新增:**斐波回调0.618**、**斐波回调0.786**(与 Binance 主站同一套规则,计算逻辑见仓库根目录 `fib_key_monitor_lib.py`)。
|
||||
|
||||
### 斐波关键位监控(方案 A:交易所限价)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 同币互斥 | 每个币种只能有一条斐波监控(0.618 与 0.786 不可并存) |
|
||||
| 上下沿 | 上沿 **H**、下沿 **L**(须 H > L) |
|
||||
| 挂单价 E | **做多** `E = H − ratio × (H − L)`(自 H 向下回撤);**做空** `E = L + ratio × (H − L)`(自 L 向上反弹) |
|
||||
| 做多 | 限价 @ E,止损 L,止盈 H |
|
||||
| 做空 | 限价 @ E,止损 H,止盈 L |
|
||||
| 添加后 | **立即**在 Gate 挂限价单;卡片显示 **挂E**、限价单 ID |
|
||||
| 失效 | 以**标记价**判断:做多且标记价 ≥ H、做空且标记价 ≤ L,且限价**未成交** → 撤销该限价单并结案(不写历史开仓) |
|
||||
| 成交后 | 按仓位挂交易所 TP/SL → 写入 **实盘下单监控**(`monitor_type=关键位监控`,`key_signal_type=斐波回调0.618/0.786`)→ 从关键位列表移除 |
|
||||
| 撤单 | 仅撤本条斐波的 `fib_limit_order_id`,**不会** `cancel_all`,避免误伤其他委托 |
|
||||
| 盈亏比 | 计划 RR 须 > `KEY_AUTO_MIN_PLANNED_RR`(与箱体/收敛一致);0.618 理论约 1.6:1,0.786 约 3.7:1 |
|
||||
| 日成交量 | 与箱体/收敛相同,须在前 `KEY_DAILY_VOLUME_RANK_MAX` 名内方可添加 |
|
||||
|
||||
后台轮询:`check_fib_key_monitors()`(标记价失效 / 成交检测);箱体/收敛仍走 `check_key_monitors()`,互不干扰。
|
||||
|
||||
手动删除关键位时,若斐波限价尚未成交,会先撤交易所限价再删库记录。
|
||||
|
||||
### 箱体 / 收敛自动开仓(来源标注)
|
||||
|
||||
- 自动开仓写入 `order_monitors.key_signal_type`:`箱体突破` 或 `收敛突破`。
|
||||
- 持仓卡片、交易记录列表会显示「来源 · 信号类型」。
|
||||
|
||||
## 列表时间窗(UTC,全站顶栏)
|
||||
|
||||
共用模块:仓库根目录 `history_window_lib.py`(Gate / Binance 主站一致)。
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 默认 | **UTC 当日**(`win_preset=utc_today`,从 UTC 0:00 至当前时刻) |
|
||||
| 可选 | 近 24 小时、近 7 天、自定义起止(UTC,`datetime-local`) |
|
||||
| 作用范围 | 关键位历史、交易记录列表、复盘记录 API、AI 历史 API、导出「交易记录」「关键位历史」 |
|
||||
| 与统计的关系 | **仅影响列表/导出**;**统计分析页仍按北京时间 `TRADING_DAY_RESET_HOUR`(默认 8:00)切交易日** |
|
||||
| 库内时间 | DB 存北京时间字符串;后端用 `utc_window_to_bj_sql_strings()` 换算后再 SQL 比较 |
|
||||
| 切换方式 | 顶栏「列表筛选(UTC)」→ 选预设 → **应用**(保留当前路由,如 `/records?win_preset=…`) |
|
||||
|
||||
查询参数示例:
|
||||
|
||||
- `?win_preset=utc_today`
|
||||
- `?win_preset=utc_last24h` / `utc_last7d`
|
||||
- `?win_preset=custom&from_utc=2026-05-18 00:00:00&to_utc=2026-05-19 12:00:00`
|
||||
|
||||
## 交易记录与复盘
|
||||
|
||||
- 平仓记录可同步交易所已实现盈亏(Gate 仓位历史等);列表盈亏列优先显示交易所数据,标注 **所** / **估**。
|
||||
- 记录页提供 **立即同步**(`POST /api/sync_exchange_pnl`),用于补全或刷新 `exchange_realized_pnl` 等字段。
|
||||
- 未做人工复盘时,展示以交易所盈亏为准(有同步数据时)。
|
||||
- **列表默认只显示当前 UTC 时间窗内**的记录(见上节);导出 CSV 同步该时间窗。
|
||||
- 表头 **「止损(开仓)」**:展示开仓快照 `initial_stop_loss`(无则回退 `stop_loss`);核对/复盘仍可用有效止损字段。
|
||||
- 平仓写入 `trade_records` 时:`stop_loss` 与 `initial_stop_loss` 均写入**开仓时止损快照**;`key_signal_type` 保留箱体/收敛/斐波来源(`fib_key_monitor_lib.key_signal_type_for_trade_record`)。
|
||||
- **开仓类型**(`entry_reason`):机器单平仓入库时,若未手填,按 `key_signal_type` 自动映射(见下表);列表/导出「开仓类型」列 = 复盘核对值优先,否则入库值,否则按信号映射。
|
||||
|
||||
| `key_signal_type` | 自动写入的 `entry_reason` |
|
||||
|-------------------|---------------------------|
|
||||
| 箱体突破 | 关键位箱体突破 |
|
||||
| 收敛突破 | 关键位收敛突破 |
|
||||
| 斐波回调0.618 | 关键位斐波0.618 |
|
||||
| 斐波回调0.786 | 关键位斐波0.786 |
|
||||
|
||||
- 复盘表单 **开仓类型** 下拉新增上述四条固定文案(与趋势/波段类并列)。
|
||||
- 复盘 **离场触发** 新增 **「止盈」**;从交易记录「填入复盘」时,若结果为「止盈/保本止盈/移动止盈/止损/手动平仓」会自动选中对应触发项,并按 `key_signal_type` 预填开仓类型。
|
||||
- 勾选「保存时自动生成多周期 K 线图」时:以 **平仓时间** 为锚点,各周期向前约 `ORDER_CHART_LIMIT`(默认 100)根 K 线(`_fetch_ohlcv_ending_at`),不再固定拉「最近 100 根」。
|
||||
- `/api/journals`、`/api/reviews` 支持同一时间窗 query,与列表一致。
|
||||
|
||||
### 导出(交易记录 v3)
|
||||
|
||||
- 文件名:`trade_records_v3_YYYYMMDD.csv`
|
||||
- 相对 v2 增加:`key_signal_type`、`initial_stop_loss`(及开仓快照列)、`planned_rr`、`actual_rr`、`risk_amount`、交易所盈亏与时间字段等;末列「开仓类型」为有效展示文案。
|
||||
- 「关键位历史」导出同样受 UTC 时间窗限制。
|
||||
|
||||
## 实盘下单页
|
||||
|
||||
- 左列:实盘下单监控(表单、划转、规则)。
|
||||
- 右列:实时持仓(独立模块)。
|
||||
- **人工开仓门控**:计划盈亏比 < `MANUAL_MIN_PLANNED_RR`(默认 **1.4**)时前端弹窗 + 后端拒绝。
|
||||
- **移动保本**(勾选启用):监控轮询达到触发 RR 后,止损阶梯上移时**同步交易所**——调用与页面「挂止盈止损」相同的 **先撤后挂**(`replace_active_monitor_tpsl_on_exchange`:撤该合约全部 TP/SL 条件单 → 按新止损 + 原止盈重挂)。仅交易所成功后才写库;失败发企业微信告警,本地止损不变。未配置实盘 API 时仍只更新本地(与旧行为一致)。
|
||||
|
||||
## 统计分析页(`/stats`)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 切日 | **北京时间**;交易日边界 = 每日 `TRADING_DAY_RESET_HOUR:00`(`.env` 默认 **8**) |
|
||||
| 品类下拉 | 页顶 **「统计品类」** 下拉切换(默认「全部交易」):全部交易、下单监控、关键位箱体突破、关键位收敛结构、关键位斐波0.618、关键位斐波0.786;一次只显示所选品类的日/周/月 |
|
||||
| URL | 切换后写入 `stats_segment=`(如 `all`、`manual`、`key_box`、`key_conv`、`key_fib618`、`key_fib786`),刷新 `/stats` 可保持选项 |
|
||||
| 每块指标 | 日 / 周 / 月:开单次数、平仓笔数、胜率、净盈亏、回撤、连续亏损等(与原口径一致) |
|
||||
| 开单次数 | 人工块:`monitor_type=下单监控` 且无 `key_signal_type`;关键位块:按 `order_monitors.key_signal_type` 计数 |
|
||||
| 不受 UTC 窗影响 | 统计始终基于库内全部已平仓记录,按北京交易日归类,**不**随顶栏 UTC 列表窗切换 |
|
||||
|
||||
## 持仓与计仓
|
||||
|
||||
- `MAX_ACTIVE_POSITIONS` 默认 **1**(可在 `.env` 调大)。
|
||||
- 关键位自动开仓:在已有持仓时,若 `KEY_SIZING_USE_ZERO_POSITION_SNAPSHOT=true`,按**首笔开仓前**交易账户资金快照计仓(`trading_sessions.key_sizing_capital_snapshot`)。
|
||||
|
||||
## 配置
|
||||
|
||||
详见 `.env.example` 中「关键位门控」「交易执行 / 人工风控」注释段。Gate 专用项(`GATE_*`、止盈止损触发等)保持原有段落不变。
|
||||
|
||||
## 自动备份(服务器)
|
||||
|
||||
- 脚本:`scripts/backup_data.sh`(`crypto.db` + `static/images`)
|
||||
- 定时:`scripts/install_backup_cron.sh` → 每天 **北京时间 0:00**,目录 **`/root/backups/<实例名>/YYYY-MM-DD/`**,保留 **30** 天
|
||||
- 详见 `部署文档.md` 第 5.4 节(自动备份)
|
||||
|
||||
## 数据库(启动时自动迁移)
|
||||
|
||||
`key_monitors` 新增斐波字段(示例):`fib_limit_order_id`、`fib_entry_price`、`fib_stop_loss`、`fib_take_profit`、`fib_order_amount`、`fib_margin_capital`、`fib_leverage`。
|
||||
|
||||
`trade_records` / `order_monitors` 新增或沿用:`key_signal_type`、`exchange_realized_pnl`、`exchange_opened_at`、`exchange_closed_at`、`exchange_sync_key`、`entry_reason`、`reviewed_entry_reason`、`initial_stop_loss`。
|
||||
|
||||
**历史数据**:本次**不做**旧记录的批量回填(`entry_reason` / `initial_stop_loss` / `key_signal_type` 等);仅**新产生**的平仓与复盘按新逻辑写入。旧行展示可回退已有字段。
|
||||
|
||||
## 涉及文件(便于排查)
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `history_window_lib.py` | UTC 时间窗解析与转北京时间 SQL 字符串 |
|
||||
| `fib_key_monitor_lib.py` | 斐波计算、`KEY_ENTRY_REASON_BY_SIGNAL`、`entry_reason_from_key_signal` |
|
||||
| `crypto_monitor_gate/app.py` | 列表筛选、统计分块、导出 v3、复盘 K 线锚点、入库逻辑 |
|
||||
| `crypto_monitor_gate/templates/index.html` | 顶栏时间窗、统计分块 UI、止损(开仓)列、复盘预填 |
|
||||
|
||||
## 升级步骤
|
||||
|
||||
1. `git pull` 后对比 `.env.example`,把新增变量合并进本地 `.env`。
|
||||
2. 在 VPS 上为 Binance / Gate / Gate Bot **各执行一次** `bash scripts/install_backup_cron.sh`(若尚未安装)。
|
||||
3. 重启 Gate 实例服务(如 `pm2 restart crypto_gate`);首次启动会自动 `ALTER TABLE` 缺列(斐波、交易所盈亏、`entry_reason` 等)。
|
||||
4. 浏览器强刷(Ctrl+F5)避免旧版 `index.html` 缓存。
|
||||
5. 打开任意页确认顶栏出现 **「列表筛选(UTC)」**;`/stats` 可见分品类统计与「北京 8:00 切日」说明。
|
||||
6. 建议在测试币上先添加一条斐波监控,确认:限价已挂出、标记价失效会撤单、成交后出现持仓监控且 TP/SL 已挂上;平仓后交易记录止损(开仓)与开仓类型是否正确。
|
||||
@@ -1,339 +0,0 @@
|
||||
# `crypto_monitor_gate_bot` 部署指南:SSH SOCKS + Gate.io + PM2(Ubuntu)
|
||||
|
||||
Ubuntu 环境总览见 **[docs/ubuntu-server.md](../docs/ubuntu-server.md)**。
|
||||
|
||||
本文面向:**在本机运行本项目**,但 **直连 Gate.io API 不稳定或被重置** 的场景。思路是:
|
||||
|
||||
- 本机用 `ssh -D` 做动态转发,把 **SOCKS5 出口**放到能正常访问 Gate 的机器(常见为一台境外 VPS)
|
||||
- 项目在 `.env` 中设置 **`GATE_SOCKS_PROXY=socks5h://127.0.0.1:1080`**(或你实际端口),`ccxt` 经 SOCKS 访问交易所
|
||||
- **SSH 隧道**:用 `ssh -D` 在本机常驻(可用 **tmux** 或 **autossh** 保持连接),**不要** 把 `ssh` 交给 PM2
|
||||
- 使用 **PM2** 仅托管 **Flask 应用**;仓库根目录 **`ecosystem.config.cjs`** 只定义 `crypto-monitor-gate`
|
||||
|
||||
> 安全提醒:不要把 `.env`、私钥 `.pem`、Gate API Key 提交到 Git;下文只用占位符。
|
||||
|
||||
---
|
||||
|
||||
## 0. 你需要准备的东西
|
||||
|
||||
- 一台 **Ubuntu**(或同类 Linux)运行项目的机器(下文称「本机」)
|
||||
- 一台可 SSH 登录、且 **能正常访问 Gate.io API** 的 VPS(示例:`HostName` 填你的服务器 IP,用户如 `root`)
|
||||
- SSH:**私钥登录**(推荐,便于隧道脚本无人值守)
|
||||
- 本机已安装:`python3`、`python3-venv`、`pip`、`curl`、`ssh`、`git`(可选)、`node` + `npm`(安装 PM2)
|
||||
|
||||
---
|
||||
|
||||
## 1. 获取代码与目录
|
||||
|
||||
将包含 `app.py` 的项目放到固定目录,例如:
|
||||
|
||||
```bash
|
||||
mkdir -p /opt/crypto_monitor
|
||||
cd /opt/crypto_monitor
|
||||
git clone https://git.bz121.com/dekun/crypto_monitor.git
|
||||
cd crypto_monitor/crypto_monitor_gate_bot
|
||||
```
|
||||
|
||||
下文用 **`/opt/crypto_monitor/crypto_monitor_gate_bot`** 仅为示例,请换成你的实际绝对路径。
|
||||
|
||||
拉取代码后,若目录下尚无 `.env`:
|
||||
|
||||
```bash
|
||||
cp -n .env.example .env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 配置 SSH 私钥与 `~/.ssh/config`
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.ssh
|
||||
chmod 700 ~/.ssh
|
||||
# 私钥示例:~/.ssh/vps1.pem
|
||||
chmod 600 ~/.ssh/vps1.pem
|
||||
```
|
||||
|
||||
编辑 `~/.ssh/config`(示例别名 **`gate-vps`**,与你手工启动 `ssh -D ... gate-vps` 一致即可):
|
||||
|
||||
```sshconfig
|
||||
Host gate-vps
|
||||
HostName 你的_VPS_IP
|
||||
User root
|
||||
IdentityFile ~/.ssh/vps1.pem
|
||||
IdentitiesOnly yes
|
||||
ServerAliveInterval 30
|
||||
ServerAliveCountMax 3
|
||||
ExitOnForwardFailure yes
|
||||
BatchMode yes
|
||||
```
|
||||
|
||||
测试:
|
||||
|
||||
```bash
|
||||
ssh gate-vps true
|
||||
```
|
||||
|
||||
> 若尚未完全改为密钥登录,可暂时注释 `BatchMode yes`,调试完成后再打开。
|
||||
|
||||
---
|
||||
|
||||
## 3. 手工验证:SSH SOCKS + Gate API
|
||||
|
||||
### 3.1 本地 SOCKS(示例端口 1080)
|
||||
|
||||
```bash
|
||||
ssh -N -D 127.0.0.1:1080 gate-vps
|
||||
```
|
||||
|
||||
保持运行,另开终端继续。
|
||||
|
||||
### 3.2 验证经 SOCKS 可访问 Gate
|
||||
|
||||
```bash
|
||||
curl -4 -sS --max-time 15 --proxy socks5h://127.0.0.1:1080 https://api.gateio.ws/api/v4/spot/time
|
||||
```
|
||||
|
||||
应返回 JSON(含服务器时间字段)。若此处失败,**不要先启动应用**:先修隧道或 VPS 出站。
|
||||
|
||||
---
|
||||
|
||||
## 4. Python 虚拟环境
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
python -m pip install -U pip
|
||||
pip install flask requests ccxt werkzeug PySocks Pillow
|
||||
```
|
||||
|
||||
走 SOCKS 时 **必须** 安装 **`PySocks`**,否则易出现代理相关报错。
|
||||
|
||||
可选:
|
||||
|
||||
```bash
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 配置环境变量(`.env.example` → `.env`)
|
||||
|
||||
| 文件 | 是否进 Git | 说明 |
|
||||
|------|------------|------|
|
||||
| **`.env.example`** | ✅ 是 | 变量模板与注释,可随 `git pull` 更新 |
|
||||
| **`.env`** | ❌ 否 | 本机真实配置;`app.py` **只读此文件** |
|
||||
|
||||
### 5.1 首次配置
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
|
||||
cp -n .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
### 5.2 备份与 `git pull`
|
||||
|
||||
- **`.env` 不在 Git 中**:`git pull` **不会**覆盖本地 `.env`。
|
||||
- 远端若更新 **`.env.example`**,pull 后请**手动**把新增变量补进你的 `.env`。
|
||||
- **升级前备份**:`cp .env .env.backup.$(date +%Y%m%d)`;恢复:`cp .env.backup.YYYYMMDD .env`。
|
||||
- **换机**:`scp` 复制 `.env`,或新机 `cp .env.example .env` 后重填。
|
||||
|
||||
### 5.3 AI 复盘与模型(可选)
|
||||
|
||||
共用根目录 **`ai_client.py`**(`PYTHONPATH=..`)。`.env` 默认 **`AI_PROVIDER=openai`** + `OPENAI_API_BASE` / `OPENAI_API_KEY` / `OPENAI_MODEL`;或 **`ollama`** + `OLLAMA_API` / `AI_MODEL`。详见 **[AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)**。
|
||||
|
||||
### 5.4 自动备份(数据库 + 复盘图片)
|
||||
|
||||
每天 **北京时间 0:00** 备份到 **`/root/backups`**,保留 **30 天**(`crypto.db` + `static/images`)。
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
chmod +x scripts/backup_data.sh scripts/install_backup_cron.sh
|
||||
bash scripts/install_backup_cron.sh
|
||||
bash scripts/backup_data.sh # 试跑
|
||||
```
|
||||
|
||||
备份目录:`/root/backups/crypto_monitor_gate_bot/YYYY-MM-DD/`。与 Binance / Gate 实例规则相同,详见 `crypto_monitor_binance/部署文档.md` 第 5.4 节(恢复步骤、可选 `.env` 变量)。
|
||||
|
||||
若服务器同时跑 **binance、gate、gate_bot** 三个实例,请在**各自项目目录**各执行一次 `install_backup_cron.sh`。
|
||||
|
||||
### 5.4 必填项检查(Gate + 代理)
|
||||
|
||||
与交易所相关的变量必须是 **Gate** 前缀(**不要**再写 OKX 变量,否则代理不会生效、密钥也不会被识别)。至少确认:
|
||||
|
||||
```env
|
||||
APP_HOST=127.0.0.1
|
||||
APP_PORT=5000
|
||||
|
||||
# 实盘(按需)
|
||||
LIVE_TRADING_ENABLED=false
|
||||
GATE_API_KEY=你的_Key
|
||||
GATE_API_SECRET=你的_Secret
|
||||
|
||||
# 经本机 SSH 动态转发访问 Gate(端口与隧道一致)
|
||||
GATE_SOCKS_PROXY=socks5h://127.0.0.1:1080
|
||||
|
||||
# 若不用 SOCKS,可改用 HTTP 代理(一般二选一)
|
||||
# GATE_HTTP_PROXY=http://127.0.0.1:7890
|
||||
# GATE_HTTPS_PROXY=http://127.0.0.1:7890
|
||||
```
|
||||
|
||||
说明:**推荐 `socks5h://`**,由 SOCKS 端解析域名,与 `curl --proxy socks5h://...` 行为一致。
|
||||
|
||||
### 5.4 趋势回调策略(可选)
|
||||
|
||||
若使用「交易执行」页的 **趋势回调** 计划:
|
||||
|
||||
- 详细规则见项目根目录 **`趋势回调策略说明.md`**。
|
||||
- **两阶段**:先「生成预览」(默认 **120 秒**内有效),再「确认执行」;执行时若可用余额与预览快照偏差超过 **5%** 会拒绝(可调 `.env`)。
|
||||
- 补仓档位数默认 **5**,预览有效期与余额偏差阈值可在 `.env` 覆盖:
|
||||
|
||||
```env
|
||||
TREND_PULLBACK_DCA_LEGS=5
|
||||
TREND_PULLBACK_PREVIEW_TTL_SECONDS=120
|
||||
TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT=5
|
||||
```
|
||||
|
||||
- **生成预览**与**确认执行**时都会读取 **Gate 永续账户 USDT 可用余额**;请尽量使用 **单独子账户** 承载策略资金。
|
||||
|
||||
**界面与对账(与策略说明 3.4–3.5 节一致)**
|
||||
|
||||
- 页顶 **计划历史**:仅 **已结束** 的趋势计划(不含未执行预览);可 **删除** 计划行,并删除 `trend_plan_id` 关联的「趋势回调」`trade_records`(新数据;旧行无 `trend_plan_id` 不级联)。
|
||||
- **运行中计划**展示交易所 **未实现盈亏**(浮盈亏)。
|
||||
- **交易记录**:趋势单在配置 API Key 后,打开「交易执行 / 交易记录」页会按节流(约 **25 秒**内同进程最多一次)拉取 Gate **平仓历史**,回填 **`exchange_realized_pnl`** 等;列表展示优先用交易所口径(见策略说明)。
|
||||
|
||||
**与交易所对齐的可选环境变量**
|
||||
|
||||
```env
|
||||
# 平仓历史同步起点:北京日期 YYYY-MM-DD 的 0 点(与 APP_TIMEZONE 一致);留空则从近 90 天拉取
|
||||
# EXCHANGE_POSITION_SYNC_FROM_BJ=2026-05-14
|
||||
# EXCHANGE_POSITION_HISTORY_LIMIT=200
|
||||
```
|
||||
|
||||
说明:同步 **只读** 交易所接口,**不要求** `LIVE_TRADING_ENABLED=true`;无 Key 时不拉取,界面仍可用(浮盈亏可能为「—」、交易记录仍为本地「估」)。
|
||||
|
||||
**交易记录 CSV**:导出为 **v3**,含 `trend_plan_id` 与交易所对齐列(详见策略说明数据库一节)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 手工启动 Flask(验证)
|
||||
|
||||
1. SOCKS 已监听 `127.0.0.1:1080`
|
||||
2. 已 `source .venv/bin/activate`
|
||||
3. `.env` 已含 `GATE_SOCKS_PROXY`
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
source .venv/bin/activate
|
||||
python app.py
|
||||
```
|
||||
|
||||
浏览器访问:`http://127.0.0.1:5000`(或你在 `.env` 中的端口)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 安装 PM2
|
||||
|
||||
```bash
|
||||
sudo npm i -g pm2
|
||||
pm2 -v
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. PM2:使用仓库内 `ecosystem.config.cjs`(推荐)
|
||||
|
||||
在项目根目录:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
pm2 start ecosystem.config.cjs
|
||||
pm2 status
|
||||
pm2 logs --lines 200
|
||||
```
|
||||
|
||||
默认只启动 **`crypto-monitor-gate`**(`.venv/bin/python app.py`)。
|
||||
|
||||
### 本机已可直连 Gate、不需要隧道时
|
||||
|
||||
`.env` 里应 **去掉或留空** `GATE_SOCKS_PROXY`(除非仍要走别的代理),再 `pm2 start ecosystem.config.cjs`。
|
||||
|
||||
### 开机自启
|
||||
|
||||
```bash
|
||||
pm2 save
|
||||
pm2 startup
|
||||
# 按屏幕提示执行一条 sudo 命令
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 等价手工命令(不使用 ecosystem 文件时)
|
||||
|
||||
### 9.1 SSH SOCKS(自行后台常驻,不推荐用 PM2)
|
||||
|
||||
示例(前台调试;生产请用 **PM2**,见本文与 [docs/ubuntu-server.md](../docs/ubuntu-server.md)):
|
||||
|
||||
```bash
|
||||
ssh -N -D 127.0.0.1:1080 gate-vps \
|
||||
-o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
|
||||
-o ExitOnForwardFailure=yes
|
||||
```
|
||||
|
||||
### 9.2 Flask
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot
|
||||
pm2 start /opt/crypto_monitor/crypto_monitor_gate_bot/.venv/bin/python --name crypto-monitor-gate -- \
|
||||
/opt/crypto_monitor/crypto_monitor_gate_bot/app.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 交易所「连接不上」排查清单
|
||||
|
||||
1. **`.env` 是否为 Gate 变量**:必须是 `GATE_SOCKS_PROXY` / `GATE_API_KEY` / `GATE_API_SECRET`,不是 OKX。
|
||||
2. **隧道是否在本机端口监听**(若配置了 `GATE_SOCKS_PROXY`):
|
||||
```bash
|
||||
ss -lntp | grep 1080 || true
|
||||
```
|
||||
3. **curl 复测 Gate**(与第 3.2 节相同);curl 不通则应用也不会通。
|
||||
4. **PySocks**:`pip show PySocks`,缺失则 `pip install PySocks`。
|
||||
5. **SSH 隧道连不上**:检查私钥权限、`~/.ssh/config`、VPS 出站与端口是否与 `.env` 一致。
|
||||
6. **启动顺序**:先保证 SOCKS 已监听,再 `pm2 start` 应用(或重启应用)。
|
||||
|
||||
---
|
||||
|
||||
## 11. 推荐启动顺序(习惯)
|
||||
|
||||
1. 若走代理:先启动并确认 SSH SOCKS 已监听,再 `curl --proxy socks5h://127.0.0.1:1080 https://api.gateio.ws/api/v4/spot/time` 成功
|
||||
2. `pm2 start ecosystem.config.cjs`
|
||||
3. 再确认页面与余额等接口正常
|
||||
|
||||
---
|
||||
|
||||
## 12. 免责声明
|
||||
|
||||
交易所有合规与地区政策要求。请确保使用方式符合当地法律法规与交易所条款。本文仅描述网络与工程部署路径。
|
||||
|
||||
---
|
||||
|
||||
## 附录:数据库标签修复脚本 `scripts/fix_breakeven_labels.py`
|
||||
|
||||
在 Ubuntu 上:
|
||||
|
||||
1)预览(不写库):
|
||||
|
||||
```bash
|
||||
python scripts/fix_breakeven_labels.py --db ./crypto.db --dry-run
|
||||
```
|
||||
|
||||
2)确认后执行:
|
||||
|
||||
```bash
|
||||
python scripts/fix_breakeven_labels.py --db ./crypto.db --apply
|
||||
```
|
||||
|
||||
默认修复条件:`monitor_type='下单监控'` 且 `result='止损'` 且 `pnl_amount > 0` → 改为 `result='保本止盈'`。
|
||||
@@ -131,6 +131,9 @@ from lib.key_monitor.trigger_entry_key_monitor_lib import (
|
||||
TRIGGER_ENTRY_VALIDITY_HOURS,
|
||||
check_trigger_entry_intent_limit,
|
||||
count_pending_trigger_entries,
|
||||
acquire_trigger_entry_exec_lock,
|
||||
is_trigger_entry_in_flight_row,
|
||||
release_trigger_entry_exec_lock,
|
||||
is_breakout_trigger_entry_key_monitor_type,
|
||||
is_trigger_entry_expired,
|
||||
is_trigger_entry_key_monitor_type,
|
||||
@@ -2754,15 +2757,39 @@ def place_exchange_order(exchange_symbol, direction, amount, leverage, stop_loss
|
||||
|
||||
|
||||
def close_exchange_order(order_row):
|
||||
"""
|
||||
市价全平。数量优先取交易所当前持仓张数,避免仅用入库 order_amount 导致平不干净。
|
||||
"""
|
||||
ensure_markets_loaded()
|
||||
exchange_symbol = order_row["exchange_symbol"] or normalize_okx_symbol(order_row["symbol"])
|
||||
amount = float(order_row["order_amount"] or 0)
|
||||
if amount <= 0:
|
||||
raise ValueError("平仓失败:缺少有效下单数量")
|
||||
direction = order_row["direction"]
|
||||
db_amt = float(order_row["order_amount"] or 0)
|
||||
side = "sell" if direction == "long" else "buy"
|
||||
params = build_okx_order_params(direction, reduce_only=True)
|
||||
return exchange.create_order(exchange_symbol, "market", side, amount, None, params)
|
||||
last_resp = None
|
||||
for _ in range(3):
|
||||
live = get_live_position_contracts(exchange_symbol, direction)
|
||||
if live is not None and live > 0:
|
||||
raw_amt = live
|
||||
else:
|
||||
raw_amt = db_amt
|
||||
if raw_amt <= 0:
|
||||
if last_resp is not None:
|
||||
return last_resp
|
||||
raise ValueError("平仓失败:缺少有效下单数量")
|
||||
try:
|
||||
amount = float(exchange.amount_to_precision(exchange_symbol, raw_amt))
|
||||
except Exception:
|
||||
amount = float(raw_amt)
|
||||
if amount <= 0:
|
||||
if last_resp is not None:
|
||||
return last_resp
|
||||
raise ValueError("平仓失败:数量经精度舍入后为 0")
|
||||
params = build_okx_order_params(direction, reduce_only=True)
|
||||
last_resp = exchange.create_order(exchange_symbol, "market", side, amount, None, params)
|
||||
live_after = get_live_position_contracts(exchange_symbol, direction)
|
||||
if live_after is None or live_after <= 0:
|
||||
return last_resp
|
||||
return last_resp
|
||||
|
||||
|
||||
def cancel_okx_swap_open_orders(exchange_symbol):
|
||||
@@ -3557,6 +3584,71 @@ def resolve_synced_flat_close(row, opened_at_str, opened_at_ms=None):
|
||||
)
|
||||
|
||||
|
||||
def _finalize_hub_flat_monitor_okx(conn, r, *, result, pnl_amount, closed_at, miss_reason):
|
||||
opened_at = get_opened_at_value(r)
|
||||
closed_at_dt = parse_dt_for_trading_day(closed_at) or app_now()
|
||||
hold_seconds = calc_hold_seconds(opened_at, closed_at_dt)
|
||||
session_date = r["session_date"] or get_trading_day(closed_at_dt)
|
||||
update_session_capital(conn, session_date, pnl_amount)
|
||||
insert_trade_record(
|
||||
conn,
|
||||
symbol=r["symbol"],
|
||||
monitor_type=trade_record_monitor_type(conn, r),
|
||||
trend_plan_id=trend_plan_id_from_monitor_row(r),
|
||||
key_signal_type=order_row_key_signal_type(r),
|
||||
direction=r["direction"],
|
||||
trigger_price=r["trigger_price"],
|
||||
stop_loss=r["stop_loss"],
|
||||
initial_stop_loss=r["initial_stop_loss"] or r["stop_loss"],
|
||||
take_profit=r["take_profit"],
|
||||
margin_capital=r["margin_capital"],
|
||||
leverage=r["leverage"],
|
||||
pnl_amount=pnl_amount,
|
||||
hold_seconds=hold_seconds,
|
||||
trade_style=r["trade_style"],
|
||||
risk_amount=r["risk_amount"],
|
||||
planned_rr=calc_rr_ratio(
|
||||
r["direction"],
|
||||
r["trigger_price"],
|
||||
r["initial_stop_loss"] or r["stop_loss"],
|
||||
r["take_profit"],
|
||||
),
|
||||
actual_rr=calc_actual_rr(pnl_amount, r["risk_amount"]),
|
||||
result=result,
|
||||
miss_reason=handoff_trade_miss_reason(miss_reason, r),
|
||||
opened_at=opened_at,
|
||||
closed_at=closed_at,
|
||||
)
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (r["id"],))
|
||||
|
||||
|
||||
def reconcile_hub_external_close(conn, symbol, direction):
|
||||
from lib.hub.hub_reconcile_flat_lib import reconcile_hub_external_close_impl
|
||||
from lib.hub.hub_symbol_lib import symbols_match
|
||||
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
|
||||
return reconcile_hub_external_close_impl(
|
||||
conn,
|
||||
symbol,
|
||||
direction,
|
||||
exchange_configured=exchange_private_api_configured,
|
||||
not_configured_msg="未配置 OKX_API_KEY / OKX_API_SECRET",
|
||||
symbols_match=symbols_match,
|
||||
get_opened_at_value=get_opened_at_value,
|
||||
resolve_monitor_exchange_symbol=resolve_monitor_exchange_symbol,
|
||||
get_live_position_contracts=get_live_position_contracts,
|
||||
cancel_conditional_orders=cancel_okx_swap_open_orders,
|
||||
resolve_synced_flat_close=resolve_synced_flat_close,
|
||||
finalize_stopped_monitor=_finalize_hub_flat_monitor_okx,
|
||||
sync_trade_records=sync_trade_records_from_exchange,
|
||||
reconcile_flat_streak=_RECONCILE_FLAT_STREAK,
|
||||
to_ms_with_fallback=_to_ms_with_fallback,
|
||||
prefer_manual_resolve=False,
|
||||
order_row_monitor_type=order_row_monitor_type,
|
||||
)
|
||||
|
||||
|
||||
def reconcile_external_closes(conn, days=None):
|
||||
global _RECONCILE_FLAT_STREAK
|
||||
if not exchange_private_api_configured():
|
||||
@@ -5006,7 +5098,7 @@ def _market_open_for_trigger_entry(
|
||||
|
||||
|
||||
def _execute_trigger_entry_cross(conn, row):
|
||||
"""标记价触达计划入场:先删监控行防重复触发,再市价开仓。"""
|
||||
"""标记价触达计划入场:加锁防重复触发,成交成功后再删监控行。"""
|
||||
symbol = row["symbol"]
|
||||
direction = (row["direction"] or "long").lower()
|
||||
ex_sym = normalize_exchange_symbol(symbol)
|
||||
@@ -5017,7 +5109,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
tc_en, tc_h, _ = time_close_settings_from_row(row)
|
||||
|
||||
kid = int(row["id"])
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
if not acquire_trigger_entry_exec_lock(conn, kid):
|
||||
return False, "触价开仓进行中"
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
@@ -5035,6 +5128,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
time_close_hours=tc_h,
|
||||
)
|
||||
except Exception as e:
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = friendly_exchange_error(e)
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓异常\n"
|
||||
@@ -5046,6 +5141,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
return False, fail_msg
|
||||
|
||||
if ok and det:
|
||||
conn.execute("DELETE FROM key_monitors WHERE id=?", (kid,))
|
||||
conn.commit()
|
||||
rr_txt = format_wechat_scalar_2dp(det.get("planned_rr_fill")) if det.get("planned_rr_fill") is not None else "-"
|
||||
msg = (
|
||||
f"# ✅ {symbol} 触价开仓成交\n"
|
||||
@@ -5062,6 +5159,8 @@ def _execute_trigger_entry_cross(conn, row):
|
||||
send_wechat_msg(msg)
|
||||
insert_key_monitor_history(conn, row, 0, msg, TRIGGER_ENTRY_CLOSE_FILLED)
|
||||
return True, None
|
||||
release_trigger_entry_exec_lock(conn, kid)
|
||||
conn.commit()
|
||||
fail_msg = err or "触价触发后开仓失败"
|
||||
send_wechat_msg(
|
||||
f"# ❌ {symbol} 触价开仓失败\n"
|
||||
@@ -5089,6 +5188,8 @@ def check_trigger_entry_key_monitors():
|
||||
sl = float(_sqlite_row_val(r, "fib_stop_loss") or 0)
|
||||
tp = float(_sqlite_row_val(r, "fib_take_profit") or 0)
|
||||
kid = int(r["id"])
|
||||
if is_trigger_entry_in_flight_row(r):
|
||||
continue
|
||||
if entry <= 0 or sl <= 0 or tp <= 0:
|
||||
_finalize_key_monitor_one_shot(conn, r, "触价计划价位无效", "fib_plan_invalid")
|
||||
continue
|
||||
@@ -5856,7 +5957,7 @@ def check_order_monitors():
|
||||
new_sl = round_price_to_exchange(ex_sym, new_sl)
|
||||
tp_ex = float(take_profit or 0)
|
||||
ok_live, _live_reason = ensure_okx_live_ready()
|
||||
synced_ex = not ok_live
|
||||
synced_ex = False
|
||||
last_ex_sync = float(_BREAKEVEN_LAST_EX_SYNC.get(pid, 0))
|
||||
interval_ok = (
|
||||
time.time() - last_ex_sync
|
||||
@@ -6265,8 +6366,8 @@ def background_task():
|
||||
from lib.strategy.strategy_trend_register import check_trend_pullback_plans
|
||||
|
||||
check_trend_pullback_plans(cfg)
|
||||
except:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[monitor_loop] {e}", flush=True)
|
||||
time.sleep(MONITOR_POLL_SECONDS)
|
||||
|
||||
|
||||
@@ -9051,6 +9152,7 @@ try:
|
||||
ohlcv_fn=_hub_fetch_ohlcv,
|
||||
volume_rank_fn=_hub_fetch_volume_rank,
|
||||
market_fn=_hub_fetch_market,
|
||||
reconcile_hub_flat_fn=reconcile_hub_external_close,
|
||||
risk_status_fn=hub_account_risk_status,
|
||||
user_close_fn=hub_user_initiated_close,
|
||||
render_main_page_fn=render_main_page,
|
||||
|
||||
@@ -157,7 +157,7 @@ nano .env
|
||||
- **升级前备份**:`cp .env .env.backup.$(date +%Y%m%d)`;恢复:`cp .env.backup.YYYYMMDD .env`。
|
||||
- **换机**:`scp` 复制 `.env`,或新机 `cp .env.example .env` 后重填。
|
||||
|
||||
**AI 复盘**:四所共用根目录 **`ai_client.py`**。默认 **`AI_PROVIDER=openai`**,网关 `https://op.bz121.com/v1`,模型 `gemma4:e4b`;或改 **`ollama`** 走本机 Ollama。PM2 须 **`PYTHONPATH=..`**。详见 **[AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)**。
|
||||
**AI 复盘**:三所共用根目录 **`ai_client.py`**。默认 **`AI_PROVIDER=openai`**,网关 `https://op.bz121.com/v1`,模型 `gemma4:e4b`;或改 **`ollama`** 走本机 Ollama。PM2 须 **`PYTHONPATH=..`**。详见 **[AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)**。
|
||||
|
||||
### 5.3 必填项检查(OKX + 代理)
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ bash deploy/setup_env.sh --install-system-deps
|
||||
常用参数:
|
||||
|
||||
```bash
|
||||
bash deploy/setup_env.sh --only binance,gate_bot # 仅部分子项目
|
||||
bash deploy/setup_env.sh --only binance,gate # 仅部分子项目
|
||||
bash deploy/setup_env.sh --recreate-venv # 重建虚拟环境
|
||||
bash deploy/setup_env.sh --skip-pm2 # 不尝试安装 pm2
|
||||
bash deploy/setup_env.sh --skip-env-copy # 不复制 .env.example
|
||||
```
|
||||
|
||||
**整目录重装**(保留 `.env`、清库、去脏 PM2)见 **[reinstall-plan-b.md](./reinstall-plan-b.md)**,执行 `bash deploy/reinstall.sh`。与 `setup_env.sh` 独立,不影响首次一键安装。
|
||||
|
||||
若在其它环境编辑过脚本后报 `pipefail` 错误,先转 LF:
|
||||
|
||||
```bash
|
||||
@@ -68,11 +70,13 @@ sed -i 's/\r$//' deploy/setup_env.sh
|
||||
pm2 save
|
||||
```
|
||||
|
||||
3. 四所 `.env` 同步脚本见 **[docs/env-sync-scripts.md](../docs/env-sync-scripts.md)**。
|
||||
或一条命令:`bash deploy/pm2_start_all.sh`
|
||||
|
||||
3. 三所 `.env` 同步脚本见 **[docs/env-sync-scripts.md](../docs/env-sync-scripts.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 依赖说明
|
||||
|
||||
- 四个监控子项目共用根目录 **[requirements.txt](../requirements.txt)**。
|
||||
- 三个监控子项目共用根目录 **[requirements.txt](../requirements.txt)**。
|
||||
- 走 SOCKS 须 **PySocks**(已包含在 requirements 中)。
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# 按推荐顺序启动三所 Flask + 中控 hub/三 agent(PM2)。
|
||||
# 用法(仓库根或任意目录):
|
||||
# bash deploy/pm2_start_all.sh
|
||||
#
|
||||
# 与 deploy/setup_env.sh 独立:setup_env 只建 venv;本脚本负责 PM2 启动。
|
||||
set -e
|
||||
set -u
|
||||
if [ -n "${BASH_VERSION:-}" ]; then
|
||||
set -o pipefail
|
||||
fi
|
||||
|
||||
DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(cd "${DEPLOY_DIR}/.." && pwd)"
|
||||
|
||||
start_one() {
|
||||
local dir_name="$1"
|
||||
local proj="${REPO_ROOT}/${dir_name}"
|
||||
local eco="${proj}/ecosystem.config.cjs"
|
||||
if [[ ! -f "${eco}" ]]; then
|
||||
echo "skip (no ecosystem): ${dir_name}" >&2
|
||||
return 0
|
||||
fi
|
||||
echo "==> pm2 start ${dir_name}"
|
||||
(cd "${proj}" && pm2 start ecosystem.config.cjs)
|
||||
}
|
||||
|
||||
if ! command -v pm2 >/dev/null 2>&1; then
|
||||
echo "未找到 pm2,请先安装 Node.js 与 pm2(见 docs/ubuntu-server.md)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
start_one crypto_monitor_binance
|
||||
start_one crypto_monitor_gate
|
||||
start_one crypto_monitor_okx
|
||||
start_one manual_trading_hub
|
||||
|
||||
pm2 save 2>/dev/null || true
|
||||
echo ""
|
||||
echo "PM2 进程:"
|
||||
pm2 list
|
||||
@@ -0,0 +1,112 @@
|
||||
# Plan B:整目录重装(生产清库)
|
||||
|
||||
适用于:**保留三所 `.env` 与中控配置,丢弃旧代码、旧 SQLite、脏 PM2 名单**(例如移除 `gate_bot` 后偶发重启)。
|
||||
|
||||
与 **[setup_env.sh](./setup_env.sh)** 的关系:
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|------|------|
|
||||
| `setup_env.sh` | **首次安装 / 日常**:建 venv、装依赖、从 `.env.example` 复制(**不变**) |
|
||||
| `reinstall.sh` | **整目录重装**:备份 → 移走旧目录 → `git clone` → 调 `setup_env.sh` → 恢复配置 → PM2 |
|
||||
|
||||
---
|
||||
|
||||
## 一键执行(推荐)
|
||||
|
||||
在现有服务器安装上以 **root** 执行:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
bash deploy/reinstall.sh --yes
|
||||
```
|
||||
|
||||
交互确认(不加 `--yes`):
|
||||
|
||||
```bash
|
||||
bash deploy/reinstall.sh
|
||||
```
|
||||
|
||||
仅预览步骤:
|
||||
|
||||
```bash
|
||||
bash deploy/reinstall.sh --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 脚本会做什么
|
||||
|
||||
1. 备份到 **`/root/backups/pre-reinstall-YYYYMMDD-HHMMSS/`**
|
||||
- 三所 `crypto_monitor_*/.env`
|
||||
- `manual_trading_hub/.env`
|
||||
- `manual_trading_hub/hub_settings.json`(若有)
|
||||
- 可选:仓库内 `one_shot` 备份目录
|
||||
2. **`pm2 stop all` + `pm2 delete all`**
|
||||
3. **`mv /opt/crypto_monitor /opt/crypto_monitor.old.时间戳`**
|
||||
4. **`git clone`** 到 `/opt/crypto_monitor`(默认 `main`)
|
||||
5. **`bash deploy/setup_env.sh --skip-env-copy --recreate-venv --skip-pm2`**
|
||||
6. 从备份 **恢复 `.env` / `hub_settings.json`**
|
||||
7. **`deploy/sanitize_hub_settings.py`** 去掉 `gate_bot` / 第四账户
|
||||
8. **`deploy/pm2_start_all.sh`** + `pm2 save`
|
||||
9. 为三所重装 **每日 0 点备份 cron**(可用 `--no-backup-cron` 跳过)
|
||||
|
||||
**不会备份/恢复**:`crypto.db`、hub `data/*.db`、`static/images`(符合「全新启动」)。
|
||||
|
||||
**不会动**:宝塔/Nginx 反代、SSH SOCKS 隧道(tmux 内)。
|
||||
|
||||
---
|
||||
|
||||
## 环境变量
|
||||
|
||||
```bash
|
||||
export INSTALL_ROOT=/opt/crypto_monitor
|
||||
export GIT_URL=https://git.bz121.com/dekun/crypto_monitor.git
|
||||
export GIT_BRANCH=main
|
||||
export BACKUP_ROOT=/root/backups
|
||||
bash deploy/reinstall.sh --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 验收
|
||||
|
||||
```bash
|
||||
pm2 list
|
||||
# 应有 7 个: crypto_binance crypto_gate crypto_okx manual-trading-hub manual-agent-*
|
||||
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5100/
|
||||
```
|
||||
|
||||
浏览器:中控 `/monitor` 登录,三所 LINK 绿,监控区为空库。
|
||||
|
||||
---
|
||||
|
||||
## 回滚
|
||||
|
||||
旧目录默认保留为 `/opt/crypto_monitor.old.时间戳`,配置在 `/root/backups/pre-reinstall-*`:
|
||||
|
||||
```bash
|
||||
pm2 delete all
|
||||
rm -rf /opt/crypto_monitor
|
||||
mv /opt/crypto_monitor.old.XXXXXXXX /opt/crypto_monitor
|
||||
bash /opt/crypto_monitor/deploy/pm2_start_all.sh
|
||||
```
|
||||
|
||||
确认新环境稳定后再删 `.old.*` 目录。
|
||||
|
||||
---
|
||||
|
||||
## 辅助脚本
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| [pm2_start_all.sh](./pm2_start_all.sh) | 按顺序 PM2 启动三所 + hub(setup_env 之后手动用) |
|
||||
| [sanitize_hub_settings.py](./sanitize_hub_settings.py) | 清理 `hub_settings.json` 中 gate_bot 条目 |
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [deploy/README.md](./README.md) — 首次一键安装
|
||||
- [docs/ubuntu-server.md](../docs/ubuntu-server.md) — Python / PM2 版本
|
||||
- [备份与恢复.md](../备份与恢复.md) — 日常 DB 备份 cron
|
||||
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env bash
|
||||
# Plan B:整目录重装 /opt/crypto_monitor(备份 .env → 移走旧目录 → git clone → setup_env → 恢复配置 → PM2)
|
||||
#
|
||||
# 与 deploy/setup_env.sh 分工:
|
||||
# setup_env.sh — 首次 / 日常:建 venv、装依赖、复制 .env.example(一键安装,不变)
|
||||
# reinstall.sh — 生产清库重装:保留密钥与 hub 配置,丢弃旧代码/旧库/脏 PM2
|
||||
#
|
||||
# 用法(在现有安装目录以 root 执行):
|
||||
# cd /opt/crypto_monitor
|
||||
# bash deploy/reinstall.sh # 交互确认
|
||||
# bash deploy/reinstall.sh --yes # 跳过确认
|
||||
# bash deploy/reinstall.sh --dry-run # 仅打印步骤
|
||||
#
|
||||
# 可选环境变量:
|
||||
# INSTALL_ROOT=/opt/crypto_monitor
|
||||
# GIT_URL=https://git.bz121.com/dekun/crypto_monitor.git
|
||||
# GIT_BRANCH=main
|
||||
# BACKUP_ROOT=/root/backups
|
||||
#
|
||||
set -e
|
||||
set -u
|
||||
if [ -n "${BASH_VERSION:-}" ]; then
|
||||
set -o pipefail
|
||||
fi
|
||||
|
||||
DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
SCRIPT_SOURCE="${DEPLOY_DIR}/reinstall.sh"
|
||||
REPO_ROOT="$(cd "${DEPLOY_DIR}/.." && pwd)"
|
||||
|
||||
INSTALL_ROOT="${INSTALL_ROOT:-/opt/crypto_monitor}"
|
||||
GIT_URL="${GIT_URL:-https://git.bz121.com/dekun/crypto_monitor.git}"
|
||||
GIT_BRANCH="${GIT_BRANCH:-main}"
|
||||
BACKUP_ROOT="${BACKUP_ROOT:-/root/backups}"
|
||||
TZ_NAME="${REINSTALL_TZ:-Asia/Shanghai}"
|
||||
|
||||
ASSUME_YES=0
|
||||
DRY_RUN=0
|
||||
INSTALL_BACKUP_CRON=1
|
||||
|
||||
CONFIG_PATHS=(
|
||||
"crypto_monitor_binance/.env"
|
||||
"crypto_monitor_okx/.env"
|
||||
"crypto_monitor_gate/.env"
|
||||
"manual_trading_hub/.env"
|
||||
"manual_trading_hub/hub_settings.json"
|
||||
)
|
||||
|
||||
usage() {
|
||||
sed -n '2,18p' "$0" | sed 's/^# \?//'
|
||||
exit "${1:-0}"
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--yes|-y) ASSUME_YES=1; shift ;;
|
||||
--dry-run) DRY_RUN=1; shift ;;
|
||||
--no-backup-cron) INSTALL_BACKUP_CRON=0; shift ;;
|
||||
-h|--help) usage 0 ;;
|
||||
*) echo "未知参数: $1" >&2; usage 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
log() { printf '[%s] %s\n' "$(TZ="${TZ_NAME}" date '+%Y-%m-%d %H:%M:%S')" "$*"; }
|
||||
step() { echo ""; log "==> $*"; }
|
||||
|
||||
run() {
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] $*"
|
||||
return 0
|
||||
fi
|
||||
log "+ $*"
|
||||
"$@"
|
||||
}
|
||||
|
||||
confirm() {
|
||||
if [[ "${ASSUME_YES}" -eq 1 || "${DRY_RUN}" -eq 1 ]]; then
|
||||
return 0
|
||||
fi
|
||||
local msg="$1"
|
||||
read -r -p "${msg} [y/N] " ans
|
||||
[[ "${ans}" == [yY] || "${ans}" == [yY][eE][sS] ]]
|
||||
}
|
||||
|
||||
resolve_path() {
|
||||
local base="$1"
|
||||
local rel="$2"
|
||||
printf '%s/%s' "${base}" "${rel}"
|
||||
}
|
||||
|
||||
backup_configs() {
|
||||
local src_root="$1"
|
||||
local dest="$2"
|
||||
mkdir -p "${dest}"
|
||||
local rel copied=0
|
||||
for rel in "${CONFIG_PATHS[@]}"; do
|
||||
local src
|
||||
src="$(resolve_path "${src_root}" "${rel}")"
|
||||
if [[ -f "${src}" ]]; then
|
||||
mkdir -p "${dest}/$(dirname "${rel}")"
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] backup ${src} -> ${dest}/${rel}"
|
||||
else
|
||||
cp -a "${src}" "${dest}/${rel}"
|
||||
log "backup ${rel}"
|
||||
fi
|
||||
copied=$((copied + 1))
|
||||
else
|
||||
log "skip (missing): ${rel}"
|
||||
fi
|
||||
done
|
||||
if [[ "${copied}" -eq 0 ]]; then
|
||||
echo "错误: 未备份到任何配置文件,请检查 ${src_root}" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -f "${src_root}/scripts/one_shot_backup_config_before_cleanup.py" ]]; then
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] python3 scripts/one_shot_backup_config_before_cleanup.py (in ${src_root})"
|
||||
else
|
||||
(cd "${src_root}" && python3 scripts/one_shot_backup_config_before_cleanup.py) || true
|
||||
if compgen -G "${src_root}/backups/one-shot-*" >/dev/null; then
|
||||
cp -a "${src_root}"/backups/one-shot-* "${dest}/" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [[ "${DRY_RUN}" -eq 0 ]]; then
|
||||
{
|
||||
echo "created_at=${STAMP}"
|
||||
echo "install_root=${INSTALL_ROOT}"
|
||||
echo "old_dir=${OLD_DIR}"
|
||||
echo "git_url=${GIT_URL}"
|
||||
echo "git_branch=${GIT_BRANCH}"
|
||||
echo "script=${SCRIPT_SOURCE}"
|
||||
} >"${dest}/reinstall.manifest"
|
||||
fi
|
||||
}
|
||||
|
||||
restore_configs() {
|
||||
local backup_dir="$1"
|
||||
local dest_root="$2"
|
||||
local rel
|
||||
for rel in "${CONFIG_PATHS[@]}"; do
|
||||
local src dest
|
||||
src="${backup_dir}/${rel}"
|
||||
dest="$(resolve_path "${dest_root}" "${rel}")"
|
||||
if [[ -f "${src}" ]]; then
|
||||
mkdir -p "$(dirname "${dest}")"
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] restore ${src} -> ${dest}"
|
||||
else
|
||||
cp -a "${src}" "${dest}"
|
||||
log "restore ${rel}"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
local hub_settings
|
||||
hub_settings="$(resolve_path "${dest_root}" "manual_trading_hub/hub_settings.json")"
|
||||
if [[ -f "${hub_settings}" && "${DRY_RUN}" -eq 0 ]]; then
|
||||
python3 "${dest_root}/deploy/sanitize_hub_settings.py" "${hub_settings}" || true
|
||||
fi
|
||||
}
|
||||
|
||||
install_instance_backup_cron() {
|
||||
local dest_root="$1"
|
||||
local dir
|
||||
for dir in crypto_monitor_binance crypto_monitor_gate crypto_monitor_okx; do
|
||||
local proj="${dest_root}/${dir}"
|
||||
local inst="${proj}/scripts/install_backup_cron.sh"
|
||||
local data="${proj}/scripts/backup_data.sh"
|
||||
if [[ -f "${inst}" && -f "${data}" ]]; then
|
||||
chmod +x "${inst}" "${data}"
|
||||
run bash "${inst}"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
verify_pm2() {
|
||||
log "预期 PM2 进程(7 个): crypto_binance crypto_gate crypto_okx manual-trading-hub manual-agent-*"
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
return 0
|
||||
fi
|
||||
pm2 list || true
|
||||
if pm2 list 2>/dev/null | grep -qiE 'gate_bot|15203'; then
|
||||
log "警告: PM2 列表仍含 gate_bot 相关进程,请 pm2 delete 后 pm2 save"
|
||||
fi
|
||||
}
|
||||
|
||||
# --- 前置检查 ---
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "请使用 root 执行(推荐路径 ${INSTALL_ROOT})" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "${REPO_ROOT}/deploy/setup_env.sh" ]]; then
|
||||
echo "当前脚本不在有效仓库内: ${REPO_ROOT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${REPO_ROOT}" != "${INSTALL_ROOT}" ]]; then
|
||||
log "提示: 当前仓库 ${REPO_ROOT} 与 INSTALL_ROOT=${INSTALL_ROOT} 不一致;将备份当前仓库并克隆到 INSTALL_ROOT"
|
||||
fi
|
||||
|
||||
STAMP="$(TZ="${TZ_NAME}" date +%Y%m%d-%H%M%S)"
|
||||
BACKUP_DIR="${BACKUP_ROOT}/pre-reinstall-${STAMP}"
|
||||
OLD_DIR="${INSTALL_ROOT}.old.${STAMP}"
|
||||
SRC_ROOT="${REPO_ROOT}"
|
||||
|
||||
if [[ -d "${INSTALL_ROOT}" && "${REPO_ROOT}" != "${INSTALL_ROOT}" ]]; then
|
||||
SRC_ROOT="${INSTALL_ROOT}"
|
||||
fi
|
||||
|
||||
step "计划"
|
||||
echo " 备份目录: ${BACKUP_DIR}"
|
||||
echo " 配置来源: ${SRC_ROOT}"
|
||||
echo " 旧目录移走: ${OLD_DIR}"
|
||||
echo " 新克隆: ${GIT_URL} (${GIT_BRANCH}) -> ${INSTALL_ROOT}"
|
||||
echo " 环境: deploy/setup_env.sh --skip-env-copy --recreate-venv --skip-pm2"
|
||||
echo ""
|
||||
echo " 将停止并 delete 全部 PM2 进程;不备份 crypto.db / hub data / 图片。"
|
||||
|
||||
if ! confirm "确认执行 Plan B 整目录重装?"; then
|
||||
log "已取消"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- 1. 备份 ---
|
||||
|
||||
step "备份配置到 ${BACKUP_DIR}"
|
||||
backup_configs "${SRC_ROOT}" "${BACKUP_DIR}"
|
||||
|
||||
# --- 2. 停 PM2 ---
|
||||
|
||||
step "停止并清空 PM2"
|
||||
if command -v pm2 >/dev/null 2>&1; then
|
||||
run pm2 stop all || true
|
||||
run pm2 delete all || true
|
||||
else
|
||||
log "未安装 pm2,跳过"
|
||||
fi
|
||||
|
||||
# --- 3. 移走旧目录 ---
|
||||
|
||||
step "移走旧安装 ${INSTALL_ROOT} -> ${OLD_DIR}"
|
||||
if [[ -d "${INSTALL_ROOT}" ]]; then
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] mv ${INSTALL_ROOT} ${OLD_DIR}"
|
||||
else
|
||||
mv "${INSTALL_ROOT}" "${OLD_DIR}"
|
||||
fi
|
||||
else
|
||||
log "目标目录不存在,跳过 mv"
|
||||
fi
|
||||
|
||||
# --- 4. 克隆 ---
|
||||
|
||||
step "git clone"
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] git clone -b ${GIT_BRANCH} ${GIT_URL} ${INSTALL_ROOT}"
|
||||
else
|
||||
git clone -b "${GIT_BRANCH}" "${GIT_URL}" "${INSTALL_ROOT}"
|
||||
fi
|
||||
|
||||
# --- 5. setup_env(一键安装逻辑,不复制 .env)---
|
||||
|
||||
step "重建 Python 虚拟环境 (setup_env.sh)"
|
||||
if [[ "${DRY_RUN}" -eq 1 ]]; then
|
||||
log "[dry-run] bash ${INSTALL_ROOT}/deploy/setup_env.sh --skip-env-copy --recreate-venv --skip-pm2"
|
||||
else
|
||||
bash "${INSTALL_ROOT}/deploy/setup_env.sh" --skip-env-copy --recreate-venv --skip-pm2
|
||||
fi
|
||||
|
||||
# --- 6. 恢复配置 ---
|
||||
|
||||
step "恢复 .env 与 hub_settings.json"
|
||||
restore_configs "${BACKUP_DIR}" "${INSTALL_ROOT}"
|
||||
|
||||
# --- 7. PM2 启动 ---
|
||||
|
||||
step "PM2 启动全部进程"
|
||||
if command -v pm2 >/dev/null 2>&1; then
|
||||
run bash "${INSTALL_ROOT}/deploy/pm2_start_all.sh"
|
||||
run pm2 save
|
||||
else
|
||||
log "未安装 pm2;请手动: bash ${INSTALL_ROOT}/deploy/pm2_start_all.sh"
|
||||
fi
|
||||
|
||||
# --- 8. 定时备份 cron(可选)---
|
||||
|
||||
if [[ "${INSTALL_BACKUP_CRON}" -eq 1 ]]; then
|
||||
step "安装三所每日备份 cron"
|
||||
install_instance_backup_cron "${INSTALL_ROOT}"
|
||||
fi
|
||||
|
||||
# --- 完成 ---
|
||||
|
||||
step "完成"
|
||||
verify_pm2
|
||||
echo ""
|
||||
echo "备份: ${BACKUP_DIR}"
|
||||
echo "旧目录(确认无误后可删): ${OLD_DIR}"
|
||||
echo ""
|
||||
echo "验收建议:"
|
||||
echo " pm2 list"
|
||||
echo " curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5100/"
|
||||
echo " 浏览器打开中控 /monitor,确认三所 LINK 正常"
|
||||
echo ""
|
||||
echo "回滚(未删旧目录时):"
|
||||
echo " pm2 delete all"
|
||||
echo " rm -rf ${INSTALL_ROOT}"
|
||||
echo " mv ${OLD_DIR} ${INSTALL_ROOT}"
|
||||
echo " cp -a ${BACKUP_DIR}/*/ ${INSTALL_ROOT}/ # 若需恢复配置"
|
||||
echo " bash ${INSTALL_ROOT}/deploy/pm2_start_all.sh"
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""重装后清理 hub_settings.json 中已废弃的 gate_bot / 第四账户条目。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DROP_KEYS = frozenset({"gate_bot", "gate-bot"})
|
||||
DROP_MARKERS = (
|
||||
"gate_bot",
|
||||
"crypto_monitor_gate_bot",
|
||||
"15203",
|
||||
":5002",
|
||||
)
|
||||
|
||||
|
||||
def _text(*parts: object) -> str:
|
||||
return " ".join(str(p) for p in parts if p is not None).lower()
|
||||
|
||||
|
||||
def should_drop(ex: dict) -> bool:
|
||||
key = str(ex.get("key") or "").strip().lower()
|
||||
if key in DROP_KEYS:
|
||||
return True
|
||||
blob = _text(
|
||||
ex.get("name"),
|
||||
ex.get("flask_url"),
|
||||
ex.get("agent_url"),
|
||||
ex.get("review_url"),
|
||||
)
|
||||
if any(m in blob for m in DROP_MARKERS):
|
||||
return True
|
||||
ex_id = str(ex.get("id") or "").strip()
|
||||
if ex_id == "3" and key not in ("gate", ""):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def sanitize_settings(data: dict) -> tuple[dict, list[str]]:
|
||||
removed: list[str] = []
|
||||
exchanges = data.get("exchanges")
|
||||
if not isinstance(exchanges, list):
|
||||
return data, removed
|
||||
|
||||
kept: list[dict] = []
|
||||
seen_keys: set[str] = set()
|
||||
for ex in exchanges:
|
||||
if not isinstance(ex, dict):
|
||||
continue
|
||||
key = str(ex.get("key") or "").strip().lower()
|
||||
label = f"id={ex.get('id')} key={key} name={ex.get('name')}"
|
||||
if should_drop(ex):
|
||||
removed.append(label)
|
||||
continue
|
||||
if key and key in seen_keys:
|
||||
removed.append(f"duplicate {label}")
|
||||
continue
|
||||
if key:
|
||||
seen_keys.add(key)
|
||||
kept.append(ex)
|
||||
|
||||
out = dict(data)
|
||||
out["exchanges"] = kept
|
||||
return out, removed
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = argv if argv is not None else sys.argv[1:]
|
||||
if len(args) != 1:
|
||||
print("用法: python deploy/sanitize_hub_settings.py <hub_settings.json>", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
path = Path(args[0])
|
||||
if not path.is_file():
|
||||
print(f"文件不存在: {path}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON 解析失败: {e}", file=sys.stderr)
|
||||
return 1
|
||||
if not isinstance(data, dict):
|
||||
print("hub_settings.json 根节点必须是 object", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
cleaned, removed = sanitize_settings(data)
|
||||
if removed:
|
||||
path.write_text(json.dumps(cleaned, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("已移除条目:")
|
||||
for line in removed:
|
||||
print(f" - {line}")
|
||||
else:
|
||||
print("无需修改(未发现 gate_bot / 第四账户)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -3,7 +3,7 @@
|
||||
#
|
||||
# 用法:
|
||||
# bash deploy/setup_env.sh
|
||||
# bash deploy/setup_env.sh --only binance,gate_bot
|
||||
# bash deploy/setup_env.sh --only binance,gate
|
||||
# bash deploy/setup_env.sh --skip-pm2
|
||||
# bash deploy/setup_env.sh --recreate-venv
|
||||
# bash deploy/setup_env.sh --install-system-deps # root + apt 时安装 python*-venv
|
||||
@@ -244,7 +244,6 @@ ensure_venv_prereqs "${PY}"
|
||||
|
||||
should_include binance && setup_monitor crypto_monitor_binance
|
||||
should_include gate && setup_monitor crypto_monitor_gate
|
||||
should_include gate_bot && setup_monitor crypto_monitor_gate_bot
|
||||
should_include okx && setup_monitor crypto_monitor_okx
|
||||
should_include hub && setup_hub
|
||||
|
||||
|
||||
@@ -1,130 +1,130 @@
|
||||
# 账户冷静期 / 日冻结风控
|
||||
|
||||
四所实例(币安 / OKX / Gate / Gate 趋势)共用 `account_risk_lib.py`。
|
||||
**仅用户主动平仓**计入风控;交易所止盈/止损、空仓同步、改保本/改委托等**不触发**冷静期。
|
||||
|
||||
## 状态展示
|
||||
|
||||
实例页顶、中控监控卡片账户名旁显示风控徽章:
|
||||
|
||||
| 状态 | 含义 | 倒计时 |
|
||||
|------|------|--------|
|
||||
| 正常 | 可新开仓 | 无 |
|
||||
| 1h冻结 | 冷静期中(通常为复盘后缩短的 1 小时) | 剩余时间,如 `1h冻结 · 52m 08s` |
|
||||
| 4h冻结 | 冷静期中(默认 4 小时) | 剩余时间,如 `4h冻结 · 3h 12m` |
|
||||
| 日冻结 | 当日禁止一切新开仓 | 至下一 **交易日切点**(`TRADING_DAY_RESET_HOUR`) |
|
||||
|
||||
- 倒计时每秒刷新;到期后徽章自动恢复为 **正常**(下次轮询/API 刷新会再次对齐服务端状态)。
|
||||
- 鼠标悬停徽章可见完整说明(含解除时刻,如有)。
|
||||
|
||||
## 什么算「手动平仓」(计入风控)
|
||||
|
||||
以下操作通过 `close_source` 登记为 **用户主动平仓**:
|
||||
|
||||
| 来源标识 | 操作 |
|
||||
|----------|------|
|
||||
| `user_instance` | 实例页删单/手动平仓(`del_order`) |
|
||||
| `user_hub` | 中控「平仓」「全平」「紧急全平」 |
|
||||
| `user_trend_stop` | 趋势计划 **「结束计划」**(手动结束) |
|
||||
|
||||
**不算**手动平仓(不触发风控):
|
||||
|
||||
- 趋势 **「保本移交下单监控」**
|
||||
- 中控/实例修改委托、挂止盈止损、移动保本
|
||||
- 交易所止盈/止损/条件单成交
|
||||
- 后台 `reconcile_external_closes` 空仓同步(即使记账为「外部平仓」)
|
||||
- 监控轮询自动止盈/止损/保本
|
||||
|
||||
## 触发规则
|
||||
|
||||
| 事件 | 行为 |
|
||||
|------|------|
|
||||
| 第 1 次用户主动平仓 | 默认 **4h** 冷静期 |
|
||||
| 第 2 次用户主动平仓(同一交易日) | **日冻结** |
|
||||
| 复盘勾选任意情绪标签 | **日冻结** |
|
||||
| 复盘:离场=手动平仓 且说明非空 | 将当前冷静期降为 **1h**(须处于 4h 档冷静期中) |
|
||||
|
||||
情绪标签:怕踏空、报复开仓、盈利飘了、拿不住单、扛单、重仓违规。
|
||||
|
||||
### 复盘缩短为 1h
|
||||
|
||||
任选一种方式,并填写说明:
|
||||
|
||||
| 方式 | 必填 |
|
||||
|------|------|
|
||||
| **复盘表单**提交 | 离场触发 = **手动平仓**;**离场补充** 非空(不是下方「备注」) |
|
||||
| **核对修改**保存 | 结果 = **手动平仓**;**备注** 非空 |
|
||||
|
||||
说明:
|
||||
|
||||
- 中控全平 / 实例手动平仓后,只要在 4h 窗口内完成上述操作即可降为 1h。
|
||||
- 复盘保存后会同步更新 `last_close_at_ms`,倒计时以 **最后一次手动平仓 + 当前档位数** 为准,不会继续读库内旧 4h 结束时间。
|
||||
- 1h 窗口已结束后,即使库里残留旧 `cooloff_until_ms`,状态也会恢复 **正常**。
|
||||
- 若超过「平仓 + 1h」才复盘,则从 **保存复盘时刻** 起再计 1h(不延长原 4h)。
|
||||
- **止盈 / 保本止盈 / 止损** 等自动平仓不触发风控,也不会刷新冷静期。
|
||||
- 代码更新后需 **重启对应实例** 并硬刷新页面。
|
||||
|
||||
### 倒计时与标签
|
||||
|
||||
- 结束时刻 = `last_close_at_ms + cooloff_hours`(`APP_TIMEZONE` 默认北京时间)
|
||||
- 1h / 4h 标签按实际剩余时长判断,与倒计时一致
|
||||
- 切交易日后,若冷静期已过期,自动清库内残留字段
|
||||
|
||||
## 环境变量
|
||||
|
||||
```env
|
||||
RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
TRADING_DAY_RESET_HOUR=8
|
||||
APP_TIMEZONE=Asia/Shanghai
|
||||
```
|
||||
|
||||
`RISK_COOLING_HOURS_EXTERNAL` 已废弃(外部平仓不再触发风控)。
|
||||
|
||||
## API 与 `risk_status` 字段
|
||||
|
||||
| 接口 | 说明 |
|
||||
|------|------|
|
||||
| `GET /api/account_snapshot` | 实例页轮询,含 `risk_status` |
|
||||
| `GET /api/account_risk_status` | hub_bridge 专用 |
|
||||
| `GET /api/hub/monitor` | 中控监控板,每账户含 `risk_status` |
|
||||
| `POST /api/hub/account-risk/user-close` | 中控登记用户平仓,`body: { source, count }` |
|
||||
|
||||
`risk_status` 主要字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `status` | `normal` / `freeze_1h` / `freeze_4h` / `freeze_daily` / `freeze_position` |
|
||||
| `status_label` | 中文标签 |
|
||||
| `can_trade` | 是否允许新开仓(仅风控维度) |
|
||||
| `reason` | 悬停提示文案 |
|
||||
| `active_count` / `max_active_positions` | 当前活跃持仓与 `.env` 中 `MAX_ACTIVE_POSITIONS` |
|
||||
| `cooloff_until_ms` | 1h/4h 冷静期结束时间戳(毫秒) |
|
||||
| `freeze_until_ms` | 倒计时结束时间戳(日冻结为下一交易日切点) |
|
||||
| `freeze_remaining_sec` | 服务端计算的剩余秒数(供调试) |
|
||||
|
||||
**仓位上限冻结**:当 **计入上限的** 活跃持仓数(不含趋势回调)≥ 实例 `.env` 的 `MAX_ACTIVE_POSITIONS`(默认 1)且账户无时间类冻结时,徽章显示 **仓位上限冻结**;此时 **新开仓** 被禁止,但 **顺势加仓**(在已有同向监控持仓上加仓)仍可用。仅存在趋势回调持仓时不触发该冻结。时间冻结(1h/4h/日)优先展示。
|
||||
|
||||
`risk_status.can_roll`:仓位上限冻结时为 `true`,表示顺势加仓不受该冻结限制。
|
||||
|
||||
## 前端倒计时
|
||||
|
||||
- 共用脚本:`static/account_risk_badge.js?v=4`
|
||||
- 样式:`static/account_risk_badge.css`
|
||||
- 展示格式:`4h冻结 · 3h 12m`;日冻结为距下一交易日切点剩余时间
|
||||
- 倒计时优先用服务端 `freeze_remaining_sec` 推算结束时刻,避免绝对时间戳与时区/脏数据偏差
|
||||
- 服务端在冷静期**已结束**或锚点无效时**自动清库**,避免重启后误读旧 `account_risk_state` 仍显示冻结
|
||||
- 无效的未来 `last_close_at_ms` **不会**被当作「现在」重启计时
|
||||
- 若当日手动平仓**已复盘**(journal 有说明)且 1h 窗口已过,即使 risk 表被误写也会强制恢复 **正常**
|
||||
- 勿与交易记录列表中的历史平仓时间混淆:风控只看 `account_risk_state` 表内 **最后一次用户主动平仓** 及其复盘结果
|
||||
|
||||
## 相关代码
|
||||
|
||||
- `account_risk_lib.py` — 状态机、`enrich_risk_status_countdown`、`apply_position_limit_risk`、`on_user_initiated_close`
|
||||
- `hub_bridge.py` — `/api/hub/account-risk/user-close`
|
||||
- `manual_trading_hub/hub.py` — 中控平仓成功后调用 user-close
|
||||
- `strategy_trend_register.py` — `stop_trend_pullback` 结束计划时登记风控
|
||||
- `tests/test_account_risk_lib.py`
|
||||
# 账户冷静期 / 日冻结风控
|
||||
|
||||
三所实例(币安 / OKX / Gate / Gate)共用 `account_risk_lib.py`。
|
||||
**仅用户主动平仓**计入风控;交易所止盈/止损、空仓同步、改保本/改委托等**不触发**冷静期。
|
||||
|
||||
## 状态展示
|
||||
|
||||
实例页顶、中控监控卡片账户名旁显示风控徽章:
|
||||
|
||||
| 状态 | 含义 | 倒计时 |
|
||||
|------|------|--------|
|
||||
| 正常 | 可新开仓 | 无 |
|
||||
| 1h冻结 | 冷静期中(通常为复盘后缩短的 1 小时) | 剩余时间,如 `1h冻结 · 52m 08s` |
|
||||
| 4h冻结 | 冷静期中(默认 4 小时) | 剩余时间,如 `4h冻结 · 3h 12m` |
|
||||
| 日冻结 | 当日禁止一切新开仓 | 至下一 **交易日切点**(`TRADING_DAY_RESET_HOUR`) |
|
||||
|
||||
- 倒计时每秒刷新;到期后徽章自动恢复为 **正常**(下次轮询/API 刷新会再次对齐服务端状态)。
|
||||
- 鼠标悬停徽章可见完整说明(含解除时刻,如有)。
|
||||
|
||||
## 什么算「手动平仓」(计入风控)
|
||||
|
||||
以下操作通过 `close_source` 登记为 **用户主动平仓**:
|
||||
|
||||
| 来源标识 | 操作 |
|
||||
|----------|------|
|
||||
| `user_instance` | 实例页删单/手动平仓(`del_order`) |
|
||||
| `user_hub` | 中控「平仓」「全平」「紧急全平」 |
|
||||
| `user_trend_stop` | 趋势计划 **「结束计划」**(手动结束) |
|
||||
|
||||
**不算**手动平仓(不触发风控):
|
||||
|
||||
- 趋势 **「保本移交下单监控」**
|
||||
- 中控/实例修改委托、挂止盈止损、移动保本
|
||||
- 交易所止盈/止损/条件单成交
|
||||
- 后台 `reconcile_external_closes` 空仓同步(即使记账为「外部平仓」)
|
||||
- 监控轮询自动止盈/止损/保本
|
||||
|
||||
## 触发规则
|
||||
|
||||
| 事件 | 行为 |
|
||||
|------|------|
|
||||
| 第 1 次用户主动平仓 | 默认 **4h** 冷静期 |
|
||||
| 第 2 次用户主动平仓(同一交易日) | **日冻结** |
|
||||
| 复盘勾选任意情绪标签 | **日冻结** |
|
||||
| 复盘:离场=手动平仓 且说明非空 | 将当前冷静期降为 **1h**(须处于 4h 档冷静期中) |
|
||||
|
||||
情绪标签:怕踏空、报复开仓、盈利飘了、拿不住单、扛单、重仓违规。
|
||||
|
||||
### 复盘缩短为 1h
|
||||
|
||||
任选一种方式,并填写说明:
|
||||
|
||||
| 方式 | 必填 |
|
||||
|------|------|
|
||||
| **复盘表单**提交 | 离场触发 = **手动平仓**;**离场补充** 非空(不是下方「备注」) |
|
||||
| **核对修改**保存 | 结果 = **手动平仓**;**备注** 非空 |
|
||||
|
||||
说明:
|
||||
|
||||
- 中控全平 / 实例手动平仓后,只要在 4h 窗口内完成上述操作即可降为 1h。
|
||||
- 复盘保存后会同步更新 `last_close_at_ms`,倒计时以 **最后一次手动平仓 + 当前档位数** 为准,不会继续读库内旧 4h 结束时间。
|
||||
- 1h 窗口已结束后,即使库里残留旧 `cooloff_until_ms`,状态也会恢复 **正常**。
|
||||
- 若超过「平仓 + 1h」才复盘,则从 **保存复盘时刻** 起再计 1h(不延长原 4h)。
|
||||
- **止盈 / 保本止盈 / 止损** 等自动平仓不触发风控,也不会刷新冷静期。
|
||||
- 代码更新后需 **重启对应实例** 并硬刷新页面。
|
||||
|
||||
### 倒计时与标签
|
||||
|
||||
- 结束时刻 = `last_close_at_ms + cooloff_hours`(`APP_TIMEZONE` 默认北京时间)
|
||||
- 1h / 4h 标签按实际剩余时长判断,与倒计时一致
|
||||
- 切交易日后,若冷静期已过期,自动清库内残留字段
|
||||
|
||||
## 环境变量
|
||||
|
||||
```env
|
||||
RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
TRADING_DAY_RESET_HOUR=8
|
||||
APP_TIMEZONE=Asia/Shanghai
|
||||
```
|
||||
|
||||
`RISK_COOLING_HOURS_EXTERNAL` 已废弃(外部平仓不再触发风控)。
|
||||
|
||||
## API 与 `risk_status` 字段
|
||||
|
||||
| 接口 | 说明 |
|
||||
|------|------|
|
||||
| `GET /api/account_snapshot` | 实例页轮询,含 `risk_status` |
|
||||
| `GET /api/account_risk_status` | hub_bridge 专用 |
|
||||
| `GET /api/hub/monitor` | 中控监控板,每账户含 `risk_status` |
|
||||
| `POST /api/hub/account-risk/user-close` | 中控登记用户平仓,`body: { source, count }` |
|
||||
|
||||
`risk_status` 主要字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `status` | `normal` / `freeze_1h` / `freeze_4h` / `freeze_daily` / `freeze_position` |
|
||||
| `status_label` | 中文标签 |
|
||||
| `can_trade` | 是否允许新开仓(仅风控维度) |
|
||||
| `reason` | 悬停提示文案 |
|
||||
| `active_count` / `max_active_positions` | 当前活跃持仓与 `.env` 中 `MAX_ACTIVE_POSITIONS` |
|
||||
| `cooloff_until_ms` | 1h/4h 冷静期结束时间戳(毫秒) |
|
||||
| `freeze_until_ms` | 倒计时结束时间戳(日冻结为下一交易日切点) |
|
||||
| `freeze_remaining_sec` | 服务端计算的剩余秒数(供调试) |
|
||||
|
||||
**仓位上限冻结**:当 **计入上限的** 活跃持仓数(不含趋势回调)≥ 实例 `.env` 的 `MAX_ACTIVE_POSITIONS`(默认 1)且账户无时间类冻结时,徽章显示 **仓位上限冻结**;此时 **新开仓** 被禁止,但 **顺势加仓**(在已有同向监控持仓上加仓)仍可用。仅存在趋势回调持仓时不触发该冻结。时间冻结(1h/4h/日)优先展示。
|
||||
|
||||
`risk_status.can_roll`:仓位上限冻结时为 `true`,表示顺势加仓不受该冻结限制。
|
||||
|
||||
## 前端倒计时
|
||||
|
||||
- 共用脚本:`static/account_risk_badge.js?v=4`
|
||||
- 样式:`static/account_risk_badge.css`
|
||||
- 展示格式:`4h冻结 · 3h 12m`;日冻结为距下一交易日切点剩余时间
|
||||
- 倒计时优先用服务端 `freeze_remaining_sec` 推算结束时刻,避免绝对时间戳与时区/脏数据偏差
|
||||
- 服务端在冷静期**已结束**或锚点无效时**自动清库**,避免重启后误读旧 `account_risk_state` 仍显示冻结
|
||||
- 无效的未来 `last_close_at_ms` **不会**被当作「现在」重启计时
|
||||
- 若当日手动平仓**已复盘**(journal 有说明)且 1h 窗口已过,即使 risk 表被误写也会强制恢复 **正常**
|
||||
- 勿与交易记录列表中的历史平仓时间混淆:风控只看 `account_risk_state` 表内 **最后一次用户主动平仓** 及其复盘结果
|
||||
|
||||
## 相关代码
|
||||
|
||||
- `account_risk_lib.py` — 状态机、`enrich_risk_status_countdown`、`apply_position_limit_risk`、`on_user_initiated_close`
|
||||
- `hub_bridge.py` — `/api/hub/account-risk/user-close`
|
||||
- `manual_trading_hub/hub.py` — 中控平仓成功后调用 user-close
|
||||
- `strategy_trend_register.py` — `stop_trend_pullback` 结束计划时登记风控
|
||||
- `tests/test_account_risk_lib.py`
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
# 每日自动划转(四所统一)
|
||||
|
||||
## 行为
|
||||
|
||||
在 `.env` 开启 `AUTO_TRANSFER_ENABLED=true` 后,监控轮询在**北京时间 `AUTO_TRANSFER_BJ_HOUR` 整点所在小时**内(默认 8:00–8:59)执行一次(按 **UTC 自然日** 去重):
|
||||
|
||||
| 交易账户 (`AUTO_TRANSFER_TO`,默认 swap) | 动作 |
|
||||
|------------------------------------------|------|
|
||||
| 余额 **低于** `AUTO_TRANSFER_AMOUNT` | 从 `AUTO_TRANSFER_FROM`(默认 funding)划入差额 |
|
||||
| 余额 **高于** `AUTO_TRANSFER_AMOUNT` | 将多余划回 `AUTO_TRANSFER_FROM` |
|
||||
| 与目标相差 < 0.01U | 跳过,不写划转 |
|
||||
| 存在 **active** 持仓(`order_monitors`,或 Gate 趋势回调已开仓计划) | **不划转**,写账簿 `skipped`,并**企业微信**说明「持仓中,本次资金无划转」 |
|
||||
|
||||
## 配置示例(目标 50U)
|
||||
|
||||
```env
|
||||
AUTO_TRANSFER_ENABLED=true
|
||||
AUTO_TRANSFER_AMOUNT=50
|
||||
AUTO_TRANSFER_FROM=funding
|
||||
AUTO_TRANSFER_TO=swap
|
||||
AUTO_TRANSFER_BJ_HOUR=8
|
||||
```
|
||||
|
||||
`AUTO_TRANSFER_AMOUNT` 与 `DAILY_START_CAPITAL`(每日开仓基数)**独立**。
|
||||
|
||||
API Key 须具备万向划转权限(与手动划转相同)。
|
||||
|
||||
## 用脚本更新四所 `.env`
|
||||
|
||||
详见 **[env-sync-scripts.md](./env-sync-scripts.md)**。常用命令:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
|
||||
# 仅补全划转相关项
|
||||
python scripts/sync_four_exchange_transfer_env.py
|
||||
|
||||
# 目标 50U 并开启自动划转
|
||||
python scripts/sync_four_exchange_transfer_env.py --set-amount 50 --enable-auto-transfer
|
||||
|
||||
# 计仓 + 划转一并补全
|
||||
python scripts/sync_four_exchange_env.py --set-transfer-amount 50 --enable-auto-transfer
|
||||
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate crypto-monitor-gate-bot
|
||||
```
|
||||
# 每日自动划转(三所统一)
|
||||
|
||||
## 行为
|
||||
|
||||
在 `.env` 开启 `AUTO_TRANSFER_ENABLED=true` 后,监控轮询在**北京时间 `AUTO_TRANSFER_BJ_HOUR` 整点所在小时**内(默认 8:00–8:59)执行一次(按 **UTC 自然日** 去重):
|
||||
|
||||
| 交易账户 (`AUTO_TRANSFER_TO`,默认 swap) | 动作 |
|
||||
|------------------------------------------|------|
|
||||
| 余额 **低于** `AUTO_TRANSFER_AMOUNT` | 从 `AUTO_TRANSFER_FROM`(默认 funding)划入差额 |
|
||||
| 余额 **高于** `AUTO_TRANSFER_AMOUNT` | 将多余划回 `AUTO_TRANSFER_FROM` |
|
||||
| 与目标相差 < 0.01U | 跳过,不写划转 |
|
||||
| 存在 **active** 持仓(`order_monitors`,或 Gate回调已开仓计划) | **不划转**,写账簿 `skipped`,并**企业微信**说明「持仓中,本次资金无划转」 |
|
||||
|
||||
## 配置示例(目标 50U)
|
||||
|
||||
```env
|
||||
AUTO_TRANSFER_ENABLED=true
|
||||
AUTO_TRANSFER_AMOUNT=50
|
||||
AUTO_TRANSFER_FROM=funding
|
||||
AUTO_TRANSFER_TO=swap
|
||||
AUTO_TRANSFER_BJ_HOUR=8
|
||||
```
|
||||
|
||||
`AUTO_TRANSFER_AMOUNT` 与 `DAILY_START_CAPITAL`(每日开仓基数)**独立**。
|
||||
|
||||
API Key 须具备万向划转权限(与手动划转相同)。
|
||||
|
||||
## 用脚本更新三所 `.env`
|
||||
|
||||
详见 **[env-sync-scripts.md](./env-sync-scripts.md)**。常用命令:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
|
||||
# 仅补全划转相关项
|
||||
python scripts/sync_four_exchange_transfer_env.py
|
||||
|
||||
# 目标 50U 并开启自动划转
|
||||
python scripts/sync_four_exchange_transfer_env.py --set-amount 50 --enable-auto-transfer
|
||||
|
||||
# 计仓 + 划转一并补全
|
||||
python scripts/sync_four_exchange_env.py --set-transfer-amount 50 --enable-auto-transfer
|
||||
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate
|
||||
```
|
||||
|
||||
@@ -1,81 +1,81 @@
|
||||
# 单日开仓次数限制(四所统一)
|
||||
|
||||
各交易实例(Binance / OKX / Gate / Gate_bot)在 `.env` 中独立配置,互不影响。
|
||||
|
||||
## 交易日口径
|
||||
|
||||
- 以 **北京时间** `TRADING_DAY_RESET_HOUR`(默认 **8:00**)切分交易日,与统计、顶栏「交易日」一致。
|
||||
- **次日恢复**:过了切日时刻后 `session_date` 变为新日期,计数自动归零,无需清库。
|
||||
|
||||
## 计数口径
|
||||
|
||||
每成功新建一条 `order_monitors` 记录计 **1 次**,包括:
|
||||
|
||||
- 人工「实盘下单」
|
||||
- 关键位自动开仓
|
||||
- 其他写入 `order_monitors` 的成功开仓
|
||||
|
||||
平仓后再开仍算新的一单。当日总次数到硬上限后 **当天不再允许新开**(即使已空仓)。
|
||||
|
||||
## 环境变量
|
||||
|
||||
在「交易执行 / 人工风控」段配置:
|
||||
|
||||
```env
|
||||
# 【单日开仓 AI 提醒】本交易日开仓次数达到该值时,企业微信推送 AI 克制提醒(不拦单)
|
||||
DAILY_OPEN_ALERT_THRESHOLD=5
|
||||
|
||||
# 【单日开仓硬上限】本交易日开仓次数 >= 该值后,禁止一切新开仓直至下一交易日;0=不启用
|
||||
DAILY_OPEN_HARD_LIMIT=0
|
||||
```
|
||||
|
||||
### 配置示例
|
||||
|
||||
```env
|
||||
# 保守户:3 次提醒,5 次封死
|
||||
DAILY_OPEN_ALERT_THRESHOLD=3
|
||||
DAILY_OPEN_HARD_LIMIT=5
|
||||
|
||||
# 仅提醒、不封(与旧版行为接近)
|
||||
DAILY_OPEN_ALERT_THRESHOLD=5
|
||||
DAILY_OPEN_HARD_LIMIT=0
|
||||
|
||||
# 严格户:到 3 次即封
|
||||
DAILY_OPEN_ALERT_THRESHOLD=2
|
||||
DAILY_OPEN_HARD_LIMIT=3
|
||||
```
|
||||
|
||||
建议 `DAILY_OPEN_ALERT_THRESHOLD <= DAILY_OPEN_HARD_LIMIT`(硬上限为 0 时除外)。
|
||||
|
||||
## 程序行为
|
||||
|
||||
| 次数 | 行为 |
|
||||
|------|------|
|
||||
| 未达提醒阈值 | 正常开仓 |
|
||||
| 达到 `DAILY_OPEN_ALERT_THRESHOLD` | 成功开仓后 AI 企业微信提醒 |
|
||||
| 达到 `DAILY_OPEN_HARD_LIMIT`(>0) | `precheck_risk` 拒绝人工/关键位开仓;顶栏 `can_trade=false` |
|
||||
|
||||
硬限制与以下规则 **同时生效**(取交集):
|
||||
|
||||
- `TRADING_DAY_RESET_OPEN_GUARD_ENABLED`:切日前禁止新开
|
||||
- `MAX_ACTIVE_POSITIONS`:同时持仓上限
|
||||
- Gate_bot:`precheck_trend_pullback_start` 同样校验单日硬上限
|
||||
|
||||
## 页面与接口
|
||||
|
||||
- 顶栏 / `api/account_snapshot` 返回 `opens_today`、`daily_open_hard_limit`、`daily_open_alert_threshold`。
|
||||
- 达硬上限时提示:`本交易日开仓 N/M 已达上限,次日 8:00 后恢复`(`M` 为配置的硬上限)。
|
||||
|
||||
## 部署
|
||||
|
||||
修改各实例 `.env` 后重启对应 pm2 进程,例如:
|
||||
|
||||
```bash
|
||||
pm2 restart crypto_binance crypto_okx crypto_gate crypto_gate_bot
|
||||
```
|
||||
|
||||
## 实现位置
|
||||
|
||||
- 共享逻辑:`daily_open_limit_lib.py`
|
||||
- 四所 `app.py`:`precheck_risk`、`can_trade`、`api/account_snapshot`、开仓成功后的 AI 提醒文案
|
||||
- 单元测试:`tests/test_daily_open_limit_lib.py`
|
||||
# 单日开仓次数限制(三所统一)
|
||||
|
||||
各交易实例(Binance / OKX / Gate)在 `.env` 中独立配置,互不影响。
|
||||
|
||||
## 交易日口径
|
||||
|
||||
- 以 **北京时间** `TRADING_DAY_RESET_HOUR`(默认 **8:00**)切分交易日,与统计、顶栏「交易日」一致。
|
||||
- **次日恢复**:过了切日时刻后 `session_date` 变为新日期,计数自动归零,无需清库。
|
||||
|
||||
## 计数口径
|
||||
|
||||
每成功新建一条 `order_monitors` 记录计 **1 次**,包括:
|
||||
|
||||
- 人工「实盘下单」
|
||||
- 关键位自动开仓
|
||||
- 其他写入 `order_monitors` 的成功开仓
|
||||
|
||||
平仓后再开仍算新的一单。当日总次数到硬上限后 **当天不再允许新开**(即使已空仓)。
|
||||
|
||||
## 环境变量
|
||||
|
||||
在「交易执行 / 人工风控」段配置:
|
||||
|
||||
```env
|
||||
# 【单日开仓 AI 提醒】本交易日开仓次数达到该值时,企业微信推送 AI 克制提醒(不拦单)
|
||||
DAILY_OPEN_ALERT_THRESHOLD=5
|
||||
|
||||
# 【单日开仓硬上限】本交易日开仓次数 >= 该值后,禁止一切新开仓直至下一交易日;0=不启用
|
||||
DAILY_OPEN_HARD_LIMIT=0
|
||||
```
|
||||
|
||||
### 配置示例
|
||||
|
||||
```env
|
||||
# 保守户:3 次提醒,5 次封死
|
||||
DAILY_OPEN_ALERT_THRESHOLD=3
|
||||
DAILY_OPEN_HARD_LIMIT=5
|
||||
|
||||
# 仅提醒、不封(与旧版行为接近)
|
||||
DAILY_OPEN_ALERT_THRESHOLD=5
|
||||
DAILY_OPEN_HARD_LIMIT=0
|
||||
|
||||
# 严格户:到 3 次即封
|
||||
DAILY_OPEN_ALERT_THRESHOLD=2
|
||||
DAILY_OPEN_HARD_LIMIT=3
|
||||
```
|
||||
|
||||
建议 `DAILY_OPEN_ALERT_THRESHOLD <= DAILY_OPEN_HARD_LIMIT`(硬上限为 0 时除外)。
|
||||
|
||||
## 程序行为
|
||||
|
||||
| 次数 | 行为 |
|
||||
|------|------|
|
||||
| 未达提醒阈值 | 正常开仓 |
|
||||
| 达到 `DAILY_OPEN_ALERT_THRESHOLD` | 成功开仓后 AI 企业微信提醒 |
|
||||
| 达到 `DAILY_OPEN_HARD_LIMIT`(>0) | `precheck_risk` 拒绝人工/关键位开仓;顶栏 `can_trade=false` |
|
||||
|
||||
硬限制与以下规则 **同时生效**(取交集):
|
||||
|
||||
- `TRADING_DAY_RESET_OPEN_GUARD_ENABLED`:切日前禁止新开
|
||||
- `MAX_ACTIVE_POSITIONS`:同时持仓上限
|
||||
- Gate:`precheck_trend_pullback_start` 同样校验单日硬上限
|
||||
|
||||
## 页面与接口
|
||||
|
||||
- 顶栏 / `api/account_snapshot` 返回 `opens_today`、`daily_open_hard_limit`、`daily_open_alert_threshold`。
|
||||
- 达硬上限时提示:`本交易日开仓 N/M 已达上限,次日 8:00 后恢复`(`M` 为配置的硬上限)。
|
||||
|
||||
## 部署
|
||||
|
||||
修改各实例 `.env` 后重启对应 pm2 进程,例如:
|
||||
|
||||
```bash
|
||||
pm2 restart crypto_binance crypto_okx crypto_gate
|
||||
```
|
||||
|
||||
## 实现位置
|
||||
|
||||
- 共享逻辑:`daily_open_limit_lib.py`
|
||||
- 三所 `app.py`:`precheck_risk`、`can_trade`、`api/account_snapshot`、开仓成功后的 AI 提醒文案
|
||||
- 单元测试:`tests/test_daily_open_limit_lib.py`
|
||||
|
||||
@@ -1,116 +1,116 @@
|
||||
# 四所 `.env` 同步脚本说明
|
||||
|
||||
在**仓库根目录**执行。仅处理四所实例目录下的 `.env`,**不覆盖** API 密钥与已存在的自定义值;若某目录无 `.env` 会 `SKIP`(需先 `cp .env.example .env`)。
|
||||
|
||||
| 目录 |
|
||||
|------|
|
||||
| `crypto_monitor_binance` |
|
||||
| `crypto_monitor_okx` |
|
||||
| `crypto_monitor_gate` |
|
||||
| `crypto_monitor_gate_bot` |
|
||||
|
||||
修改 `.env` 后须 **`pm2 restart`** 对应实例后生效。
|
||||
|
||||
---
|
||||
|
||||
## 一键同步(推荐)
|
||||
|
||||
`scripts/sync_four_exchange_env.py`:依次执行**计仓** + **自动划转** 两个子脚本。
|
||||
|
||||
```bash
|
||||
cd /path/to/crypto_monitor
|
||||
git pull
|
||||
|
||||
# 仅补全缺失项(已有值保留)
|
||||
python scripts/sync_four_exchange_env.py
|
||||
|
||||
# 预览,不写文件
|
||||
python scripts/sync_four_exchange_env.py --dry-run
|
||||
|
||||
# 划转目标 50U 并开启自动划转(计仓仍只补缺失项)
|
||||
python scripts/sync_four_exchange_env.py --set-transfer-amount 50 --enable-auto-transfer
|
||||
|
||||
# 无仓后切换全仓杠杆(须先确认交易所无持仓)
|
||||
python scripts/sync_four_exchange_env.py --set-mode full_margin
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 只打印将做的变更,不写 `.env` |
|
||||
| `--set-mode risk\|full_margin` | 强制四所 `POSITION_SIZING_MODE` |
|
||||
| `--set-transfer-amount U` | 强制四所 `AUTO_TRANSFER_AMOUNT` |
|
||||
| `--enable-auto-transfer` | 强制四所 `AUTO_TRANSFER_ENABLED=true` |
|
||||
|
||||
---
|
||||
|
||||
## 仅自动划转
|
||||
|
||||
`scripts/sync_four_exchange_transfer_env.py`
|
||||
|
||||
行为说明见 [auto-transfer-daily.md](./auto-transfer-daily.md)。
|
||||
|
||||
```bash
|
||||
# 补全缺失项
|
||||
python scripts/sync_four_exchange_transfer_env.py
|
||||
python scripts/sync_four_exchange_transfer_env.py --dry-run
|
||||
|
||||
# 目标 50U 并开启
|
||||
python scripts/sync_four_exchange_transfer_env.py --set-amount 50 --enable-auto-transfer
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 预览 |
|
||||
| `--set-amount U` | 强制 `AUTO_TRANSFER_AMOUNT` |
|
||||
| `--enable-auto-transfer` | 强制 `AUTO_TRANSFER_ENABLED=true` |
|
||||
|
||||
**缺项默认**(未使用 `--set-amount` 且文件中无该键时):
|
||||
|
||||
1. 若已有 `AUTO_TRANSFER_AMOUNT` → 保留
|
||||
2. 否则若存在 `DAILY_START_CAPITAL` → 沿用其值
|
||||
3. 否则 → **50**
|
||||
|
||||
补全时会写入(若缺失):`AUTO_TRANSFER_FROM=funding`、`AUTO_TRANSFER_TO=swap`、`TRANSFER_CCY=USDT`、`AUTO_TRANSFER_BJ_HOUR=8`;币安额外补 `BINANCE_FUNDING_INCLUDE_SPOT=false`。
|
||||
|
||||
---
|
||||
|
||||
## 仅计仓模式
|
||||
|
||||
`scripts/sync_four_exchange_position_sizing_env.py`
|
||||
|
||||
行为说明见 [position-sizing-mode.md](./position-sizing-mode.md)。
|
||||
|
||||
```bash
|
||||
# 补全缺失项(默认 risk、FULL_MARGIN_BUFFER_RATIO=0.98)
|
||||
python scripts/sync_four_exchange_position_sizing_env.py
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --dry-run
|
||||
|
||||
# 无仓后切全仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode full_margin
|
||||
|
||||
# 无仓后切回以损定仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode risk
|
||||
|
||||
# 强制缓冲比例
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-buffer 0.98
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 预览 |
|
||||
| `--set-mode risk\|full_margin` | 强制 `POSITION_SIZING_MODE`(**须无持仓**后 restart) |
|
||||
| `--set-buffer RATIO` | 强制 `FULL_MARGIN_BUFFER_RATIO` |
|
||||
|
||||
---
|
||||
|
||||
## 部署后重启
|
||||
|
||||
```bash
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate crypto-monitor-gate-bot
|
||||
```
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [计仓模式](./position-sizing-mode.md)
|
||||
- [每日自动划转](./auto-transfer-daily.md)
|
||||
- [部署说明](../deploy/README.md)
|
||||
# 三所 `.env` 同步脚本说明
|
||||
|
||||
在**仓库根目录**执行。仅处理三所实例目录下的 `.env`,**不覆盖** API 密钥与已存在的自定义值;若某目录无 `.env` 会 `SKIP`(需先 `cp .env.example .env`)。
|
||||
|
||||
| 目录 |
|
||||
|------|
|
||||
| `crypto_monitor_binance` |
|
||||
| `crypto_monitor_okx` |
|
||||
| `crypto_monitor_gate` |
|
||||
| `crypto_monitor_gate` |
|
||||
|
||||
修改 `.env` 后须 **`pm2 restart`** 对应实例后生效。
|
||||
|
||||
---
|
||||
|
||||
## 一键同步(推荐)
|
||||
|
||||
`scripts/sync_four_exchange_env.py`:依次执行**计仓** + **自动划转** 两个子脚本。
|
||||
|
||||
```bash
|
||||
cd /path/to/crypto_monitor
|
||||
git pull
|
||||
|
||||
# 仅补全缺失项(已有值保留)
|
||||
python scripts/sync_four_exchange_env.py
|
||||
|
||||
# 预览,不写文件
|
||||
python scripts/sync_four_exchange_env.py --dry-run
|
||||
|
||||
# 划转目标 50U 并开启自动划转(计仓仍只补缺失项)
|
||||
python scripts/sync_four_exchange_env.py --set-transfer-amount 50 --enable-auto-transfer
|
||||
|
||||
# 无仓后切换全仓杠杆(须先确认交易所无持仓)
|
||||
python scripts/sync_four_exchange_env.py --set-mode full_margin
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 只打印将做的变更,不写 `.env` |
|
||||
| `--set-mode risk\|full_margin` | 强制三所 `POSITION_SIZING_MODE` |
|
||||
| `--set-transfer-amount U` | 强制三所 `AUTO_TRANSFER_AMOUNT` |
|
||||
| `--enable-auto-transfer` | 强制三所 `AUTO_TRANSFER_ENABLED=true` |
|
||||
|
||||
---
|
||||
|
||||
## 仅自动划转
|
||||
|
||||
`scripts/sync_four_exchange_transfer_env.py`
|
||||
|
||||
行为说明见 [auto-transfer-daily.md](./auto-transfer-daily.md)。
|
||||
|
||||
```bash
|
||||
# 补全缺失项
|
||||
python scripts/sync_four_exchange_transfer_env.py
|
||||
python scripts/sync_four_exchange_transfer_env.py --dry-run
|
||||
|
||||
# 目标 50U 并开启
|
||||
python scripts/sync_four_exchange_transfer_env.py --set-amount 50 --enable-auto-transfer
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 预览 |
|
||||
| `--set-amount U` | 强制 `AUTO_TRANSFER_AMOUNT` |
|
||||
| `--enable-auto-transfer` | 强制 `AUTO_TRANSFER_ENABLED=true` |
|
||||
|
||||
**缺项默认**(未使用 `--set-amount` 且文件中无该键时):
|
||||
|
||||
1. 若已有 `AUTO_TRANSFER_AMOUNT` → 保留
|
||||
2. 否则若存在 `DAILY_START_CAPITAL` → 沿用其值
|
||||
3. 否则 → **50**
|
||||
|
||||
补全时会写入(若缺失):`AUTO_TRANSFER_FROM=funding`、`AUTO_TRANSFER_TO=swap`、`TRANSFER_CCY=USDT`、`AUTO_TRANSFER_BJ_HOUR=8`;币安额外补 `BINANCE_FUNDING_INCLUDE_SPOT=false`。
|
||||
|
||||
---
|
||||
|
||||
## 仅计仓模式
|
||||
|
||||
`scripts/sync_four_exchange_position_sizing_env.py`
|
||||
|
||||
行为说明见 [position-sizing-mode.md](./position-sizing-mode.md)。
|
||||
|
||||
```bash
|
||||
# 补全缺失项(默认 risk、FULL_MARGIN_BUFFER_RATIO=0.98)
|
||||
python scripts/sync_four_exchange_position_sizing_env.py
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --dry-run
|
||||
|
||||
# 无仓后切全仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode full_margin
|
||||
|
||||
# 无仓后切回以损定仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode risk
|
||||
|
||||
# 强制缓冲比例
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-buffer 0.98
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `--dry-run` | 预览 |
|
||||
| `--set-mode risk\|full_margin` | 强制 `POSITION_SIZING_MODE`(**须无持仓**后 restart) |
|
||||
| `--set-buffer RATIO` | 强制 `FULL_MARGIN_BUFFER_RATIO` |
|
||||
|
||||
---
|
||||
|
||||
## 部署后重启
|
||||
|
||||
```bash
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate
|
||||
```
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [计仓模式](./position-sizing-mode.md)
|
||||
- [每日自动划转](./auto-transfer-daily.md)
|
||||
- [部署说明](../deploy/README.md)
|
||||
|
||||
@@ -1,135 +1,135 @@
|
||||
# 内照明心与永久 K 线
|
||||
|
||||
## 概述
|
||||
|
||||
「内照明心」页(`/archive`)用于 **复盘语录 + 交易记录回顾 + 按需 K 线**。左侧维护每日复盘语录(最多 100 条);右侧按日期区间列出开仓记录,展示区间统计,并可展开 K 线图表对照单笔交易。
|
||||
|
||||
与行情区 `hub_kline.db`(15 天滚动缓存)**完全独立**:档案库只增不删,从建档起永久保留。
|
||||
|
||||
## 页面布局
|
||||
|
||||
| 区域 | 说明 |
|
||||
|------|------|
|
||||
| **复盘语录** | 左栏;按日期添加/编辑/删除,一日一条 |
|
||||
| **日期与筛选** | 顶栏:本日 / 本周 / 本月 / 自选区间;盈利单、亏损单、犯病、交易所、搜索 |
|
||||
| **区间统计** | 统计栏随日期选择自动更新(见下) |
|
||||
| **K 线图表** | 默认折叠;点「图表」或展开后按需加载 |
|
||||
| **交易记录** | 默认展开;犯病行 **红色字体**(无红底);可编辑标签与备注 |
|
||||
|
||||
## 日期区间
|
||||
|
||||
交易日按北京时间 **8:00** 切日(`TRADING_DAY_RESET_HOUR`)。
|
||||
|
||||
| 模式 | 范围 |
|
||||
|------|------|
|
||||
| **本日** | 可选单个交易日(默认当前交易日) |
|
||||
| **本周** | 当周周一至当前交易日 |
|
||||
| **本月** | 当月 1 日至当前交易日 |
|
||||
| **区间** | 自选 `date_from`~`date_to`(含首尾交易日) |
|
||||
|
||||
## 区间统计(统计栏)
|
||||
|
||||
基于当前 **列表筛选结果**(含盈利/亏损/犯病勾选、合约搜索;交易所下拉仍限定数据源):
|
||||
|
||||
| 指标 | 说明 |
|
||||
|------|------|
|
||||
| 总开仓次数 | 区间内开仓笔数 |
|
||||
| 盈利单 / 亏损单 | 盈亏 > 0 / < 0 的笔数(持平不计) |
|
||||
| 平均盈利 / 平均亏损 | 盈利单、亏损单各自的均值(U) |
|
||||
| 最大盈利 / 最大亏损 | 单笔最大盈利、最大亏损(U) |
|
||||
| 犯病次数 / 占比 | `behavior_tag = sick` 的笔数及占开仓比例 |
|
||||
| 盈亏 | 区间内全部已平仓盈亏合计 |
|
||||
| 剔除犯病盈亏 | 排除犯病单后的盈亏合计 |
|
||||
| 各交易所 | 每所同上分项 |
|
||||
|
||||
在搜索框输入币种(如 `BTC`)后,统计栏与下方列表同步按该条件收窄。
|
||||
|
||||
## 数据约定
|
||||
|
||||
| 项 | 约定 |
|
||||
|----|------|
|
||||
| 交易来源 | 四所 `trade_records` + 未落库的 `strategy_trade_snapshots`,经 `/api/hub/trades/archive` 拉取 |
|
||||
| 犯病标签 | 中控 `trade_overlay.behavior_tag = sick` |
|
||||
| K 线真源 | 仅 **5m** 写入 `hub_symbol_archive.db` |
|
||||
| 建档种子 | 该币 **最早开仓** 向前 **30 天** 5m |
|
||||
| 增量同步 | 默认每 **4 小时** 补新 5m 至当前 |
|
||||
| 展示周期 | Tab:**5m / 15m / 1h / 4h**,默认 **15m** |
|
||||
| 视窗模式 | **持仓过程**(锚平仓,默认)/ **进场决策**(锚开仓) |
|
||||
| 时间跳转 | 输入 `YYYY-MM-DD HH:MM` 后点「跳转」 |
|
||||
|
||||
## 存储
|
||||
|
||||
- 默认路径:`manual_trading_hub/data/hub_symbol_archive.db`
|
||||
- 环境变量:`HUB_ARCHIVE_DB_PATH`
|
||||
- 表:
|
||||
- `archive_meta` — 建档元数据
|
||||
- `archive_bars_5m` — 永久 5m K 线
|
||||
- `archive_trade_cache` — 从实例同步的交易快照
|
||||
- `trade_overlay` — 犯病标签与备注(仅中控)
|
||||
- `archive_review_quotes` — 复盘语录
|
||||
|
||||
## API(中控 FastAPI)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/archive/meta` | 周期、交易所、同步间隔等 |
|
||||
| GET | `/api/archive/daily-trades` | 区间交易列表与统计(见 query) |
|
||||
| GET | `/api/archive/quotes` | 复盘语录列表 |
|
||||
| POST | `/api/archive/quotes` | 新增语录 |
|
||||
| PATCH | `/api/archive/quotes/{id}` | 更新语录 |
|
||||
| DELETE | `/api/archive/quotes/{id}` | 删除语录 |
|
||||
| GET | `/api/archive/ohlcv` | K 线视窗(`timeframe` / `mode` / `anchor_ms` / `at`) |
|
||||
| PATCH | `/api/archive/trade/{exchange_key}/{trade_id}` | 更新标签/备注 |
|
||||
| POST | `/api/archive/sync` | 立即同步四所交易 + K 线 |
|
||||
|
||||
`GET /api/archive/daily-trades` 主要 query:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `period` | `today` / `week` / `month` / `range` |
|
||||
| `trading_day` | 本日模式下的交易日 `YYYY-MM-DD` |
|
||||
| `date_from` / `date_to` | 区间模式起止日 |
|
||||
| `exchange_key` | 可选,按交易所筛选 |
|
||||
| `filter_profit` / `filter_loss` / `filter_sick` | 过滤列表与统计 |
|
||||
| `search` | 合约 / 交易所 / 备注搜索(同步过滤列表与统计) |
|
||||
|
||||
返回 `stats` 含 `open_count`、`win_count`、`loss_count`、`win_rate`、`avg_win`、`avg_loss`、`profit_loss_ratio`、`max_win`、`max_loss`、`sick_count`、`sick_pct`、`pnl_total`、`pnl_ex_sick`、`by_exchange`。
|
||||
|
||||
实例侧:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/hub/trades/archive` | 近 N 天已平仓(`days` / `limit`) |
|
||||
|
||||
## 后台任务
|
||||
|
||||
Hub 启动后在 lifespan 中运行 `hub-archive-sync`:
|
||||
|
||||
1. 对各启用交易所调用 `/api/hub/trades/archive`
|
||||
2. 写入 `archive_trade_cache`
|
||||
3. 未建档币种:拉 30 天 5m 种子
|
||||
4. 已建档币种:增量补 5m
|
||||
|
||||
间隔:`HUB_ARCHIVE_SYNC_INTERVAL_SEC`(默认 14400)。
|
||||
|
||||
## 代码位置
|
||||
|
||||
- `hub_symbol_archive_lib.py` — 库表、区间统计、种子、增量、聚合
|
||||
- `hub_trades_lib.py` — `fetch_trades_for_archive`
|
||||
- `hub_bridge.py` — 实例 `/api/hub/trades/archive`
|
||||
- `manual_trading_hub/hub.py` — 路由与后台同步
|
||||
- `manual_trading_hub/static/archive.js` — 内照明心前端
|
||||
|
||||
## 与行情区的区别
|
||||
|
||||
| | 行情区 | 内照明心 |
|
||||
|--|--------|----------|
|
||||
| DB | `hub_kline.db` | `hub_symbol_archive.db` |
|
||||
| 保留 | 15 天滚动删除 | 建档起永久 |
|
||||
| 周期 | 多周期直存/拉取 | 仅存 5m,高周期聚合 |
|
||||
| 用途 | 实时看盘 | 复盘语录与交易回顾 |
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [中控平仓与交易记录](trend-hub-close-and-trade-records.md)
|
||||
- [中控使用说明](../manual_trading_hub/使用说明.md)
|
||||
# 内照明心与永久 K 线
|
||||
|
||||
## 概述
|
||||
|
||||
「内照明心」页(`/archive`)用于 **复盘语录 + 交易记录回顾 + 按需 K 线**。左侧维护每日复盘语录(最多 100 条);右侧按日期区间列出开仓记录,展示区间统计,并可展开 K 线图表对照单笔交易。
|
||||
|
||||
与行情区 `hub_kline.db`(15 天滚动缓存)**完全独立**:档案库只增不删,从建档起永久保留。
|
||||
|
||||
## 页面布局
|
||||
|
||||
| 区域 | 说明 |
|
||||
|------|------|
|
||||
| **复盘语录** | 左栏;按日期添加/编辑/删除,一日一条 |
|
||||
| **日期与筛选** | 顶栏:本日 / 本周 / 本月 / 自选区间;盈利单、亏损单、犯病、交易所、搜索 |
|
||||
| **区间统计** | 统计栏随日期选择自动更新(见下) |
|
||||
| **K 线图表** | 默认折叠;点「图表」或展开后按需加载 |
|
||||
| **交易记录** | 默认展开;犯病行 **红色字体**(无红底);可编辑标签与备注 |
|
||||
|
||||
## 日期区间
|
||||
|
||||
交易日按北京时间 **8:00** 切日(`TRADING_DAY_RESET_HOUR`)。
|
||||
|
||||
| 模式 | 范围 |
|
||||
|------|------|
|
||||
| **本日** | 可选单个交易日(默认当前交易日) |
|
||||
| **本周** | 当周周一至当前交易日 |
|
||||
| **本月** | 当月 1 日至当前交易日 |
|
||||
| **区间** | 自选 `date_from`~`date_to`(含首尾交易日) |
|
||||
|
||||
## 区间统计(统计栏)
|
||||
|
||||
基于当前 **列表筛选结果**(含盈利/亏损/犯病勾选、合约搜索;交易所下拉仍限定数据源):
|
||||
|
||||
| 指标 | 说明 |
|
||||
|------|------|
|
||||
| 总开仓次数 | 区间内开仓笔数 |
|
||||
| 盈利单 / 亏损单 | 盈亏 > 0 / < 0 的笔数(持平不计) |
|
||||
| 平均盈利 / 平均亏损 | 盈利单、亏损单各自的均值(U) |
|
||||
| 最大盈利 / 最大亏损 | 单笔最大盈利、最大亏损(U) |
|
||||
| 犯病次数 / 占比 | `behavior_tag = sick` 的笔数及占开仓比例 |
|
||||
| 盈亏 | 区间内全部已平仓盈亏合计 |
|
||||
| 剔除犯病盈亏 | 排除犯病单后的盈亏合计 |
|
||||
| 各交易所 | 每所同上分项 |
|
||||
|
||||
在搜索框输入币种(如 `BTC`)后,统计栏与下方列表同步按该条件收窄。
|
||||
|
||||
## 数据约定
|
||||
|
||||
| 项 | 约定 |
|
||||
|----|------|
|
||||
| 交易来源 | 三所 `trade_records` + 未落库的 `strategy_trade_snapshots`,经 `/api/hub/trades/archive` 拉取 |
|
||||
| 犯病标签 | 中控 `trade_overlay.behavior_tag = sick` |
|
||||
| K 线真源 | 仅 **5m** 写入 `hub_symbol_archive.db` |
|
||||
| 建档种子 | 该币 **最早开仓** 向前 **30 天** 5m |
|
||||
| 增量同步 | 默认每 **4 小时** 补新 5m 至当前 |
|
||||
| 展示周期 | Tab:**5m / 15m / 1h / 4h**,默认 **15m** |
|
||||
| 视窗模式 | **持仓过程**(锚平仓,默认)/ **进场决策**(锚开仓) |
|
||||
| 时间跳转 | 输入 `YYYY-MM-DD HH:MM` 后点「跳转」 |
|
||||
|
||||
## 存储
|
||||
|
||||
- 默认路径:`manual_trading_hub/data/hub_symbol_archive.db`
|
||||
- 环境变量:`HUB_ARCHIVE_DB_PATH`
|
||||
- 表:
|
||||
- `archive_meta` — 建档元数据
|
||||
- `archive_bars_5m` — 永久 5m K 线
|
||||
- `archive_trade_cache` — 从实例同步的交易快照
|
||||
- `trade_overlay` — 犯病标签与备注(仅中控)
|
||||
- `archive_review_quotes` — 复盘语录
|
||||
|
||||
## API(中控 FastAPI)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/archive/meta` | 周期、交易所、同步间隔等 |
|
||||
| GET | `/api/archive/daily-trades` | 区间交易列表与统计(见 query) |
|
||||
| GET | `/api/archive/quotes` | 复盘语录列表 |
|
||||
| POST | `/api/archive/quotes` | 新增语录 |
|
||||
| PATCH | `/api/archive/quotes/{id}` | 更新语录 |
|
||||
| DELETE | `/api/archive/quotes/{id}` | 删除语录 |
|
||||
| GET | `/api/archive/ohlcv` | K 线视窗(`timeframe` / `mode` / `anchor_ms` / `at`) |
|
||||
| PATCH | `/api/archive/trade/{exchange_key}/{trade_id}` | 更新标签/备注 |
|
||||
| POST | `/api/archive/sync` | 立即同步三所交易 + K 线 |
|
||||
|
||||
`GET /api/archive/daily-trades` 主要 query:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `period` | `today` / `week` / `month` / `range` |
|
||||
| `trading_day` | 本日模式下的交易日 `YYYY-MM-DD` |
|
||||
| `date_from` / `date_to` | 区间模式起止日 |
|
||||
| `exchange_key` | 可选,按交易所筛选 |
|
||||
| `filter_profit` / `filter_loss` / `filter_sick` | 过滤列表与统计 |
|
||||
| `search` | 合约 / 交易所 / 备注搜索(同步过滤列表与统计) |
|
||||
|
||||
返回 `stats` 含 `open_count`、`win_count`、`loss_count`、`win_rate`、`avg_win`、`avg_loss`、`profit_loss_ratio`、`max_win`、`max_loss`、`sick_count`、`sick_pct`、`pnl_total`、`pnl_ex_sick`、`by_exchange`。
|
||||
|
||||
实例侧:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/hub/trades/archive` | 近 N 天已平仓(`days` / `limit`) |
|
||||
|
||||
## 后台任务
|
||||
|
||||
Hub 启动后在 lifespan 中运行 `hub-archive-sync`:
|
||||
|
||||
1. 对各启用交易所调用 `/api/hub/trades/archive`
|
||||
2. 写入 `archive_trade_cache`
|
||||
3. 未建档币种:拉 30 天 5m 种子
|
||||
4. 已建档币种:增量补 5m
|
||||
|
||||
间隔:`HUB_ARCHIVE_SYNC_INTERVAL_SEC`(默认 14400)。
|
||||
|
||||
## 代码位置
|
||||
|
||||
- `hub_symbol_archive_lib.py` — 库表、区间统计、种子、增量、聚合
|
||||
- `hub_trades_lib.py` — `fetch_trades_for_archive`
|
||||
- `hub_bridge.py` — 实例 `/api/hub/trades/archive`
|
||||
- `manual_trading_hub/hub.py` — 路由与后台同步
|
||||
- `manual_trading_hub/static/archive.js` — 内照明心前端
|
||||
|
||||
## 与行情区的区别
|
||||
|
||||
| | 行情区 | 内照明心 |
|
||||
|--|--------|----------|
|
||||
| DB | `hub_kline.db` | `hub_symbol_archive.db` |
|
||||
| 保留 | 15 天滚动删除 | 建档起永久 |
|
||||
| 周期 | 多周期直存/拉取 | 仅存 5m,高周期聚合 |
|
||||
| 用途 | 实时看盘 | 复盘语录与交易回顾 |
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [中控平仓与交易记录](trend-hub-close-and-trade-records.md)
|
||||
- [中控使用说明](../manual_trading_hub/使用说明.md)
|
||||
|
||||
@@ -1,147 +1,147 @@
|
||||
# lib/ 共用模块结构
|
||||
|
||||
四所实例与中控共用的 Python 库、模板与静态资源统一放在仓库根目录的 **`lib/`** 下。部署单元(`crypto_monitor_*`、`manual_trading_hub`)仍保持独立目录与 PM2 配置不变。
|
||||
|
||||
**重构前快照 Git 标签**:`pre-lib-modularization`(可用 `git checkout pre-lib-modularization` 查看旧布局)。
|
||||
|
||||
---
|
||||
|
||||
## 顶层目录
|
||||
|
||||
```
|
||||
crypto_monitor/
|
||||
├── crypto_monitor_binance/ # 四所:各自 app + .env + PM2
|
||||
├── crypto_monitor_gate/
|
||||
├── crypto_monitor_gate_bot/
|
||||
├── crypto_monitor_okx/
|
||||
├── manual_trading_hub/ # 中控 + 子代理 agent
|
||||
│
|
||||
├── lib/ # 共用模块(本说明)
|
||||
│ ├── strategy/
|
||||
│ ├── key_monitor/
|
||||
│ ├── trade/
|
||||
│ ├── hub/
|
||||
│ ├── ai/
|
||||
│ ├── instance/
|
||||
│ ├── exchange/
|
||||
│ ├── common/
|
||||
│ └── paths.py
|
||||
│
|
||||
├── brand/ # 各所共用图标
|
||||
├── docs/
|
||||
├── deploy/
|
||||
├── scripts/
|
||||
├── tests/
|
||||
├── requirements.txt
|
||||
└── README.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## lib/ 子包说明
|
||||
|
||||
| 子包 | 职责 | 主要模块 |
|
||||
|------|------|----------|
|
||||
| **`lib/strategy/`** | 策略交易(顺势加仓、趋势回调、快照与记录) | `strategy_register.py`、`strategy_trend_register.py`、`strategy_db.py`、`strategy_roll_*`、`strategy_trend_*` |
|
||||
| **`lib/strategy/templates/`** | 策略页 Jinja 模板(原 `strategy_templates/`) | `strategy_trading_page.html`、`strategy_roll_panel.html` 等 |
|
||||
| **`lib/key_monitor/`** | 关键位监控、斐波、假突破、止盈止损方案 | `key_monitor_lib.py`、`fib_key_monitor_lib.py`、`key_sl_tp_lib.py` 等 |
|
||||
| **`lib/trade/`** | 下单监控展示、计仓、账户风控、手动 SL/TP | `order_monitor_display_lib.py`、`position_sizing_lib.py`、`account_risk_lib.py` 等 |
|
||||
| **`lib/hub/`** | 中控 API、K 线、归档、计仓器、SSO/Bridge | `hub_bridge.py`、`hub_kline_store.py`、`hub_trades_lib.py` 等 |
|
||||
| **`lib/ai/`** | AI 复盘与文本生成 | `ai_client.py`、`ai_review_lib.py` |
|
||||
| **`lib/instance/`** | 中控 iframe 嵌入、导航、复盘图表 | `instance_embed_lib.py`、`focus_chart_lib.py`、`journal_chart_lib.py` |
|
||||
| **`lib/instance/templates/`** | 嵌入页片段(原 `embed_templates/`) | `embed_page_fragment.html` |
|
||||
| **`lib/exchange/`** | 特定交易所工具 | `gate_transfer_lib.py`、`okx_orders_lib.py` 等 |
|
||||
| **`lib/common/`** | 跨功能小工具 | `form_submit_lib.py`、`wechat_notify_lib.py` 等 |
|
||||
| **`lib/common/static/`** | 四所与中控共用的 JS/CSS(原根目录 `static/`) | `instance_theme.js`、`strategy_roll.js` 等 |
|
||||
|
||||
> **说明**:`hub_*` 命名表示「中控侧能力或行情聚合」,但部分模块(如 `hub_volume_rank_lib`、`hub_market_info_lib`)四所 `app.py` 也会调用,并非中控独占。
|
||||
|
||||
---
|
||||
|
||||
## 路径辅助函数
|
||||
|
||||
`lib/paths.py` 集中维护资源目录,避免硬编码:
|
||||
|
||||
```python
|
||||
from lib.paths import strategy_templates_dir, embed_templates_dir, common_static_dir
|
||||
|
||||
strategy_templates_dir() # .../lib/strategy/templates
|
||||
embed_templates_dir() # .../lib/instance/templates
|
||||
common_static_dir() # .../lib/common/static
|
||||
```
|
||||
|
||||
可选传入 `repo_root`(字符串或 `Path`),默认使用 `lib/` 的上级目录即仓库根。
|
||||
|
||||
---
|
||||
|
||||
## Python 导入约定
|
||||
|
||||
各部署目录在启动时将 **仓库根** 加入 `sys.path`(与重构前相同):
|
||||
|
||||
```python
|
||||
_REPO_ROOT = os.path.dirname(BASE_DIR) # 或 Path(__file__).resolve().parent.parent
|
||||
if _REPO_ROOT not in sys.path:
|
||||
sys.path.insert(0, _REPO_ROOT)
|
||||
```
|
||||
|
||||
之后使用 **`lib.<子包>.<模块>`** 形式导入,例如:
|
||||
|
||||
```python
|
||||
from lib.strategy.strategy_db import init_strategy_tables
|
||||
from lib.key_monitor.key_monitor_lib import check_key_monitors
|
||||
from lib.hub.hub_bridge import install_on_app
|
||||
from lib.ai.ai_client import ai_review
|
||||
```
|
||||
|
||||
策略注册仍在各所 `app.py` 末尾:
|
||||
|
||||
```python
|
||||
from lib.strategy.strategy_register import install_strategy_trading
|
||||
from lib.strategy.strategy_trend_register import install_strategy_trend
|
||||
|
||||
install_strategy_trading(app, _REPO_ROOT, app_module=sys.modules[__name__])
|
||||
install_strategy_trend(app, _REPO_ROOT, app_module=sys.modules[__name__])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 静态资源与 URL
|
||||
|
||||
- 四所页面仍通过 **`/static/...`** 访问共用脚本;`hub_bridge.install_instance_theme_static` 从 `lib/common/static/` 提供部分根级静态路由。
|
||||
- 各所目录下 **`static/`**(图标、上传图片等)仍为实例私有,未迁入 `lib/`。
|
||||
- 中控 `manual_trading_hub/hub.py` 通过 `_REPO_ROOT / "lib" / "common" / "static"` 挂载与四所共用的 badge、复盘 JS 等。
|
||||
|
||||
---
|
||||
|
||||
## 测试
|
||||
|
||||
在仓库根执行(需将根目录置于 Python 路径,或从根目录运行):
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
python -m unittest discover -s tests -p "test_*.py"
|
||||
```
|
||||
|
||||
测试文件内统一 `from lib.<子包>.<模块> import ...`。使用 `@patch` 时目标写完整模块路径,例如 `lib.hub.hub_calculator_lib._resolve_market`。
|
||||
|
||||
---
|
||||
|
||||
## 迁移脚本
|
||||
|
||||
一次性迁移由 `scripts/migrate_to_lib.py` 完成(移动文件 + 批量改写 import)。**不要在已迁移后的仓库上重复执行**。
|
||||
|
||||
---
|
||||
|
||||
## 后续可选整理
|
||||
|
||||
- 四所 `app.py` 体量接近,可逐步抽取公共 `exchange_app` 基座(改动面大,单独规划)。
|
||||
- `manual_trading_hub/okx_orders_lib.py` 为 agent 本地副本,可与 `lib/exchange/okx_orders_lib.py` 合并去重。
|
||||
- 可引入 `pyproject.toml` + `pip install -e .`,替代 `sys.path.insert`(长期维护更规范)。
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [README.md](../README.md) — 总览与部署
|
||||
- [策略交易说明.md](../策略交易说明.md)
|
||||
- [manual_trading_hub/使用说明.md](../manual_trading_hub/使用说明.md)
|
||||
# lib/ 共用模块结构
|
||||
|
||||
三所实例与中控共用的 Python 库、模板与静态资源统一放在仓库根目录的 **`lib/`** 下。部署单元(`crypto_monitor_*`、`manual_trading_hub`)仍保持独立目录与 PM2 配置不变。
|
||||
|
||||
**重构前快照 Git 标签**:`pre-lib-modularization`(可用 `git checkout pre-lib-modularization` 查看旧布局)。
|
||||
**移除 gate_bot 前快照 Git 标签**:`pre-remove-gate-bot`。
|
||||
|
||||
---
|
||||
|
||||
## 顶层目录
|
||||
|
||||
```
|
||||
crypto_monitor/
|
||||
├── crypto_monitor_binance/ # 三所:各自 app + .env + PM2
|
||||
├── crypto_monitor_gate/
|
||||
├── crypto_monitor_okx/
|
||||
├── manual_trading_hub/ # 中控 + 子代理 agent
|
||||
│
|
||||
├── lib/ # 共用模块(本说明)
|
||||
│ ├── strategy/
|
||||
│ ├── key_monitor/
|
||||
│ ├── trade/
|
||||
│ ├── hub/
|
||||
│ ├── ai/
|
||||
│ ├── instance/
|
||||
│ ├── exchange/
|
||||
│ ├── common/
|
||||
│ └── paths.py
|
||||
│
|
||||
├── brand/ # 各所共用图标
|
||||
├── docs/
|
||||
├── deploy/
|
||||
├── scripts/
|
||||
├── tests/
|
||||
├── requirements.txt
|
||||
└── README.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## lib/ 子包说明
|
||||
|
||||
| 子包 | 职责 | 主要模块 |
|
||||
|------|------|----------|
|
||||
| **`lib/strategy/`** | 策略交易(顺势加仓、趋势回调、快照与记录) | `strategy_register.py`、`strategy_trend_register.py`、`strategy_db.py`、`strategy_roll_*`、`strategy_trend_*` |
|
||||
| **`lib/strategy/templates/`** | 策略页 Jinja 模板(原 `strategy_templates/`) | `strategy_trading_page.html`、`strategy_roll_panel.html` 等 |
|
||||
| **`lib/key_monitor/`** | 关键位监控、斐波、假突破、止盈止损方案 | `key_monitor_lib.py`、`fib_key_monitor_lib.py`、`key_sl_tp_lib.py` 等 |
|
||||
| **`lib/trade/`** | 下单监控展示、计仓、账户风控、手动 SL/TP | `order_monitor_display_lib.py`、`position_sizing_lib.py`、`account_risk_lib.py` 等 |
|
||||
| **`lib/hub/`** | 中控 API、K 线、归档、计仓器、SSO/Bridge | `hub_bridge.py`、`hub_kline_store.py`、`hub_trades_lib.py` 等 |
|
||||
| **`lib/ai/`** | AI 复盘与文本生成 | `ai_client.py`、`ai_review_lib.py` |
|
||||
| **`lib/instance/`** | 中控 iframe 嵌入、导航、复盘图表 | `instance_embed_lib.py`、`focus_chart_lib.py`、`journal_chart_lib.py` |
|
||||
| **`lib/instance/templates/`** | 嵌入页片段(原 `embed_templates/`) | `embed_page_fragment.html` |
|
||||
| **`lib/exchange/`** | 特定交易所工具 | `gate_transfer_lib.py`、`okx_orders_lib.py` 等 |
|
||||
| **`lib/common/`** | 跨功能小工具 | `form_submit_lib.py`、`wechat_notify_lib.py` 等 |
|
||||
| **`lib/common/static/`** | 三所与中控共用的 JS/CSS(原根目录 `static/`) | `instance_theme.js`、`strategy_roll.js` 等 |
|
||||
|
||||
> **说明**:`hub_*` 命名表示「中控侧能力或行情聚合」,但部分模块(如 `hub_volume_rank_lib`、`hub_market_info_lib`)三所 `app.py` 也会调用,并非中控独占。
|
||||
|
||||
---
|
||||
|
||||
## 路径辅助函数
|
||||
|
||||
`lib/paths.py` 集中维护资源目录,避免硬编码:
|
||||
|
||||
```python
|
||||
from lib.paths import strategy_templates_dir, embed_templates_dir, common_static_dir
|
||||
|
||||
strategy_templates_dir() # .../lib/strategy/templates
|
||||
embed_templates_dir() # .../lib/instance/templates
|
||||
common_static_dir() # .../lib/common/static
|
||||
```
|
||||
|
||||
可选传入 `repo_root`(字符串或 `Path`),默认使用 `lib/` 的上级目录即仓库根。
|
||||
|
||||
---
|
||||
|
||||
## Python 导入约定
|
||||
|
||||
各部署目录在启动时将 **仓库根** 加入 `sys.path`(与重构前相同):
|
||||
|
||||
```python
|
||||
_REPO_ROOT = os.path.dirname(BASE_DIR) # 或 Path(__file__).resolve().parent.parent
|
||||
if _REPO_ROOT not in sys.path:
|
||||
sys.path.insert(0, _REPO_ROOT)
|
||||
```
|
||||
|
||||
之后使用 **`lib.<子包>.<模块>`** 形式导入,例如:
|
||||
|
||||
```python
|
||||
from lib.strategy.strategy_db import init_strategy_tables
|
||||
from lib.key_monitor.key_monitor_lib import check_key_monitors
|
||||
from lib.hub.hub_bridge import install_on_app
|
||||
from lib.ai.ai_client import ai_review
|
||||
```
|
||||
|
||||
策略注册仍在各所 `app.py` 末尾:
|
||||
|
||||
```python
|
||||
from lib.strategy.strategy_register import install_strategy_trading
|
||||
from lib.strategy.strategy_trend_register import install_strategy_trend
|
||||
|
||||
install_strategy_trading(app, _REPO_ROOT, app_module=sys.modules[__name__])
|
||||
install_strategy_trend(app, _REPO_ROOT, app_module=sys.modules[__name__])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 静态资源与 URL
|
||||
|
||||
- 三所页面仍通过 **`/static/...`** 访问共用脚本;`hub_bridge.install_instance_theme_static` 从 `lib/common/static/` 提供部分根级静态路由。
|
||||
- 各所目录下 **`static/`**(图标、上传图片等)仍为实例私有,未迁入 `lib/`。
|
||||
- 中控 `manual_trading_hub/hub.py` 通过 `_REPO_ROOT / "lib" / "common" / "static"` 挂载与三所共用的 badge、复盘 JS 等。
|
||||
|
||||
---
|
||||
|
||||
## 测试
|
||||
|
||||
在仓库根执行(需将根目录置于 Python 路径,或从根目录运行):
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
python -m unittest discover -s tests -p "test_*.py"
|
||||
```
|
||||
|
||||
测试文件内统一 `from lib.<子包>.<模块> import ...`。使用 `@patch` 时目标写完整模块路径,例如 `lib.hub.hub_calculator_lib._resolve_market`。
|
||||
|
||||
---
|
||||
|
||||
## 迁移脚本
|
||||
|
||||
一次性迁移由 `scripts/migrate_to_lib.py` 完成(移动文件 + 批量改写 import)。**不要在已迁移后的仓库上重复执行**。
|
||||
|
||||
---
|
||||
|
||||
## 后续可选整理
|
||||
|
||||
- 三所 `app.py` 体量接近,可逐步抽取公共 `exchange_app` 基座(改动面大,单独规划)。
|
||||
- `manual_trading_hub/okx_orders_lib.py` 为 agent 本地副本,可与 `lib/exchange/okx_orders_lib.py` 合并去重。
|
||||
- 可引入 `pyproject.toml` + `pip install -e .`,替代 `sys.path.insert`(长期维护更规范)。
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [README.md](../README.md) — 总览与部署
|
||||
- [策略交易说明.md](../策略交易说明.md)
|
||||
- [manual_trading_hub/使用说明.md](../manual_trading_hub/使用说明.md)
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
# 实盘下单 · 预估盈亏比
|
||||
|
||||
## 功能
|
||||
|
||||
四所(Binance / OKX / Gate / Gate趋势)**实盘下单监控**表单中,在「开仓」按钮前显示 **预估盈亏比**。
|
||||
|
||||
- **价格模式**:填完币种、方向、止损价、止盈价后,调用 `GET /api/order_defaults` 取标记价,按几何距离计算 RR。
|
||||
- **百分比模式**:填完币种、方向、止损%、止盈% 后拉快照校验币种,再显示 RR(`止盈% / 止损%`)。
|
||||
- **固定盈亏比模式**:不显示预估盈亏比(盈亏比由输入框直接指定;仍保留原有「预估止盈」)。
|
||||
|
||||
- **以损定仓**(`POSITION_SIZING_MODE=risk`):预估风险 = 当前交易基数 × `risk%`。
|
||||
- **全仓杠杆**(`full_margin`):预估风险 = 合约可用 × 缓冲比例 × 杠杆(BTC/ETH 与山寨按 `.env` 配置)× 止损距离比例,与开仓时 `calc_risk_amount_from_plan` 一致。
|
||||
|
||||
## 前端实现
|
||||
|
||||
- 共享脚本:`static/manual_order_rr_preview.js`
|
||||
- 各所 `templates/index.html` 引入并在 `MANUAL_MIN_PLANNED_RR` 定义后执行:
|
||||
```js
|
||||
ManualOrderRrPreview.wire({ minRr: MANUAL_MIN_PLANNED_RR });
|
||||
```
|
||||
- 展示元素:`#order-rr-preview`(开仓按钮左侧)
|
||||
- 颜色:≥ 最低要求为绿色,低于为红色,无效/取价失败为红色或灰色
|
||||
|
||||
## 与提交校验
|
||||
|
||||
提交时仍走原有 `calcClientRr` / `calcClientRrFromPct` 与 `rejectManualOrderRr`;预估仅用于下单前参考,不替代服务端风控。
|
||||
|
||||
## 校验记录
|
||||
|
||||
- `node --check static/manual_order_rr_preview.js`
|
||||
- `tests/test_manual_order_rr_preview.py`:RR 公式与四所 `calc_rr_ratio` 口径一致
|
||||
# 实盘下单 · 预估盈亏比
|
||||
|
||||
## 功能
|
||||
|
||||
三所(Binance / OKX / Gate)**实盘下单监控**表单中,在「开仓」按钮前显示 **预估盈亏比**。
|
||||
|
||||
- **价格模式**:填完币种、方向、止损价、止盈价后,调用 `GET /api/order_defaults` 取标记价,按几何距离计算 RR。
|
||||
- **百分比模式**:填完币种、方向、止损%、止盈% 后拉快照校验币种,再显示 RR(`止盈% / 止损%`)。
|
||||
- **固定盈亏比模式**:不显示预估盈亏比(盈亏比由输入框直接指定;仍保留原有「预估止盈」)。
|
||||
|
||||
- **以损定仓**(`POSITION_SIZING_MODE=risk`):预估风险 = 当前交易基数 × `risk%`。
|
||||
- **全仓杠杆**(`full_margin`):预估风险 = 合约可用 × 缓冲比例 × 杠杆(BTC/ETH 与山寨按 `.env` 配置)× 止损距离比例,与开仓时 `calc_risk_amount_from_plan` 一致。
|
||||
|
||||
## 前端实现
|
||||
|
||||
- 共享脚本:`static/manual_order_rr_preview.js`
|
||||
- 各所 `templates/index.html` 引入并在 `MANUAL_MIN_PLANNED_RR` 定义后执行:
|
||||
```js
|
||||
ManualOrderRrPreview.wire({ minRr: MANUAL_MIN_PLANNED_RR });
|
||||
```
|
||||
- 展示元素:`#order-rr-preview`(开仓按钮左侧)
|
||||
- 颜色:≥ 最低要求为绿色,低于为红色,无效/取价失败为红色或灰色
|
||||
|
||||
## 与提交校验
|
||||
|
||||
提交时仍走原有 `calcClientRr` / `calcClientRrFromPct` 与 `rejectManualOrderRr`;预估仅用于下单前参考,不替代服务端风控。
|
||||
|
||||
## 校验记录
|
||||
|
||||
- `node --check static/manual_order_rr_preview.js`
|
||||
- `tests/test_manual_order_rr_preview.py`:RR 公式与三所 `calc_rr_ratio` 口径一致
|
||||
|
||||
@@ -1,57 +1,57 @@
|
||||
# 计仓模式(四所统一)
|
||||
|
||||
## 配置
|
||||
|
||||
在各实例 `.env` 中设置(**仅能通过 env 切换,修改后须重启进程**):
|
||||
|
||||
```env
|
||||
# risk(默认)= 以损定仓
|
||||
# full_margin = 全仓杠杆(合约可用保证金 × 比例)
|
||||
POSITION_SIZING_MODE=risk
|
||||
FULL_MARGIN_BUFFER_RATIO=0.98
|
||||
```
|
||||
|
||||
切换为全仓杠杆前:**交易所须无持仓**(`MAX_ACTIVE_POSITIONS` 默认 1,全仓模式会强制单仓)。
|
||||
|
||||
## 模式说明
|
||||
|
||||
| 模式 | 保证金计算 | 杠杆 | 允许入口 |
|
||||
|------|------------|------|----------|
|
||||
| `risk` | `RISK_PERCENT` × 交易资金,按止损距离反推 | 表单可选 / 同步交易所 | 实盘人工、关键位自动、趋势回调、顺势加仓 |
|
||||
| `full_margin` | **合约账户可用 USDT × `FULL_MARGIN_BUFFER_RATIO`**(保留 2 位小数) | BTC/ETH **10x**,其它 **5x**(与 `BTC_LEVERAGE`/`ALT_LEVERAGE` 一致) | **实盘人工下单**、**关键位触价开仓**;阻力/支撑仅提醒 |
|
||||
|
||||
全仓模式下:
|
||||
|
||||
- 仍校验 **计划盈亏比**(实盘用 `MANUAL_MIN_PLANNED_RR`;触价开仓用 `KEY_AUTO_MIN_PLANNED_RR`)。
|
||||
- 下单张数由 `prepare_order_amount` + 交易所 `amount_to_precision` 决定。
|
||||
- `order_monitors.initial_stop_loss` 仍记录**开仓时**止损快照;交易记录复盘以该快照为准。
|
||||
- 已存在的 **箱体突破 / 收敛突破 / 斐波 / 假突破** 监控:进程启动时**自动撤销**并企业微信通知。
|
||||
|
||||
## 不允许(全仓模式)
|
||||
|
||||
- 关键位:箱体突破、收敛突破、斐波、假突破(添加时拒绝;已存在则启动时撤销)。
|
||||
- 趋势回调、顺势加仓(策略入口返回明确错误)。
|
||||
|
||||
**允许:** 关键位 **回调触价开仓** / **突破触价开仓**(程序盯价、触达/穿越计划入场后市价成交,无交易所挂单;全仓下仅允许一条待触发)。
|
||||
|
||||
## 用脚本更新四所 `.env`
|
||||
|
||||
详见 **[env-sync-scripts.md](./env-sync-scripts.md)**。常用命令:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
|
||||
# 仅补全计仓相关项(缺省 risk、缓冲 0.98)
|
||||
python scripts/sync_four_exchange_position_sizing_env.py
|
||||
|
||||
# 无仓后切换全仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode full_margin
|
||||
|
||||
# 无仓后切回以损定仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode risk
|
||||
|
||||
# 计仓 + 划转一并补全
|
||||
python scripts/sync_four_exchange_env.py
|
||||
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate crypto-monitor-gate-bot
|
||||
```
|
||||
# 计仓模式(三所统一)
|
||||
|
||||
## 配置
|
||||
|
||||
在各实例 `.env` 中设置(**仅能通过 env 切换,修改后须重启进程**):
|
||||
|
||||
```env
|
||||
# risk(默认)= 以损定仓
|
||||
# full_margin = 全仓杠杆(合约可用保证金 × 比例)
|
||||
POSITION_SIZING_MODE=risk
|
||||
FULL_MARGIN_BUFFER_RATIO=0.98
|
||||
```
|
||||
|
||||
切换为全仓杠杆前:**交易所须无持仓**(`MAX_ACTIVE_POSITIONS` 默认 1,全仓模式会强制单仓)。
|
||||
|
||||
## 模式说明
|
||||
|
||||
| 模式 | 保证金计算 | 杠杆 | 允许入口 |
|
||||
|------|------------|------|----------|
|
||||
| `risk` | `RISK_PERCENT` × 交易资金,按止损距离反推 | 表单可选 / 同步交易所 | 实盘人工、关键位自动、趋势回调、顺势加仓 |
|
||||
| `full_margin` | **合约账户可用 USDT × `FULL_MARGIN_BUFFER_RATIO`**(保留 2 位小数) | BTC/ETH **10x**,其它 **5x**(与 `BTC_LEVERAGE`/`ALT_LEVERAGE` 一致) | **实盘人工下单**、**关键位触价开仓**;阻力/支撑仅提醒 |
|
||||
|
||||
全仓模式下:
|
||||
|
||||
- 仍校验 **计划盈亏比**(实盘用 `MANUAL_MIN_PLANNED_RR`;触价开仓用 `KEY_AUTO_MIN_PLANNED_RR`)。
|
||||
- 下单张数由 `prepare_order_amount` + 交易所 `amount_to_precision` 决定。
|
||||
- `order_monitors.initial_stop_loss` 仍记录**开仓时**止损快照;交易记录复盘以该快照为准。
|
||||
- 已存在的 **箱体突破 / 收敛突破 / 斐波 / 假突破** 监控:进程启动时**自动撤销**并企业微信通知。
|
||||
|
||||
## 不允许(全仓模式)
|
||||
|
||||
- 关键位:箱体突破、收敛突破、斐波、假突破(添加时拒绝;已存在则启动时撤销)。
|
||||
- 趋势回调、顺势加仓(策略入口返回明确错误)。
|
||||
|
||||
**允许:** 关键位 **回调触价开仓** / **突破触价开仓**(程序盯价、触达/穿越计划入场后市价成交,无交易所挂单;全仓下仅允许一条待触发)。
|
||||
|
||||
## 用脚本更新三所 `.env`
|
||||
|
||||
详见 **[env-sync-scripts.md](./env-sync-scripts.md)**。常用命令:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
|
||||
# 仅补全计仓相关项(缺省 risk、缓冲 0.98)
|
||||
python scripts/sync_four_exchange_position_sizing_env.py
|
||||
|
||||
# 无仓后切换全仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode full_margin
|
||||
|
||||
# 无仓后切回以损定仓
|
||||
python scripts/sync_four_exchange_position_sizing_env.py --set-mode risk
|
||||
|
||||
# 计仓 + 划转一并补全
|
||||
python scripts/sync_four_exchange_env.py
|
||||
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate
|
||||
```
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
# Chrome 桌面快捷方式图标说明
|
||||
|
||||
## 图标从哪来?
|
||||
|
||||
用 Chrome **「创建快捷方式」** 或 **「安装应用」** 时,桌面/开始菜单图标**不是**操作系统自带的,而是浏览器从**你打开的网站**读取的,优先级大致为:
|
||||
|
||||
1. `manifest.webmanifest` 里的 `icons`(192×192、512×512)
|
||||
2. `link rel="apple-touch-icon"`(约 180×180)
|
||||
3. `link rel="icon"` / `favicon.ico`
|
||||
4. 若都没有 → 灰色地球或网页标题首字
|
||||
|
||||
本仓库已在 **中控** 与 **四所监控页** 配置统一品牌图标(深色圆角底 + 青绿趋势线 + 简化的 K 线),与页面 UI 一致。PNG/ICO 由 **Pillow** 生成,避免损坏的 favicon 出现花屏。
|
||||
|
||||
## 文件位置
|
||||
|
||||
| 位置 | 访问路径 |
|
||||
|------|----------|
|
||||
| 源稿 | `brand/icon.svg`、`brand/icons/*.png` |
|
||||
| 中控 | `manual_trading_hub/static/icons/` → `/assets/icons/...` |
|
||||
| 四所 | `crypto_monitor_*/static/icons/` → `/static/icons/...` |
|
||||
|
||||
## 重新生成 / 同步
|
||||
|
||||
```bash
|
||||
python scripts/generate_brand_icons.py
|
||||
python scripts/sync_brand_icons.py
|
||||
git pull # 服务器部署后
|
||||
pm2 restart …
|
||||
```
|
||||
|
||||
## 快捷方式仍显示旧图标?
|
||||
|
||||
Chrome / Windows 会**缓存** favicon:
|
||||
|
||||
1. 浏览器打开站点,**Ctrl+F5** 强刷
|
||||
2. 删除旧快捷方式,重新「创建快捷方式」
|
||||
3. 必要时清除 Chrome 站点数据(该域名)后再创建
|
||||
|
||||
## 自定义图标
|
||||
|
||||
可替换 `brand/icon.svg` 后重新运行上面两条命令;或把设计好的 `icon-192.png`、`icon-512.png` 放入 `brand/icons/` 再 `sync_brand_icons.py`。
|
||||
# Chrome 桌面快捷方式图标说明
|
||||
|
||||
## 图标从哪来?
|
||||
|
||||
用 Chrome **「创建快捷方式」** 或 **「安装应用」** 时,桌面/开始菜单图标**不是**操作系统自带的,而是浏览器从**你打开的网站**读取的,优先级大致为:
|
||||
|
||||
1. `manifest.webmanifest` 里的 `icons`(192×192、512×512)
|
||||
2. `link rel="apple-touch-icon"`(约 180×180)
|
||||
3. `link rel="icon"` / `favicon.ico`
|
||||
4. 若都没有 → 灰色地球或网页标题首字
|
||||
|
||||
本仓库已在 **中控** 与 **三所监控页** 配置统一品牌图标(深色圆角底 + 青绿趋势线 + 简化的 K 线),与页面 UI 一致。PNG/ICO 由 **Pillow** 生成,避免损坏的 favicon 出现花屏。
|
||||
|
||||
## 文件位置
|
||||
|
||||
| 位置 | 访问路径 |
|
||||
|------|----------|
|
||||
| 源稿 | `brand/icon.svg`、`brand/icons/*.png` |
|
||||
| 中控 | `manual_trading_hub/static/icons/` → `/assets/icons/...` |
|
||||
| 三所 | `crypto_monitor_*/static/icons/` → `/static/icons/...` |
|
||||
|
||||
## 重新生成 / 同步
|
||||
|
||||
```bash
|
||||
python scripts/generate_brand_icons.py
|
||||
python scripts/sync_brand_icons.py
|
||||
git pull # 服务器部署后
|
||||
pm2 restart …
|
||||
```
|
||||
|
||||
## 快捷方式仍显示旧图标?
|
||||
|
||||
Chrome / Windows 会**缓存** favicon:
|
||||
|
||||
1. 浏览器打开站点,**Ctrl+F5** 强刷
|
||||
2. 删除旧快捷方式,重新「创建快捷方式」
|
||||
3. 必要时清除 Chrome 站点数据(该域名)后再创建
|
||||
|
||||
## 自定义图标
|
||||
|
||||
可替换 `brand/icon.svg` 后重新运行上面两条命令;或把设计好的 `icon-192.png`、`icon-512.png` 放入 `brand/icons/` 再 `sync_brand_icons.py`。
|
||||
|
||||
@@ -1,184 +1,184 @@
|
||||
# 趋势回调:中控平仓与交易记录(检阅备忘)
|
||||
|
||||
本文档汇总 **中控手动结束趋势计划**、**交易记录 / 策略记录** 写入规则,以及 **四所展示统一**、**补仓表计价** 相关修复,便于自行检阅与排错。
|
||||
|
||||
适用仓库:`crypto_monitor`(Binance / OKX / Gate / Gate Bot + `manual_trading_hub`)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 中控手动平仓会不会写交易记录?
|
||||
|
||||
**会。** 在实例已部署 **`80226ee` 及之后** 代码并 **重启对应 Flask** 的前提下:
|
||||
|
||||
中控点击 **「结束计划」** → 实例执行市价平仓 + 结束计划 → **同时写入**:
|
||||
|
||||
| 目标 | 表 | 页面入口 |
|
||||
|------|-----|----------|
|
||||
| 策略记录 | `strategy_trade_snapshots` | 顶栏 **策略交易记录** → 左栏「趋势回调记录」 |
|
||||
| 交易记录 | `trade_records` | 顶栏 **交易记录与复盘** |
|
||||
|
||||
手动结束的结果字段为 **「手动平仓」**(亏损时也不会被改成「止损」)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 调用链(四所统一)
|
||||
|
||||
```
|
||||
manual_trading_hub
|
||||
POST /api/trend/{exchange_id}/stop
|
||||
→ 实例 POST /api/hub/trend/stop/{plan_id}
|
||||
→ stop_trend_pullback(pid)
|
||||
→ 市价平仓 + 撤单
|
||||
→ _finalize_plan(cfg, conn, row, "手动平仓", exit_price)
|
||||
```
|
||||
|
||||
共用实现:`strategy_trend_register.py`(四所同一套,Gate Bot 的 `stop_trend_pullback` 也调用 `_finalize_plan`)。
|
||||
|
||||
---
|
||||
|
||||
## 3. `_finalize_plan` 写入顺序(修复后)
|
||||
|
||||
1. 写 **策略快照** `save_trend_plan_snapshot` → `strategy_trade_snapshots`
|
||||
2. 撤该品种挂单
|
||||
3. 若尚无 `trade_records.trend_plan_id = 计划ID`:
|
||||
- 更新当日 session 资金
|
||||
- **`insert_trade_record`** 写入交易记录
|
||||
4. 更新 `trend_pullback_plans.status`(`stopped_manual` / `stopped_sl` / `stopped_tp`)
|
||||
5. **`conn.commit()`** 一次提交
|
||||
|
||||
要点:**先写交易记录,再结束计划**,避免「计划已结束、交易记录未写入」的半成功状态。
|
||||
|
||||
---
|
||||
|
||||
## 4. 曾出现的 Bug(#4 ONDO 漏记)
|
||||
|
||||
**现象**:策略记录有(止损 -2.71U),**交易记录没有**。
|
||||
|
||||
**原因**:Gate Bot 的 `insert_trade_record` 曾 **缺少 `entry_reason` 参数**,而 `_finalize_plan` 固定传入 `entry_reason="趋势回调"`,触发:
|
||||
|
||||
```text
|
||||
TypeError: insert_trade_record() got an unexpected keyword argument 'entry_reason'
|
||||
```
|
||||
|
||||
策略快照在异常 **之前** 已插入,交易记录插入失败,故只出现在策略记录页。
|
||||
|
||||
**修复提交**:`80226ee`
|
||||
|
||||
- Gate Bot `insert_trade_record` 增加 `entry_reason`
|
||||
- `_call_insert_trade_record`:按各所函数 **签名过滤** 参数,避免未知字段导致失败
|
||||
- 调整写入顺序:交易记录 → 计划结束 → commit
|
||||
|
||||
---
|
||||
|
||||
## 5. 历史漏记补录
|
||||
|
||||
对已结束、策略快照在、交易记录缺的计划(如 #4):
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor # 或本机仓库根目录
|
||||
|
||||
# 先预览
|
||||
python scripts/backfill_trend_trade_records.py \
|
||||
--db crypto_monitor_gate_bot/crypto.db --dry-run
|
||||
|
||||
# 确认后写入
|
||||
python scripts/backfill_trend_trade_records.py \
|
||||
--db crypto_monitor_gate_bot/crypto.db --apply
|
||||
```
|
||||
|
||||
其它所将 `--db` 换成对应 `crypto.db` 路径即可。
|
||||
|
||||
---
|
||||
|
||||
## 6. 与「保本移交」的区别
|
||||
|
||||
| 操作 | 策略记录 | 交易记录 |
|
||||
|------|----------|----------|
|
||||
| 中控 **结束计划**(手动平仓) | 计划结束时写入 | **同一时刻**写入 |
|
||||
| **保本移交** | 移交时写入策略快照 | **不立即写**;持仓移交到 `order_monitors`,**后续平仓** 再写入 `trade_records` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 四所展示统一(中控 ↔ 实例)
|
||||
|
||||
### 7.1 数据 enrich 入口
|
||||
|
||||
| 场景 | 函数 |
|
||||
|------|------|
|
||||
| 实例策略页 | `enrich_trend_plan` |
|
||||
| 中控 `/api/hub/monitor` | `enrich_trend_plan_for_hub` → 同上 |
|
||||
| 补仓明细表 | `attach_trend_dca_levels` → `enrich_trend_dca_levels_with_tp` |
|
||||
|
||||
Gate Bot 在 `hub_bridge` 安装后调用 `patch_trend_hub_enrich`,与另外三所 `install_strategy_trend` 行为一致。
|
||||
|
||||
### 7.2 补仓表「触发价 / 加仓后均价」
|
||||
|
||||
**禁止**为凑均价 **反推虚构成交价**(曾错误出现做多补仓触发价 0.3941 等离谱数值)。
|
||||
|
||||
**`trend_leg_display_price`(四所唯一口径)**:
|
||||
|
||||
| 列 | 规则 |
|
||||
|----|------|
|
||||
| **触发价** | `leg_fill_prices_json` 有记录 → 实际成交价;无记录 → **计划网格价** |
|
||||
| **末档已补仓的加仓后均价** | 与顶部均价一致,取 **交易所持仓 `entry_price`**(`avg_entry_price`) |
|
||||
| **顶部均价** | 优先交易所 live `entry_price`,非计划库内估算值 |
|
||||
|
||||
修复提交:`08082eb`(移除反推成交价逻辑)。
|
||||
|
||||
### 7.3 中控静态页
|
||||
|
||||
`manual_trading_hub/static/app.js`:趋势浮盈亏计算 **优先** `trendPlan.avg_entry_price`,与计划卡一致。
|
||||
|
||||
---
|
||||
|
||||
## 8. 部署与自检
|
||||
|
||||
### 8.1 升级
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
git pull # 需含 80226ee、08082eb
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate crypto-monitor-gate-bot manual-trading-hub
|
||||
pm2 save
|
||||
```
|
||||
|
||||
### 8.2 手动平仓后自检
|
||||
|
||||
1. 中控结束一笔测试计划(或极小仓位)
|
||||
2. **策略交易记录**:出现对应条目
|
||||
3. **交易记录与复盘**:出现 `类型=趋势回调`、`结果=手动平仓`,且 `trend_plan_id` 与计划 ID 一致
|
||||
4. 若实例 flash / 日志出现「计划已结束但记账可能不完整」,说明 `insert_trade_record` 仍失败,需查 PM2 日志
|
||||
|
||||
### 8.3 相关代码文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
|------|------|
|
||||
| `strategy_trend_register.py` | `_finalize_plan`、`_call_insert_trade_record`、`enrich_trend_plan` |
|
||||
| `strategy_trend_lib.py` | `trend_leg_display_price`、`enrich_trend_dca_levels_with_tp` |
|
||||
| `strategy_snapshot_lib.py` | 策略快照写入 |
|
||||
| `hub_bridge.py` | `/api/hub/trend/stop/<pid>` |
|
||||
| `crypto_monitor_gate_bot/app.py` | `insert_trade_record`(含 `entry_reason`) |
|
||||
| `scripts/backfill_trend_trade_records.py` | 漏记交易记录补录 |
|
||||
|
||||
### 8.4 相关提交
|
||||
|
||||
| 提交 | 说明 |
|
||||
|------|------|
|
||||
| `6a4ec69` | 中控与四所趋势展示 enrich 统一 |
|
||||
| `08082eb` | 移除补仓表反推虚构成交价 |
|
||||
| `80226ee` | 修复 Gate Bot 中控平仓漏写 `trade_records` |
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关文档
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [策略交易说明.md](../策略交易说明.md) | 策略总览、策略交易记录页 |
|
||||
| [crypto_monitor_gate_bot/趋势回调策略说明.md](../crypto_monitor_gate_bot/趋势回调策略说明.md) | 趋势回调业务细则 |
|
||||
| [manual_trading_hub/使用说明.md](../manual_trading_hub/使用说明.md) | 中控监控与趋势卡布局 |
|
||||
| [hub-symbol-archive-kline.md](./hub-symbol-archive-kline.md) | 币种档案、永久 5m K 线、交易 overlay |
|
||||
|
||||
---
|
||||
|
||||
*最后整理:2026-06-07(与对话中修复项同步)*
|
||||
# 趋势回调:中控平仓与交易记录(检阅备忘)
|
||||
|
||||
本文档汇总 **中控手动结束趋势计划**、**交易记录 / 策略记录** 写入规则,以及 **三所展示统一**、**补仓表计价** 相关修复,便于自行检阅与排错。
|
||||
|
||||
适用仓库:`crypto_monitor`(Binance / OKX / + `manual_trading_hub`)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 中控手动平仓会不会写交易记录?
|
||||
|
||||
**会。** 在实例已部署 **`80226ee` 及之后** 代码并 **重启对应 Flask** 的前提下:
|
||||
|
||||
中控点击 **「结束计划」** → 实例执行市价平仓 + 结束计划 → **同时写入**:
|
||||
|
||||
| 目标 | 表 | 页面入口 |
|
||||
|------|-----|----------|
|
||||
| 策略记录 | `strategy_trade_snapshots` | 顶栏 **策略交易记录** → 左栏「趋势回调记录」 |
|
||||
| 交易记录 | `trade_records` | 顶栏 **交易记录与复盘** |
|
||||
|
||||
手动结束的结果字段为 **「手动平仓」**(亏损时也不会被改成「止损」)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 调用链(三所统一)
|
||||
|
||||
```
|
||||
manual_trading_hub
|
||||
POST /api/trend/{exchange_id}/stop
|
||||
→ 实例 POST /api/hub/trend/stop/{plan_id}
|
||||
→ stop_trend_pullback(pid)
|
||||
→ 市价平仓 + 撤单
|
||||
→ _finalize_plan(cfg, conn, row, "手动平仓", exit_price)
|
||||
```
|
||||
|
||||
共用实现:`strategy_trend_register.py`(三所同一套,各所的 `stop_trend_pullback` 也调用 `_finalize_plan`)。
|
||||
|
||||
---
|
||||
|
||||
## 3. `_finalize_plan` 写入顺序(修复后)
|
||||
|
||||
1. 写 **策略快照** `save_trend_plan_snapshot` → `strategy_trade_snapshots`
|
||||
2. 撤该品种挂单
|
||||
3. 若尚无 `trade_records.trend_plan_id = 计划ID`:
|
||||
- 更新当日 session 资金
|
||||
- **`insert_trade_record`** 写入交易记录
|
||||
4. 更新 `trend_pullback_plans.status`(`stopped_manual` / `stopped_sl` / `stopped_tp`)
|
||||
5. **`conn.commit()`** 一次提交
|
||||
|
||||
要点:**先写交易记录,再结束计划**,避免「计划已结束、交易记录未写入」的半成功状态。
|
||||
|
||||
---
|
||||
|
||||
## 4. 曾出现的 Bug(#4 ONDO 漏记)
|
||||
|
||||
**现象**:策略记录有(止损 -2.71U),**交易记录没有**。
|
||||
|
||||
**原因**:各所的 `insert_trade_record` 曾 **缺少 `entry_reason` 参数**,而 `_finalize_plan` 固定传入 `entry_reason="趋势回调"`,触发:
|
||||
|
||||
```text
|
||||
TypeError: insert_trade_record() got an unexpected keyword argument 'entry_reason'
|
||||
```
|
||||
|
||||
策略快照在异常 **之前** 已插入,交易记录插入失败,故只出现在策略记录页。
|
||||
|
||||
**修复提交**:`80226ee`
|
||||
|
||||
- `insert_trade_record` 增加 `entry_reason`
|
||||
- `_call_insert_trade_record`:按各所函数 **签名过滤** 参数,避免未知字段导致失败
|
||||
- 调整写入顺序:交易记录 → 计划结束 → commit
|
||||
|
||||
---
|
||||
|
||||
## 5. 历史漏记补录
|
||||
|
||||
对已结束、策略快照在、交易记录缺的计划(如 #4):
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor # 或本机仓库根目录
|
||||
|
||||
# 先预览
|
||||
python scripts/backfill_trend_trade_records.py \
|
||||
--db crypto_monitor_gate/crypto.db --dry-run
|
||||
|
||||
# 确认后写入
|
||||
python scripts/backfill_trend_trade_records.py \
|
||||
--db crypto_monitor_gate/crypto.db --apply
|
||||
```
|
||||
|
||||
其它所将 `--db` 换成对应 `crypto.db` 路径即可。
|
||||
|
||||
---
|
||||
|
||||
## 6. 与「保本移交」的区别
|
||||
|
||||
| 操作 | 策略记录 | 交易记录 |
|
||||
|------|----------|----------|
|
||||
| 中控 **结束计划**(手动平仓) | 计划结束时写入 | **同一时刻**写入 |
|
||||
| **保本移交** | 移交时写入策略快照 | **不立即写**;持仓移交到 `order_monitors`,**后续平仓** 再写入 `trade_records` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 三所展示统一(中控 ↔ 实例)
|
||||
|
||||
### 7.1 数据 enrich 入口
|
||||
|
||||
| 场景 | 函数 |
|
||||
|------|------|
|
||||
| 实例策略页 | `enrich_trend_plan` |
|
||||
| 中控 `/api/hub/monitor` | `enrich_trend_plan_for_hub` → 同上 |
|
||||
| 补仓明细表 | `attach_trend_dca_levels` → `enrich_trend_dca_levels_with_tp` |
|
||||
|
||||
在 `hub_bridge` 安装后调用 `patch_trend_hub_enrich`,与另外三所 `install_strategy_trend` 行为一致。
|
||||
|
||||
### 7.2 补仓表「触发价 / 加仓后均价」
|
||||
|
||||
**禁止**为凑均价 **反推虚构成交价**(曾错误出现做多补仓触发价 0.3941 等离谱数值)。
|
||||
|
||||
**`trend_leg_display_price`(三所唯一口径)**:
|
||||
|
||||
| 列 | 规则 |
|
||||
|----|------|
|
||||
| **触发价** | `leg_fill_prices_json` 有记录 → 实际成交价;无记录 → **计划网格价** |
|
||||
| **末档已补仓的加仓后均价** | 与顶部均价一致,取 **交易所持仓 `entry_price`**(`avg_entry_price`) |
|
||||
| **顶部均价** | 优先交易所 live `entry_price`,非计划库内估算值 |
|
||||
|
||||
修复提交:`08082eb`(移除反推成交价逻辑)。
|
||||
|
||||
### 7.3 中控静态页
|
||||
|
||||
`manual_trading_hub/static/app.js`:趋势浮盈亏计算 **优先** `trendPlan.avg_entry_price`,与计划卡一致。
|
||||
|
||||
---
|
||||
|
||||
## 8. 部署与自检
|
||||
|
||||
### 8.1 升级
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
git pull # 需含 80226ee、08082eb
|
||||
pm2 restart crypto-monitor-binance crypto-monitor-okx crypto-monitor-gate manual-trading-hub
|
||||
pm2 save
|
||||
```
|
||||
|
||||
### 8.2 手动平仓后自检
|
||||
|
||||
1. 中控结束一笔测试计划(或极小仓位)
|
||||
2. **策略交易记录**:出现对应条目
|
||||
3. **交易记录与复盘**:出现 `类型=趋势回调`、`结果=手动平仓`,且 `trend_plan_id` 与计划 ID 一致
|
||||
4. 若实例 flash / 日志出现「计划已结束但记账可能不完整」,说明 `insert_trade_record` 仍失败,需查 PM2 日志
|
||||
|
||||
### 8.3 相关代码文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
|------|------|
|
||||
| `strategy_trend_register.py` | `_finalize_plan`、`_call_insert_trade_record`、`enrich_trend_plan` |
|
||||
| `strategy_trend_lib.py` | `trend_leg_display_price`、`enrich_trend_dca_levels_with_tp` |
|
||||
| `strategy_snapshot_lib.py` | 策略快照写入 |
|
||||
| `hub_bridge.py` | `/api/hub/trend/stop/<pid>` |
|
||||
| `crypto_monitor_gate/app.py` | `insert_trade_record`(含 `entry_reason`) |
|
||||
| `scripts/backfill_trend_trade_records.py` | 漏记交易记录补录 |
|
||||
|
||||
### 8.4 相关提交
|
||||
|
||||
| 提交 | 说明 |
|
||||
|------|------|
|
||||
| `6a4ec69` | 中控与三所趋势展示 enrich 统一 |
|
||||
| `08082eb` | 移除补仓表反推虚构成交价 |
|
||||
| `80226ee` | 修复 中控平仓漏写 `trade_records` |
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关文档
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [策略交易说明.md](../策略交易说明.md) | 策略总览、策略交易记录页 |
|
||||
| [crypto_monitor_gate/趋势回调策略说明.md](../crypto_monitor_gate/趋势回调策略说明.md) | 趋势回调业务细则 |
|
||||
| [manual_trading_hub/使用说明.md](../manual_trading_hub/使用说明.md) | 中控监控与趋势卡布局 |
|
||||
| [hub-symbol-archive-kline.md](./hub-symbol-archive-kline.md) | 币种档案、永久 5m K 线、交易 overlay |
|
||||
|
||||
---
|
||||
|
||||
*最后整理:2026-06-07(与对话中修复项同步)*
|
||||
|
||||
@@ -1,129 +1,129 @@
|
||||
# 趋势回调策略(机器人)说明
|
||||
|
||||
本文描述 **「趋势回调」** 自动交易计划的业务规则与实现口径。
|
||||
|
||||
**四所主站**(Binance / Gate / OKX / 本目录 `crypto_monitor_gate_bot`)均在顶栏 **策略交易 → `/strategy`** 左栏提供同一套逻辑(共用 `strategy_trend_register.py`);本目录侧重 **Gate 子账户 / 机器人** 实例,可与主 Gate 账户隔离部署。
|
||||
|
||||
**检阅备忘**(中控平仓、交易记录、补仓展示、漏记补录):[docs/trend-hub-close-and-trade-records.md](../docs/trend-hub-close-and-trade-records.md)
|
||||
|
||||
---
|
||||
|
||||
## 1. 适用场景
|
||||
|
||||
- 单独用于跑策略的 **Gate.io USDT 永续** 子账户(建议与主资金隔离);其它交易所实例同理,使用各自 API 与 `crypto.db`。
|
||||
- 你已明确:**方向、止损价、补仓区间边界价、止盈价、杠杆**,并接受程序按风险预算拆分 **首仓 50% + 多档补仓 50%**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 名词与参数
|
||||
|
||||
| 名称 | 含义 |
|
||||
|------|------|
|
||||
| **合约 USDT 可用余额** | **生成预览**时通过 API 读取的 **swap 账户 USDT `free`** 快照;**确认执行**时再次读取并与快照比对偏差。 |
|
||||
| **风险比例** | 默认 **5%**:指「若整笔计划在 **补仓区间远侧边界**(做多=上沿、做空=下沿)这一侧的最坏价格结构下触及止损」,目标亏损上限约为 **可用余额快照 × 风险比例**(实现上用 `calc_risk_fraction` 与 `prepare_order_amount` 反推总张数,受交易所最小张数与精度约束)。 |
|
||||
| **止损价** | 用户填写;开仓后挂 **交易所仓位类止损触发单**(全平)。 |
|
||||
| **补仓区间边界**(库字段 `add_upper`) | 用户填写;**仅在该价位与止损价构成的区间内** 才允许程序触发剩余 50% 的市价补仓。**界面文案**:做多显示「补仓上沿」,做空显示「补仓下沿」。校验:做多 `止损 < 边界价`;做空 `止损 > 边界价`。 |
|
||||
| **止盈价** | 用户填写的 **固定价格**;**不由交易所条件止盈单触发**,由应用后台 **按标记价/行情价轮询**,达到后 **市价全平**。 |
|
||||
| **杠杆** | 计划内固定写入;用于 `set_leverage` 与名义换算。 |
|
||||
| **补仓档位数** | 默认 **5** 档(环境变量 `TREND_PULLBACK_DCA_LEGS` 可调);程序在满足最小张数前提下可能 **自动减少档数**。 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 执行流程(时间顺序)
|
||||
|
||||
### 3.0 列表时间窗(交易记录 / 计划历史)
|
||||
|
||||
- **交易记录**、**计划历史**(含预览快照)列表与 **交易记录 CSV 导出** 支持 **UTC** 时间筛选(默认 UTC 当日;可选近 24h、近 7d、自定义起止)。
|
||||
- 查询参数:`win_preset`(`utc_today` / `utc_last24h` / `utc_last7d` / `custom`)、自定义时另传 `from_utc`、`to_utc`。
|
||||
- **统计分析**页仍按北京时间 `TRADING_DAY_RESET_HOUR` 切日,不受列表窗影响。
|
||||
|
||||
### 3.1 预览阶段(不下单)
|
||||
|
||||
1. **风控**:与「机器人下单监控」**互斥**——存在活跃机器人持仓或运行中趋势计划时,不可生成预览。
|
||||
2. **读取可用余额快照** `get_available_trading_usdt()`,失败则拒绝。
|
||||
3. **计算**(写入表 `trend_pullback_previews`,并跳转带 `preview_id`):
|
||||
- 在 **补仓区间边界 ↔ 止损** 区间内生成 `N` 个补仓触发价(做多从上沿向止损、做空从下沿向止损);
|
||||
- 将 **剩余 50% 计划张数** 拆成 `N` 份写入 `leg_amounts_json`。
|
||||
4. **预览有效期**:默认 **120 秒**(`TREND_PULLBACK_PREVIEW_TTL_SECONDS`),超时须重新点「生成预览」。
|
||||
|
||||
### 3.2 确认执行(实盘)
|
||||
|
||||
5. 再次校验:预览未过期;**当前可用余额**与预览快照相对偏差 ≤ `TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT`(默认 **5%**),否则拒绝执行并要求重新预览。
|
||||
6. **首仓**:**立即市价** 开立 **总计划张数 × 50%**(不附带交易所止盈单)。
|
||||
7. **止损**:撤销旧条件单后,挂 **仅止损** 的仓位触发单;之后每次补仓成交会 **刷新** 止损挂单。
|
||||
7b. **保本移交下单监控**(可选):首仓完成且交易所有持仓后,可点击「保本移交下单监控」——将止损移至 **持仓均价 ± 偏移%**(默认 **+0.3%** 多 / **−0.3%** 空),仅当新止损 **优于** 当前止损时生效;**本次趋势计划随即结束**,持仓写入 **下单监控**(备注 **趋势回调计划**),交易所在 **同一时刻挂保本止损 + 计划止盈**;后续无论中控平仓或交易所手动平仓,均经下单监控轮询 **`reconcile_external_closes` / `check_order_monitors`** 写入 **交易记录**(含 `trend_plan_id`、开仓类型「趋势回调」),供人工核对。
|
||||
8. **补仓**:当价格 **穿越** 下一档触发价(做多为自上向下穿越,做空为自下向上穿越)时,按该档张数 **市价加仓**;直至 `N` 档执行完毕或计划结束。
|
||||
9. **止盈监控**:后台线程若发现价格触及止盈,则 **市价全平**。
|
||||
10. **止损触发**:若仓位被交易所止损打光,本地检测到 **持仓为 0** 后记账为 **止损** 并结束计划。
|
||||
11. **计划结束**:任一结束路径(止盈 / 止损 / 用户手动结束)均会 **撤单**(条件单 + 普通挂单,尽力而为)。
|
||||
|
||||
### 3.3 取消预览
|
||||
|
||||
用户可「取消预览」删除 `trend_pullback_previews` 中对应记录;过期记录会在新预览或页面加载时清理。
|
||||
|
||||
### 3.4 界面:计划历史与运行中浮动盈亏
|
||||
|
||||
- **计划历史(页顶卡片)**
|
||||
- 仅展示 **`trend_pullback_plans` 中已结束的计划**(`status != 'active'`,如止盈结束、止损结束、手动结束)。
|
||||
- **不包含**仅存在于 `trend_pullback_previews`、从未「确认执行」的预览。
|
||||
- 每行提供 **删除**:删除该计划行,并删除 `trade_records` 中 **`trend_plan_id` 与之相同** 且类型为「趋势回调」的记录(用于与计划一一对应的新数据;历史旧行若无 `trend_plan_id` 则不会随删)。
|
||||
- **运行中的计划(交易执行页)**
|
||||
- 在计划摘要下方展示 **浮盈亏(交易所)**:来自 Gate 当前持仓接口的 **未实现盈亏**(及标记价,若可得);与本地按均价估算可能略有差异,以交易所为准便于对照。
|
||||
- **补仓边界**按方向显示「补仓上沿」或「补仓下沿」(数值仍为 `add_upper` 字段)。
|
||||
- **手动保本**:表单可改偏移 %(默认见 `TREND_PULLBACK_MANUAL_BREAKEVEN_OFFSET_PCT`);成功后显示「已保本」时间与原止损(若与当前不同)。
|
||||
|
||||
### 3.5 交易记录与交易所「已实现盈亏」对齐
|
||||
|
||||
- 平仓时仍会写入一条 **`trade_records`**(`monitor_type=趋势回调`),其中的 **`pnl_amount` 等为本地估算**(`calc_pnl`,不含手续费、资金费等完整账单口径)。
|
||||
- 打开 **「交易执行」或「交易记录」** 页面时,若已配置 **`GATE_API_KEY` / `GATE_API_SECRET`**(不要求 `LIVE_TRADING_ENABLED=true`,只读即可),应用会按节流策略(同进程约 **25 秒**内最多一次)调用 Gate **`fetch_positions_history`(平仓历史)**,为尚未写入 `exchange_sync_key` 的趋势回调记录 **匹配一条平仓记录**,并回填:
|
||||
- **`exchange_realized_pnl`**:交易所口径已实现盈亏(与 App「历史仓位」更接近);
|
||||
- **`exchange_opened_at` / `exchange_closed_at`**:换算为应用时区(默认北京)下的开、平时间字符串。
|
||||
- **交易记录表**展示列「开仓(展示) / 平仓(展示) / 盈亏U(展示)」:对「趋势回调」行,若已同步则优先显示交易所字段(界面小字 **「所」**);未同步前仍显示本地复盘字段(小字 **「估」**)。
|
||||
- 匹配规则概要:同品种、同方向、平仓时间与本地 `closed_at` 接近,并结合 **`trend_plan_id`** 对应计划的 `opened_at` 收窄时间窗;极端情况下若短时间多笔同向同品种,仍存在错配可能,可对照 `exchange_sync_key` 与交易所记录。
|
||||
|
||||
---
|
||||
|
||||
## 4. 与「机器人下单监控」的差异
|
||||
|
||||
| 项目 | 机器人下单监控 | 趋势回调 |
|
||||
|------|------------------|----------|
|
||||
| 开仓 | 单次市价 + 条件止盈+止损 | 首仓 50% 市价 + 多档补仓 + **仅止损在交易所** |
|
||||
| 止盈 | 条件单 + 本地监控 | **仅本地监控市价止盈** |
|
||||
| 仓位基数 | 以损定仓(表单/会话基数) | **可用余额快照 × 风险比例** 推导 |
|
||||
| 移动保本 | 支持(按 R 自动上移) | **保本移交**(结束计划→下单监控;交易所 TP+SL;**无**自动 R 保本) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 风险声明(必读)
|
||||
|
||||
- 市价单存在 **滑点**;极端行情下实际亏损可能 **大于** 理论 5%。
|
||||
- 补仓触发依赖应用 **轮询间隔**(`MONITOR_POLL_SECONDS`),非毫秒级高频。
|
||||
- 交易所 **最小张数 / 精度** 可能导致计划张数被截断,实际风险略低于或偏离纸面计算。
|
||||
- 请使用 **单独 API Key / 子账户**,并先在 `LIVE_TRADING_ENABLED=false` 环境验证流程(若需沙盒请自行对接测试网,本仓库默认实盘接口)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 相关环境变量
|
||||
|
||||
| 变量 | 说明 | 默认 |
|
||||
|------|------|------|
|
||||
| `TREND_PULLBACK_MANUAL_BREAKEVEN_OFFSET_PCT` | 手动保本默认偏移(相对持仓均价,%) | `0.3` |
|
||||
| `TREND_PULLBACK_DCA_LEGS` | 剩余 50% 拆档数量上限 | `5` |
|
||||
| `TREND_PULLBACK_PREVIEW_TTL_SECONDS` | 预览有效时间(秒) | `120` |
|
||||
| `TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT` | 确认执行时允许「当前可用 / 预览快照」最大相对偏差(%) | `5` |
|
||||
| `MONITOR_POLL_SECONDS` | 监控轮询间隔(秒) | `3` |
|
||||
| `LIVE_TRADING_ENABLED` | 是否允许真实下单 | `false` |
|
||||
| `FULL_MARGIN_BUFFER_RATIO` | 计划保证金相对可用余额上限比例 | `0.98` |
|
||||
| `APP_TIMEZONE` | 应用墙钟与「北京日期」同步起点时区(如 `Asia/Shanghai`) | `Asia/Shanghai` |
|
||||
| `EXCHANGE_POSITION_SYNC_FROM_BJ` | 拉取 Gate **平仓历史** 的最早日期(`YYYY-MM-DD`,按 `APP_TIMEZONE` 当日 **00:00** 起算)。**留空**则从近 **90 天** 起拉取 | 空 |
|
||||
| `EXCHANGE_POSITION_HISTORY_LIMIT` | 单次拉取平仓历史条数上限(50–1000) | `200` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据库
|
||||
|
||||
- **`trend_pullback_previews`**:未执行的预览行(含 `expires_at_ms`),执行成功或取消后删除;过期可被清理。
|
||||
- **`trend_pullback_plans`**:趋势回调计划。执行后写入一行,`status='active'` 表示运行中;止盈 / 止损 / 手动结束后变为 **`stopped_tp` / `stopped_sl` / `stopped_manual`** 等非 `active` 状态,并出现在页顶 **计划历史**。字段含快照可用余额、计划保证金、总张数、首仓张数、补仓 JSON、网格价 JSON、已补仓档数、均价、`opened_at`、`message`(结束说明)等;**`add_upper`** 存补仓区间远侧边界价(做多=上沿、做空=下沿)。
|
||||
- **`trade_records`**(`monitor_type=趋势回调`):每次计划结束插入一行;含本地估算盈亏等。新写入行带 **`trend_plan_id`** 指向 `trend_pullback_plans.id`。另含 **`exchange_realized_pnl`、`exchange_opened_at`、`exchange_closed_at`、`exchange_sync_key`**,由页面触发的交易所平仓历史同步填充(见 3.5)。
|
||||
|
||||
**CSV 导出**:交易记录导出为 **v3**,包含上述交易所对齐字段及 `trend_plan_id`。
|
||||
# 趋势回调策略说明
|
||||
|
||||
本文描述 **「趋势回调」** 自动交易计划的业务规则与实现口径。
|
||||
|
||||
**三所主站**(Binance / Gate / OKX)均在顶栏 **策略交易 → `/strategy`** 左栏提供同一套逻辑(共用 `strategy_trend_register.py`);各所使用各自 API 与 `crypto.db`。
|
||||
|
||||
**检阅备忘**(中控平仓、交易记录、补仓展示、漏记补录):[trend-hub-close-and-trade-records.md](./trend-hub-close-and-trade-records.md)
|
||||
|
||||
---
|
||||
|
||||
## 1. 适用场景
|
||||
|
||||
- 各 **USDT 永续** 实例独立部署,使用各自 API 与 `crypto.db`。
|
||||
- 你已明确:**方向、止损价、补仓区间边界价、止盈价、杠杆**,并接受程序按风险预算拆分 **首仓 50% + 多档补仓 50%**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 名词与参数
|
||||
|
||||
| 名称 | 含义 |
|
||||
|------|------|
|
||||
| **合约 USDT 可用余额** | **生成预览**时通过 API 读取的 **swap 账户 USDT `free`** 快照;**确认执行**时再次读取并与快照比对偏差。 |
|
||||
| **风险比例** | 默认 **5%**:指「若整笔计划在 **补仓区间远侧边界**(做多=上沿、做空=下沿)这一侧的最坏价格结构下触及止损」,目标亏损上限约为 **可用余额快照 × 风险比例**(实现上用 `calc_risk_fraction` 与 `prepare_order_amount` 反推总张数,受交易所最小张数与精度约束)。 |
|
||||
| **止损价** | 用户填写;开仓后挂 **交易所仓位类止损触发单**(全平)。 |
|
||||
| **补仓区间边界**(库字段 `add_upper`) | 用户填写;**仅在该价位与止损价构成的区间内** 才允许程序触发剩余 50% 的市价补仓。**界面文案**:做多显示「补仓上沿」,做空显示「补仓下沿」。校验:做多 `止损 < 边界价`;做空 `止损 > 边界价`。 |
|
||||
| **止盈价** | 用户填写的 **固定价格**;**不由交易所条件止盈单触发**,由应用后台 **按标记价/行情价轮询**,达到后 **市价全平**。 |
|
||||
| **杠杆** | 计划内固定写入;用于 `set_leverage` 与名义换算。 |
|
||||
| **补仓档位数** | 默认 **5** 档(环境变量 `TREND_PULLBACK_DCA_LEGS` 可调);程序在满足最小张数前提下可能 **自动减少档数**。 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 执行流程(时间顺序)
|
||||
|
||||
### 3.0 列表时间窗(交易记录 / 计划历史)
|
||||
|
||||
- **交易记录**、**计划历史**(含预览快照)列表与 **交易记录 CSV 导出** 支持 **UTC** 时间筛选(默认 UTC 当日;可选近 24h、近 7d、自定义起止)。
|
||||
- 查询参数:`win_preset`(`utc_today` / `utc_last24h` / `utc_last7d` / `custom`)、自定义时另传 `from_utc`、`to_utc`。
|
||||
- **统计分析**页仍按北京时间 `TRADING_DAY_RESET_HOUR` 切日,不受列表窗影响。
|
||||
|
||||
### 3.1 预览阶段(不下单)
|
||||
|
||||
1. **风控**:与「机器人下单监控」**互斥**——存在活跃机器人持仓或运行中趋势计划时,不可生成预览。
|
||||
2. **读取可用余额快照** `get_available_trading_usdt()`,失败则拒绝。
|
||||
3. **计算**(写入表 `trend_pullback_previews`,并跳转带 `preview_id`):
|
||||
- 在 **补仓区间边界 ↔ 止损** 区间内生成 `N` 个补仓触发价(做多从上沿向止损、做空从下沿向止损);
|
||||
- 将 **剩余 50% 计划张数** 拆成 `N` 份写入 `leg_amounts_json`。
|
||||
4. **预览有效期**:默认 **120 秒**(`TREND_PULLBACK_PREVIEW_TTL_SECONDS`),超时须重新点「生成预览」。
|
||||
|
||||
### 3.2 确认执行(实盘)
|
||||
|
||||
5. 再次校验:预览未过期;**当前可用余额**与预览快照相对偏差 ≤ `TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT`(默认 **5%**),否则拒绝执行并要求重新预览。
|
||||
6. **首仓**:**立即市价** 开立 **总计划张数 × 50%**(不附带交易所止盈单)。
|
||||
7. **止损**:撤销旧条件单后,挂 **仅止损** 的仓位触发单;之后每次补仓成交会 **刷新** 止损挂单。
|
||||
7b. **保本移交下单监控**(可选):首仓完成且交易所有持仓后,可点击「保本移交下单监控」——将止损移至 **持仓均价 ± 偏移%**(默认 **+0.3%** 多 / **−0.3%** 空),仅当新止损 **优于** 当前止损时生效;**本次趋势计划随即结束**,持仓写入 **下单监控**(备注 **趋势回调计划**),交易所在 **同一时刻挂保本止损 + 计划止盈**;后续无论中控平仓或交易所手动平仓,均经下单监控轮询 **`reconcile_external_closes` / `check_order_monitors`** 写入 **交易记录**(含 `trend_plan_id`、开仓类型「趋势回调」),供人工核对。
|
||||
8. **补仓**:当价格 **穿越** 下一档触发价(做多为自上向下穿越,做空为自下向上穿越)时,按该档张数 **市价加仓**;直至 `N` 档执行完毕或计划结束。
|
||||
9. **止盈监控**:后台线程若发现价格触及止盈,则 **市价全平**。
|
||||
10. **止损触发**:若仓位被交易所止损打光,本地检测到 **持仓为 0** 后记账为 **止损** 并结束计划。
|
||||
11. **计划结束**:任一结束路径(止盈 / 止损 / 用户手动结束)均会 **撤单**(条件单 + 普通挂单,尽力而为)。
|
||||
|
||||
### 3.3 取消预览
|
||||
|
||||
用户可「取消预览」删除 `trend_pullback_previews` 中对应记录;过期记录会在新预览或页面加载时清理。
|
||||
|
||||
### 3.4 界面:计划历史与运行中浮动盈亏
|
||||
|
||||
- **计划历史(页顶卡片)**
|
||||
- 仅展示 **`trend_pullback_plans` 中已结束的计划**(`status != 'active'`,如止盈结束、止损结束、手动结束)。
|
||||
- **不包含**仅存在于 `trend_pullback_previews`、从未「确认执行」的预览。
|
||||
- 每行提供 **删除**:删除该计划行,并删除 `trade_records` 中 **`trend_plan_id` 与之相同** 且类型为「趋势回调」的记录(用于与计划一一对应的新数据;历史旧行若无 `trend_plan_id` 则不会随删)。
|
||||
- **运行中的计划(交易执行页)**
|
||||
- 在计划摘要下方展示 **浮盈亏(交易所)**:来自 Gate 当前持仓接口的 **未实现盈亏**(及标记价,若可得);与本地按均价估算可能略有差异,以交易所为准便于对照。
|
||||
- **补仓边界**按方向显示「补仓上沿」或「补仓下沿」(数值仍为 `add_upper` 字段)。
|
||||
- **手动保本**:表单可改偏移 %(默认见 `TREND_PULLBACK_MANUAL_BREAKEVEN_OFFSET_PCT`);成功后显示「已保本」时间与原止损(若与当前不同)。
|
||||
|
||||
### 3.5 交易记录与交易所「已实现盈亏」对齐
|
||||
|
||||
- 平仓时仍会写入一条 **`trade_records`**(`monitor_type=趋势回调`),其中的 **`pnl_amount` 等为本地估算**(`calc_pnl`,不含手续费、资金费等完整账单口径)。
|
||||
- 打开 **「交易执行」或「交易记录」** 页面时,若已配置 **`GATE_API_KEY` / `GATE_API_SECRET`**(不要求 `LIVE_TRADING_ENABLED=true`,只读即可),应用会按节流策略(同进程约 **25 秒**内最多一次)调用 Gate **`fetch_positions_history`(平仓历史)**,为尚未写入 `exchange_sync_key` 的趋势回调记录 **匹配一条平仓记录**,并回填:
|
||||
- **`exchange_realized_pnl`**:交易所口径已实现盈亏(与 App「历史仓位」更接近);
|
||||
- **`exchange_opened_at` / `exchange_closed_at`**:换算为应用时区(默认北京)下的开、平时间字符串。
|
||||
- **交易记录表**展示列「开仓(展示) / 平仓(展示) / 盈亏U(展示)」:对「趋势回调」行,若已同步则优先显示交易所字段(界面小字 **「所」**);未同步前仍显示本地复盘字段(小字 **「估」**)。
|
||||
- 匹配规则概要:同品种、同方向、平仓时间与本地 `closed_at` 接近,并结合 **`trend_plan_id`** 对应计划的 `opened_at` 收窄时间窗;极端情况下若短时间多笔同向同品种,仍存在错配可能,可对照 `exchange_sync_key` 与交易所记录。
|
||||
|
||||
---
|
||||
|
||||
## 4. 与「机器人下单监控」的差异
|
||||
|
||||
| 项目 | 机器人下单监控 | 趋势回调 |
|
||||
|------|------------------|----------|
|
||||
| 开仓 | 单次市价 + 条件止盈+止损 | 首仓 50% 市价 + 多档补仓 + **仅止损在交易所** |
|
||||
| 止盈 | 条件单 + 本地监控 | **仅本地监控市价止盈** |
|
||||
| 仓位基数 | 以损定仓(表单/会话基数) | **可用余额快照 × 风险比例** 推导 |
|
||||
| 移动保本 | 支持(按 R 自动上移) | **保本移交**(结束计划→下单监控;交易所 TP+SL;**无**自动 R 保本) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 风险声明(必读)
|
||||
|
||||
- 市价单存在 **滑点**;极端行情下实际亏损可能 **大于** 理论 5%。
|
||||
- 补仓触发依赖应用 **轮询间隔**(`MONITOR_POLL_SECONDS`),非毫秒级高频。
|
||||
- 交易所 **最小张数 / 精度** 可能导致计划张数被截断,实际风险略低于或偏离纸面计算。
|
||||
- 请使用 **单独 API Key / 子账户**,并先在 `LIVE_TRADING_ENABLED=false` 环境验证流程(若需沙盒请自行对接测试网,本仓库默认实盘接口)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 相关环境变量
|
||||
|
||||
| 变量 | 说明 | 默认 |
|
||||
|------|------|------|
|
||||
| `TREND_PULLBACK_MANUAL_BREAKEVEN_OFFSET_PCT` | 手动保本默认偏移(相对持仓均价,%) | `0.3` |
|
||||
| `TREND_PULLBACK_DCA_LEGS` | 剩余 50% 拆档数量上限 | `5` |
|
||||
| `TREND_PULLBACK_PREVIEW_TTL_SECONDS` | 预览有效时间(秒) | `120` |
|
||||
| `TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT` | 确认执行时允许「当前可用 / 预览快照」最大相对偏差(%) | `5` |
|
||||
| `MONITOR_POLL_SECONDS` | 监控轮询间隔(秒) | `3` |
|
||||
| `LIVE_TRADING_ENABLED` | 是否允许真实下单 | `false` |
|
||||
| `FULL_MARGIN_BUFFER_RATIO` | 计划保证金相对可用余额上限比例 | `0.98` |
|
||||
| `APP_TIMEZONE` | 应用墙钟与「北京日期」同步起点时区(如 `Asia/Shanghai`) | `Asia/Shanghai` |
|
||||
| `EXCHANGE_POSITION_SYNC_FROM_BJ` | 拉取 Gate **平仓历史** 的最早日期(`YYYY-MM-DD`,按 `APP_TIMEZONE` 当日 **00:00** 起算)。**留空**则从近 **90 天** 起拉取 | 空 |
|
||||
| `EXCHANGE_POSITION_HISTORY_LIMIT` | 单次拉取平仓历史条数上限(50–1000) | `200` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据库
|
||||
|
||||
- **`trend_pullback_previews`**:未执行的预览行(含 `expires_at_ms`),执行成功或取消后删除;过期可被清理。
|
||||
- **`trend_pullback_plans`**:趋势回调计划。执行后写入一行,`status='active'` 表示运行中;止盈 / 止损 / 手动结束后变为 **`stopped_tp` / `stopped_sl` / `stopped_manual`** 等非 `active` 状态,并出现在页顶 **计划历史**。字段含快照可用余额、计划保证金、总张数、首仓张数、补仓 JSON、网格价 JSON、已补仓档数、均价、`opened_at`、`message`(结束说明)等;**`add_upper`** 存补仓区间远侧边界价(做多=上沿、做空=下沿)。
|
||||
- **`trade_records`**(`monitor_type=趋势回调`):每次计划结束插入一行;含本地估算盈亏等。新写入行带 **`trend_plan_id`** 指向 `trend_pullback_plans.id`。另含 **`exchange_realized_pnl`、`exchange_opened_at`、`exchange_closed_at`、`exchange_sync_key`**,由页面触发的交易所平仓历史同步填充(见 3.5)。
|
||||
|
||||
**CSV 导出**:交易记录导出为 **v3**,包含上述交易所对齐字段及 `trend_plan_id`。
|
||||
@@ -1,160 +1,169 @@
|
||||
# Ubuntu 服务器部署与环境说明
|
||||
|
||||
本文档为 **生产环境唯一推荐路径**:**Ubuntu**、**root** 用户、代码目录 **`/opt/crypto_monitor`**、进程托管 **PM2**。不使用 Windows 部署、不使用 systemd/screen/nohup 托管应用(SSH 隧道除外)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 系统要求
|
||||
|
||||
| 项 | 要求 |
|
||||
|----|------|
|
||||
| 操作系统 | **Ubuntu 22.04 LTS** 或 **24.04 LTS**(64 位) |
|
||||
| 运行用户 | **root**(下文命令均按 root 编写) |
|
||||
| 项目路径 | **`/opt/crypto_monitor`**(整仓克隆到此目录) |
|
||||
| 进程管理 | **PM2**(全局安装,见 §3) |
|
||||
| 网络 | 能 `git clone` 私有仓库;访问交易所不稳定时需 **SSH SOCKS**(见各所《部署文档》) |
|
||||
|
||||
---
|
||||
|
||||
## 2. Python 环境
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| **版本** | **Python 3.10 或 3.11**(`python3 --version` ≥ 3.10);脚本会拒绝 3.9 及以下 |
|
||||
| **虚拟环境** | 每个子项目独立 **`.venv`**(`deploy/setup_env.sh` 自动创建) |
|
||||
| **依赖文件** | 四所监控共用仓库根目录 **`requirements.txt`**;中控用 **`manual_trading_hub/requirements.txt`** |
|
||||
| **SOCKS** | 走代理时必须安装 **PySocks**(已写入 requirements) |
|
||||
|
||||
### 2.1 系统包(root)
|
||||
|
||||
```bash
|
||||
apt update
|
||||
apt install -y python3 python3-pip python3-venv curl git ca-certificates
|
||||
# 若 python3 为 3.10:
|
||||
apt install -y python3.10-venv
|
||||
# 若为 3.12:
|
||||
apt install -y python3.12-venv
|
||||
```
|
||||
|
||||
### 2.2 一键创建各目录 venv
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
bash deploy/setup_env.sh --install-system-deps
|
||||
# 或已是 root 且已装 venv 包:
|
||||
bash deploy/setup_env.sh
|
||||
```
|
||||
|
||||
完成后各目录使用 **`.venv/bin/python`** 运行 `app.py` / `hub.py`;**PM2 的 ecosystem 脚本已指向该解释器**。
|
||||
|
||||
---
|
||||
|
||||
## 3. Node.js 与 PM2
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| **Node.js** | 建议 **18 LTS** 或 **20 LTS**(用于安装 PM2;应用本体为 Python) |
|
||||
| **PM2** | 全局安装,托管所有 Flask 与中控/子代理 |
|
||||
|
||||
### 3.1 安装 Node + PM2(root)
|
||||
|
||||
```bash
|
||||
# 方式 A:NodeSource(示例 Node 20)
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs
|
||||
node -v # v20.x
|
||||
npm -v
|
||||
|
||||
npm install -g pm2
|
||||
pm2 -v
|
||||
pm2 startup # 按提示执行,保证重启后 PM2 自启
|
||||
```
|
||||
|
||||
`deploy/setup_env.sh` 在检测到 Node 时也会尝试 `npm install -g pm2`(未装 Node 则跳过并提示手动安装)。
|
||||
|
||||
### 3.2 PM2 启动顺序(推荐)
|
||||
|
||||
```bash
|
||||
# 1) 四所 Flask(在各子目录执行,或分别 start)
|
||||
cd /opt/crypto_monitor/crypto_monitor_binance && pm2 start ecosystem.config.cjs
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate && pm2 start ecosystem.config.cjs
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate_bot && pm2 start ecosystem.config.cjs
|
||||
cd /opt/crypto_monitor/crypto_monitor_okx && pm2 start ecosystem.config.cjs
|
||||
|
||||
# 2) 中控 + 四子代理(一条配置 5 进程)
|
||||
cd /opt/crypto_monitor/manual_trading_hub
|
||||
pm2 start ecosystem.config.cjs
|
||||
|
||||
pm2 save
|
||||
pm2 list
|
||||
```
|
||||
|
||||
升级代码后:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor && git pull
|
||||
# 若 requirements 有变,对各目录 .venv/bin/pip install -r ...
|
||||
pm2 restart all # 或按进程名 restart
|
||||
```
|
||||
|
||||
**不要** 再用 systemd unit、screen、nohup 启动 `app.py` / `hub.py` / `agent.py`,避免与 PM2 抢端口。
|
||||
|
||||
### 3.3 常见 PM2 进程名
|
||||
|
||||
| 目录 | ecosystem 内典型名称 |
|
||||
|------|---------------------|
|
||||
| `crypto_monitor_binance` | `crypto-monitor-binance` |
|
||||
| `crypto_monitor_gate` | `crypto-monitor-gate` |
|
||||
| `crypto_monitor_gate_bot` | `crypto-monitor-gate-bot` |
|
||||
| `crypto_monitor_okx` | `crypto-monitor-okx` |
|
||||
| `manual_trading_hub` | `manual-trading-hub`、`manual-agent-*` |
|
||||
|
||||
以各目录 **`ecosystem.config.cjs`** 为准。
|
||||
|
||||
---
|
||||
|
||||
## 4. 目录与权限
|
||||
|
||||
```bash
|
||||
mkdir -p /opt
|
||||
cd /opt
|
||||
git clone https://git.bz121.com/dekun/crypto_monitor.git crypto_monitor
|
||||
chown -R root:root /opt/crypto_monitor
|
||||
```
|
||||
|
||||
- 数据库默认:各所 **`crypto.db`**(SQLite)
|
||||
- 备份目录建议:**`/root/backups`**(见 [备份与恢复.md](../备份与恢复.md))
|
||||
- **`.env`**:仅本机编辑,**勿提交 Git**;升级前 `cp .env .env.backup.$(date +%Y%m%d)`
|
||||
|
||||
---
|
||||
|
||||
## 5. SSH 动态转发(SOCKS)
|
||||
|
||||
若交易所 API 需经境外 VPS:
|
||||
|
||||
- 在本机用 **`ssh -N -D 127.0.0.1:1080 别名`** 建立隧道(配置见各所《部署文档》`~/.ssh/config`)
|
||||
- 隧道进程可用 **tmux** 或 **autossh** 保持常驻;**不必** 也不建议把 `ssh` 交给 PM2
|
||||
- 各所 `.env` 设置对应 `*_SOCKS_PROXY=socks5h://127.0.0.1:1080`
|
||||
|
||||
---
|
||||
|
||||
## 6. 部署后检查
|
||||
|
||||
```bash
|
||||
# 中控验收(需已 start hub)
|
||||
bash /opt/crypto_monitor/manual_trading_hub/scripts/verify_hub_deploy.sh
|
||||
|
||||
pm2 logs manual-trading-hub --lines 50
|
||||
curl -sS http://127.0.0.1:5100/api/monitor/board | head
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 相关文档
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [deploy/README.md](../deploy/README.md) | `setup_env.sh` 参数说明 |
|
||||
| [备份与恢复.md](../备份与恢复.md) | 数据库与 `.env` 备份 |
|
||||
| 各 `crypto_monitor_*/部署文档.md` | 交易所 SOCKS、`.env`、PM2 细节 |
|
||||
| [manual_trading_hub/部署文档.md](../manual_trading_hub/部署文档.md) | 中控 PM2、端口、反代 |
|
||||
# Ubuntu 服务器部署与环境说明
|
||||
|
||||
本文档为 **生产环境唯一推荐路径**:**Ubuntu**、**root** 用户、代码目录 **`/opt/crypto_monitor`**、进程托管 **PM2**。不使用 Windows 部署、不使用 systemd/screen/nohup 托管应用(SSH 隧道除外)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 系统要求
|
||||
|
||||
| 项 | 要求 |
|
||||
|----|------|
|
||||
| 操作系统 | **Ubuntu 22.04 LTS** 或 **24.04 LTS**(64 位) |
|
||||
| 运行用户 | **root**(下文命令均按 root 编写) |
|
||||
| 项目路径 | **`/opt/crypto_monitor`**(整仓克隆到此目录) |
|
||||
| 进程管理 | **PM2**(全局安装,见 §3) |
|
||||
| 网络 | 能 `git clone` 私有仓库;访问交易所不稳定时需 **SSH SOCKS**(见各所《部署文档》) |
|
||||
|
||||
---
|
||||
|
||||
## 2. Python 环境
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| **版本** | **Python 3.10 或 3.11**(`python3 --version` ≥ 3.10);脚本会拒绝 3.9 及以下 |
|
||||
| **虚拟环境** | 每个子项目独立 **`.venv`**(`deploy/setup_env.sh` 自动创建) |
|
||||
| **依赖文件** | 三所监控共用仓库根目录 **`requirements.txt`**;中控用 **`manual_trading_hub/requirements.txt`** |
|
||||
| **SOCKS** | 走代理时必须安装 **PySocks**(已写入 requirements) |
|
||||
|
||||
### 2.1 系统包(root)
|
||||
|
||||
```bash
|
||||
apt update
|
||||
apt install -y python3 python3-pip python3-venv curl git ca-certificates
|
||||
# 若 python3 为 3.10:
|
||||
apt install -y python3.10-venv
|
||||
# 若为 3.12:
|
||||
apt install -y python3.12-venv
|
||||
```
|
||||
|
||||
### 2.2 一键创建各目录 venv
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
bash deploy/setup_env.sh --install-system-deps
|
||||
# 或已是 root 且已装 venv 包:
|
||||
bash deploy/setup_env.sh
|
||||
```
|
||||
|
||||
完成后各目录使用 **`.venv/bin/python`** 运行 `app.py` / `hub.py`;**PM2 的 ecosystem 脚本已指向该解释器**。
|
||||
|
||||
---
|
||||
|
||||
## 3. Node.js 与 PM2
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| **Node.js** | 建议 **18 LTS** 或 **20 LTS**(用于安装 PM2;应用本体为 Python) |
|
||||
| **PM2** | 全局安装,托管所有 Flask 与中控/子代理 |
|
||||
|
||||
### 3.1 安装 Node + PM2(root)
|
||||
|
||||
```bash
|
||||
# 方式 A:NodeSource(示例 Node 20)
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs
|
||||
node -v # v20.x
|
||||
npm -v
|
||||
|
||||
npm install -g pm2
|
||||
pm2 -v
|
||||
pm2 startup # 按提示执行,保证重启后 PM2 自启
|
||||
```
|
||||
|
||||
`deploy/setup_env.sh` 在检测到 Node 时也会尝试 `npm install -g pm2`(未装 Node 则跳过并提示手动安装)。
|
||||
|
||||
### 3.2 PM2 启动顺序(推荐)
|
||||
|
||||
```bash
|
||||
# 1) 三所 Flask(在各子目录执行,或分别 start)
|
||||
cd /opt/crypto_monitor/crypto_monitor_binance && pm2 start ecosystem.config.cjs
|
||||
cd /opt/crypto_monitor/crypto_monitor_gate && pm2 start ecosystem.config.cjs
|
||||
cd /opt/crypto_monitor/crypto_monitor_okx && pm2 start ecosystem.config.cjs
|
||||
|
||||
# 2) 中控 + 三子代理(一条配置 4 进程:hub + 3 agent)
|
||||
cd /opt/crypto_monitor/manual_trading_hub
|
||||
pm2 start ecosystem.config.cjs
|
||||
|
||||
pm2 save
|
||||
pm2 list
|
||||
```
|
||||
|
||||
升级代码后:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor && git pull
|
||||
# 若 requirements 有变,对各目录 .venv/bin/pip install -r ...
|
||||
pm2 restart all # 或按进程名 restart
|
||||
```
|
||||
|
||||
**不要** 再用 systemd unit、screen、nohup 启动 `app.py` / `hub.py` / `agent.py`,避免与 PM2 抢端口。
|
||||
|
||||
### 3.3 常见 PM2 进程名
|
||||
|
||||
| 目录 | ecosystem 内典型名称 |
|
||||
|------|---------------------|
|
||||
| `crypto_monitor_binance` | `crypto_binance` |
|
||||
| `crypto_monitor_gate` | `crypto_gate` |
|
||||
| `crypto_monitor_okx` | `crypto_okx` |
|
||||
| `manual_trading_hub` | `manual-trading-hub`、`manual-agent-*` |
|
||||
|
||||
以各目录 **`ecosystem.config.cjs`** 为准。
|
||||
|
||||
### 3.4 整目录重装(清库 / 去脏 PM2)
|
||||
|
||||
保留 `.env`、丢弃旧库与旧 PM2 名单时,见 **[deploy/reinstall-plan-b.md](../deploy/reinstall-plan-b.md)**:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor
|
||||
bash deploy/reinstall.sh --yes
|
||||
```
|
||||
|
||||
首次安装仍只用 `deploy/setup_env.sh`,二者互不影响。
|
||||
|
||||
---
|
||||
|
||||
## 4. 目录与权限
|
||||
|
||||
```bash
|
||||
mkdir -p /opt
|
||||
cd /opt
|
||||
git clone https://git.bz121.com/dekun/crypto_monitor.git crypto_monitor
|
||||
chown -R root:root /opt/crypto_monitor
|
||||
```
|
||||
|
||||
- 数据库默认:各所 **`crypto.db`**(SQLite)
|
||||
- 备份目录建议:**`/root/backups`**(见 [备份与恢复.md](../备份与恢复.md))
|
||||
- **`.env`**:仅本机编辑,**勿提交 Git**;升级前 `cp .env .env.backup.$(date +%Y%m%d)`
|
||||
|
||||
---
|
||||
|
||||
## 5. SSH 动态转发(SOCKS)
|
||||
|
||||
若交易所 API 需经境外 VPS:
|
||||
|
||||
- 在本机用 **`ssh -N -D 127.0.0.1:1080 别名`** 建立隧道(配置见各所《部署文档》`~/.ssh/config`)
|
||||
- 隧道进程可用 **tmux** 或 **autossh** 保持常驻;**不必** 也不建议把 `ssh` 交给 PM2
|
||||
- 各所 `.env` 设置对应 `*_SOCKS_PROXY=socks5h://127.0.0.1:1080`
|
||||
|
||||
---
|
||||
|
||||
## 6. 部署后检查
|
||||
|
||||
```bash
|
||||
# 中控验收(需已 start hub)
|
||||
bash /opt/crypto_monitor/manual_trading_hub/scripts/verify_hub_deploy.sh
|
||||
|
||||
pm2 logs manual-trading-hub --lines 50
|
||||
curl -sS http://127.0.0.1:5100/api/monitor/board | head
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 相关文档
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [deploy/README.md](../deploy/README.md) | `setup_env.sh` 参数说明 |
|
||||
| [备份与恢复.md](../备份与恢复.md) | 数据库与 `.env` 备份 |
|
||||
| 各 `crypto_monitor_*/部署文档.md` | 交易所 SOCKS、`.env`、PM2 细节 |
|
||||
| [manual_trading_hub/部署文档.md](../manual_trading_hub/部署文档.md) | 中控 PM2、端口、反代 |
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""AI 日复盘 / 周复盘:附图收集与 journal 文本格式化(四所共用)。"""
|
||||
"""AI 日复盘 / 周复盘:附图收集与 journal 文本格式化(三所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
@@ -46,7 +46,7 @@ def journal_row_lines_for_ai(
|
||||
*,
|
||||
include_hold_duration: bool = True,
|
||||
) -> str:
|
||||
"""把 journal 字段拼成给 AI 的文本;四所日复盘/周复盘共用。"""
|
||||
"""把 journal 字段拼成给 AI 的文本;三所日复盘/周复盘共用。"""
|
||||
lines = [
|
||||
(
|
||||
f"{idx}. {_journal_nz(_row_get(row, 'coin'))} {_journal_nz(_row_get(row, 'tf'))} "
|
||||
|
||||
@@ -1,150 +1,150 @@
|
||||
/* 账户风控状态徽章 — 四所实例 + 中控共用;兼容 data-theme light/dark */
|
||||
|
||||
:root,
|
||||
html[data-theme="dark"] {
|
||||
--risk-normal-fg: #9cf0c4;
|
||||
--risk-normal-bg: rgba(36, 140, 96, 0.16);
|
||||
--risk-normal-border: rgba(72, 190, 130, 0.42);
|
||||
--risk-normal-glow: rgba(72, 190, 130, 0.35);
|
||||
|
||||
--risk-1h-fg: #ffd27a;
|
||||
--risk-1h-bg: rgba(210, 150, 40, 0.16);
|
||||
--risk-1h-border: rgba(230, 170, 60, 0.45);
|
||||
--risk-1h-glow: rgba(230, 170, 60, 0.32);
|
||||
|
||||
--risk-4h-fg: #ffab8a;
|
||||
--risk-4h-bg: rgba(210, 90, 55, 0.16);
|
||||
--risk-4h-border: rgba(230, 110, 70, 0.48);
|
||||
--risk-4h-glow: rgba(230, 110, 70, 0.34);
|
||||
|
||||
--risk-daily-fg: #ff9ec4;
|
||||
--risk-daily-bg: rgba(190, 55, 100, 0.18);
|
||||
--risk-daily-border: rgba(210, 75, 120, 0.5);
|
||||
--risk-daily-glow: rgba(210, 75, 120, 0.36);
|
||||
|
||||
--risk-position-fg: #8ec8ff;
|
||||
--risk-position-bg: rgba(55, 120, 210, 0.18);
|
||||
--risk-position-border: rgba(75, 145, 230, 0.48);
|
||||
--risk-position-glow: rgba(75, 145, 230, 0.34);
|
||||
|
||||
--risk-badge-shadow: 0 1px 2px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
html[data-theme="light"] {
|
||||
--risk-normal-fg: #056b44;
|
||||
--risk-normal-bg: rgba(10, 143, 92, 0.14);
|
||||
--risk-normal-border: rgba(8, 122, 80, 0.38);
|
||||
--risk-normal-glow: rgba(10, 143, 92, 0.22);
|
||||
|
||||
--risk-1h-fg: #8a5a00;
|
||||
--risk-1h-bg: rgba(200, 140, 20, 0.14);
|
||||
--risk-1h-border: rgba(170, 115, 10, 0.38);
|
||||
--risk-1h-glow: rgba(200, 140, 20, 0.2);
|
||||
|
||||
--risk-4h-fg: #a83812;
|
||||
--risk-4h-bg: rgba(210, 85, 35, 0.12);
|
||||
--risk-4h-border: rgba(180, 65, 25, 0.36);
|
||||
--risk-4h-glow: rgba(210, 85, 35, 0.2);
|
||||
|
||||
--risk-daily-fg: #9a1248;
|
||||
--risk-daily-bg: rgba(180, 35, 80, 0.1);
|
||||
--risk-daily-border: rgba(155, 28, 68, 0.34);
|
||||
--risk-daily-glow: rgba(180, 35, 80, 0.18);
|
||||
|
||||
--risk-position-fg: #0b5cab;
|
||||
--risk-position-bg: rgba(20, 100, 190, 0.12);
|
||||
--risk-position-border: rgba(15, 85, 165, 0.36);
|
||||
--risk-position-glow: rgba(20, 100, 190, 0.2);
|
||||
|
||||
--risk-badge-shadow: 0 1px 2px rgba(20, 50, 80, 0.1);
|
||||
}
|
||||
|
||||
.risk-status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.76rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
line-height: 1.15;
|
||||
padding: 5px 12px 5px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--risk-border, transparent);
|
||||
background: var(--risk-bg, transparent);
|
||||
color: var(--risk-fg, inherit);
|
||||
box-shadow: var(--risk-badge-shadow);
|
||||
white-space: nowrap;
|
||||
vertical-align: middle;
|
||||
transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
/* 中控 iframe 内切页:避免徽章过渡动画造成 header 闪动 */
|
||||
html[data-hub-linked="1"] .header-row .risk-status-badge {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.risk-status-badge::before {
|
||||
content: "";
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, currentColor 30%, transparent),
|
||||
0 0 8px var(--risk-glow, currentColor);
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.risk-status-normal {
|
||||
--risk-fg: var(--risk-normal-fg);
|
||||
--risk-bg: var(--risk-normal-bg);
|
||||
--risk-border: var(--risk-normal-border);
|
||||
--risk-glow: var(--risk-normal-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_1h {
|
||||
--risk-fg: var(--risk-1h-fg);
|
||||
--risk-bg: var(--risk-1h-bg);
|
||||
--risk-border: var(--risk-1h-border);
|
||||
--risk-glow: var(--risk-1h-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_4h {
|
||||
--risk-fg: var(--risk-4h-fg);
|
||||
--risk-bg: var(--risk-4h-bg);
|
||||
--risk-border: var(--risk-4h-border);
|
||||
--risk-glow: var(--risk-4h-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_daily {
|
||||
--risk-fg: var(--risk-daily-fg);
|
||||
--risk-bg: var(--risk-daily-bg);
|
||||
--risk-border: var(--risk-daily-border);
|
||||
--risk-glow: var(--risk-daily-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_position {
|
||||
--risk-fg: var(--risk-position-fg);
|
||||
--risk-bg: var(--risk-position-bg);
|
||||
--risk-border: var(--risk-position-border);
|
||||
--risk-glow: var(--risk-position-glow);
|
||||
}
|
||||
|
||||
/* 实例页:与交易所标签并排 */
|
||||
.header-row .risk-status-badge {
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
/* 中控卡片标题内 */
|
||||
.card-title .risk-status-badge,
|
||||
.hub-tile-name .risk-status-badge {
|
||||
font-size: 0.7rem;
|
||||
padding: 3px 10px 3px 8px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.card-title .risk-status-badge::before,
|
||||
.hub-tile-name .risk-status-badge::before {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
/* 账户风控状态徽章 — 三所实例 + 中控共用;兼容 data-theme light/dark */
|
||||
|
||||
:root,
|
||||
html[data-theme="dark"] {
|
||||
--risk-normal-fg: #9cf0c4;
|
||||
--risk-normal-bg: rgba(36, 140, 96, 0.16);
|
||||
--risk-normal-border: rgba(72, 190, 130, 0.42);
|
||||
--risk-normal-glow: rgba(72, 190, 130, 0.35);
|
||||
|
||||
--risk-1h-fg: #ffd27a;
|
||||
--risk-1h-bg: rgba(210, 150, 40, 0.16);
|
||||
--risk-1h-border: rgba(230, 170, 60, 0.45);
|
||||
--risk-1h-glow: rgba(230, 170, 60, 0.32);
|
||||
|
||||
--risk-4h-fg: #ffab8a;
|
||||
--risk-4h-bg: rgba(210, 90, 55, 0.16);
|
||||
--risk-4h-border: rgba(230, 110, 70, 0.48);
|
||||
--risk-4h-glow: rgba(230, 110, 70, 0.34);
|
||||
|
||||
--risk-daily-fg: #ff9ec4;
|
||||
--risk-daily-bg: rgba(190, 55, 100, 0.18);
|
||||
--risk-daily-border: rgba(210, 75, 120, 0.5);
|
||||
--risk-daily-glow: rgba(210, 75, 120, 0.36);
|
||||
|
||||
--risk-position-fg: #8ec8ff;
|
||||
--risk-position-bg: rgba(55, 120, 210, 0.18);
|
||||
--risk-position-border: rgba(75, 145, 230, 0.48);
|
||||
--risk-position-glow: rgba(75, 145, 230, 0.34);
|
||||
|
||||
--risk-badge-shadow: 0 1px 2px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
html[data-theme="light"] {
|
||||
--risk-normal-fg: #056b44;
|
||||
--risk-normal-bg: rgba(10, 143, 92, 0.14);
|
||||
--risk-normal-border: rgba(8, 122, 80, 0.38);
|
||||
--risk-normal-glow: rgba(10, 143, 92, 0.22);
|
||||
|
||||
--risk-1h-fg: #8a5a00;
|
||||
--risk-1h-bg: rgba(200, 140, 20, 0.14);
|
||||
--risk-1h-border: rgba(170, 115, 10, 0.38);
|
||||
--risk-1h-glow: rgba(200, 140, 20, 0.2);
|
||||
|
||||
--risk-4h-fg: #a83812;
|
||||
--risk-4h-bg: rgba(210, 85, 35, 0.12);
|
||||
--risk-4h-border: rgba(180, 65, 25, 0.36);
|
||||
--risk-4h-glow: rgba(210, 85, 35, 0.2);
|
||||
|
||||
--risk-daily-fg: #9a1248;
|
||||
--risk-daily-bg: rgba(180, 35, 80, 0.1);
|
||||
--risk-daily-border: rgba(155, 28, 68, 0.34);
|
||||
--risk-daily-glow: rgba(180, 35, 80, 0.18);
|
||||
|
||||
--risk-position-fg: #0b5cab;
|
||||
--risk-position-bg: rgba(20, 100, 190, 0.12);
|
||||
--risk-position-border: rgba(15, 85, 165, 0.36);
|
||||
--risk-position-glow: rgba(20, 100, 190, 0.2);
|
||||
|
||||
--risk-badge-shadow: 0 1px 2px rgba(20, 50, 80, 0.1);
|
||||
}
|
||||
|
||||
.risk-status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.76rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
line-height: 1.15;
|
||||
padding: 5px 12px 5px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--risk-border, transparent);
|
||||
background: var(--risk-bg, transparent);
|
||||
color: var(--risk-fg, inherit);
|
||||
box-shadow: var(--risk-badge-shadow);
|
||||
white-space: nowrap;
|
||||
vertical-align: middle;
|
||||
transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
/* 中控 iframe 内切页:避免徽章过渡动画造成 header 闪动 */
|
||||
html[data-hub-linked="1"] .header-row .risk-status-badge {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.risk-status-badge::before {
|
||||
content: "";
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, currentColor 30%, transparent),
|
||||
0 0 8px var(--risk-glow, currentColor);
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.risk-status-normal {
|
||||
--risk-fg: var(--risk-normal-fg);
|
||||
--risk-bg: var(--risk-normal-bg);
|
||||
--risk-border: var(--risk-normal-border);
|
||||
--risk-glow: var(--risk-normal-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_1h {
|
||||
--risk-fg: var(--risk-1h-fg);
|
||||
--risk-bg: var(--risk-1h-bg);
|
||||
--risk-border: var(--risk-1h-border);
|
||||
--risk-glow: var(--risk-1h-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_4h {
|
||||
--risk-fg: var(--risk-4h-fg);
|
||||
--risk-bg: var(--risk-4h-bg);
|
||||
--risk-border: var(--risk-4h-border);
|
||||
--risk-glow: var(--risk-4h-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_daily {
|
||||
--risk-fg: var(--risk-daily-fg);
|
||||
--risk-bg: var(--risk-daily-bg);
|
||||
--risk-border: var(--risk-daily-border);
|
||||
--risk-glow: var(--risk-daily-glow);
|
||||
}
|
||||
|
||||
.risk-status-freeze_position {
|
||||
--risk-fg: var(--risk-position-fg);
|
||||
--risk-bg: var(--risk-position-bg);
|
||||
--risk-border: var(--risk-position-border);
|
||||
--risk-glow: var(--risk-position-glow);
|
||||
}
|
||||
|
||||
/* 实例页:与交易所标签并排 */
|
||||
.header-row .risk-status-badge {
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
/* 中控卡片标题内 */
|
||||
.card-title .risk-status-badge,
|
||||
.hub-tile-name .risk-status-badge {
|
||||
font-size: 0.7rem;
|
||||
padding: 3px 10px 3px 8px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.card-title .risk-status-badge::before,
|
||||
.hub-tile-name .risk-status-badge::before {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
@@ -1,120 +1,120 @@
|
||||
/**
|
||||
* 账户风控徽章倒计时 — 四所实例 + 中控共用。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function formatRemaining(totalSec) {
|
||||
const sec = Math.max(0, Math.floor(Number(totalSec) || 0));
|
||||
if (sec <= 0) return "";
|
||||
const h = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
if (h > 0) return `${h}h ${String(m).padStart(2, "0")}m`;
|
||||
if (m > 0) return `${m}m ${String(s).padStart(2, "0")}s`;
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
function baseLabel(riskStatus, el) {
|
||||
if (riskStatus && riskStatus.status_label) return String(riskStatus.status_label);
|
||||
if (el && el.dataset && el.dataset.statusLabel) return String(el.dataset.statusLabel);
|
||||
return "正常";
|
||||
}
|
||||
|
||||
function resolveFreezeUntilMs(riskStatus) {
|
||||
if (!riskStatus) return null;
|
||||
const sec = Number(riskStatus.freeze_remaining_sec);
|
||||
if (Number.isFinite(sec) && sec > 0) {
|
||||
return Date.now() + sec * 1000;
|
||||
}
|
||||
const until = Number(riskStatus.freeze_until_ms);
|
||||
return Number.isFinite(until) && until > 0 ? until : null;
|
||||
}
|
||||
|
||||
function badgeText(riskStatus) {
|
||||
const label = baseLabel(riskStatus, null);
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
if (!until || until <= Date.now()) return label;
|
||||
const cd = formatRemaining((until - Date.now()) / 1000);
|
||||
return cd ? `${label} · ${cd}` : label;
|
||||
}
|
||||
|
||||
function setNormalBadge(el) {
|
||||
el.className = "risk-status-badge risk-status-normal";
|
||||
el.dataset.statusLabel = "正常";
|
||||
el.textContent = "正常";
|
||||
el.title = "";
|
||||
if (el.dataset) delete el.dataset.freezeUntilMs;
|
||||
}
|
||||
|
||||
function refreshElement(el) {
|
||||
if (!el) return;
|
||||
const label = baseLabel(null, el);
|
||||
const until = Number(el.dataset && el.dataset.freezeUntilMs);
|
||||
if (!Number.isFinite(until) || until <= Date.now()) {
|
||||
if (el.dataset && el.dataset.freezeUntilMs) {
|
||||
setNormalBadge(el);
|
||||
} else {
|
||||
el.textContent = label;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const cd = formatRemaining((until - Date.now()) / 1000);
|
||||
el.textContent = cd ? `${label} · ${cd}` : label;
|
||||
}
|
||||
|
||||
function applyToElement(el, riskStatus) {
|
||||
if (!el || !riskStatus) return;
|
||||
const st = riskStatus.status || "normal";
|
||||
el.className = "risk-status-badge risk-status-" + st;
|
||||
el.dataset.statusLabel = baseLabel(riskStatus, el);
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
if (until) {
|
||||
el.dataset.freezeUntilMs = String(until);
|
||||
} else if (el.dataset) {
|
||||
delete el.dataset.freezeUntilMs;
|
||||
}
|
||||
el.textContent = badgeText(riskStatus);
|
||||
el.title = riskStatus.reason || "";
|
||||
}
|
||||
|
||||
function formatBadgeHtml(riskStatus, esc) {
|
||||
if (!riskStatus || typeof riskStatus !== "object") return "";
|
||||
const safe = typeof esc === "function" ? esc : (s) => String(s);
|
||||
const st = riskStatus.status || "normal";
|
||||
const label = safe(riskStatus.status_label || "正常");
|
||||
const title = safe(riskStatus.reason || "");
|
||||
const text = safe(badgeText(riskStatus));
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
const untilAttr =
|
||||
until != null
|
||||
? ` data-freeze-until-ms="${safe(String(Math.floor(until)))}"`
|
||||
: "";
|
||||
return (
|
||||
`<span class="risk-status-badge risk-status-${safe(st)}" role="status"` +
|
||||
` title="${title}" data-status-label="${label}"${untilAttr}>${text}</span>`
|
||||
);
|
||||
}
|
||||
|
||||
function tickAll(root) {
|
||||
const scope = root || document;
|
||||
scope.querySelectorAll(".risk-status-badge[data-freeze-until-ms]").forEach(refreshElement);
|
||||
}
|
||||
|
||||
let timer = null;
|
||||
function startTicker() {
|
||||
if (timer) return;
|
||||
tickAll();
|
||||
timer = setInterval(() => tickAll(), 1000);
|
||||
}
|
||||
|
||||
global.AccountRiskBadge = {
|
||||
formatRemaining,
|
||||
badgeText,
|
||||
refreshElement,
|
||||
applyToElement,
|
||||
formatBadgeHtml,
|
||||
tickAll,
|
||||
startTicker,
|
||||
};
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
/**
|
||||
* 账户风控徽章倒计时 — 三所实例 + 中控共用。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function formatRemaining(totalSec) {
|
||||
const sec = Math.max(0, Math.floor(Number(totalSec) || 0));
|
||||
if (sec <= 0) return "";
|
||||
const h = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
if (h > 0) return `${h}h ${String(m).padStart(2, "0")}m`;
|
||||
if (m > 0) return `${m}m ${String(s).padStart(2, "0")}s`;
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
function baseLabel(riskStatus, el) {
|
||||
if (riskStatus && riskStatus.status_label) return String(riskStatus.status_label);
|
||||
if (el && el.dataset && el.dataset.statusLabel) return String(el.dataset.statusLabel);
|
||||
return "正常";
|
||||
}
|
||||
|
||||
function resolveFreezeUntilMs(riskStatus) {
|
||||
if (!riskStatus) return null;
|
||||
const sec = Number(riskStatus.freeze_remaining_sec);
|
||||
if (Number.isFinite(sec) && sec > 0) {
|
||||
return Date.now() + sec * 1000;
|
||||
}
|
||||
const until = Number(riskStatus.freeze_until_ms);
|
||||
return Number.isFinite(until) && until > 0 ? until : null;
|
||||
}
|
||||
|
||||
function badgeText(riskStatus) {
|
||||
const label = baseLabel(riskStatus, null);
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
if (!until || until <= Date.now()) return label;
|
||||
const cd = formatRemaining((until - Date.now()) / 1000);
|
||||
return cd ? `${label} · ${cd}` : label;
|
||||
}
|
||||
|
||||
function setNormalBadge(el) {
|
||||
el.className = "risk-status-badge risk-status-normal";
|
||||
el.dataset.statusLabel = "正常";
|
||||
el.textContent = "正常";
|
||||
el.title = "";
|
||||
if (el.dataset) delete el.dataset.freezeUntilMs;
|
||||
}
|
||||
|
||||
function refreshElement(el) {
|
||||
if (!el) return;
|
||||
const label = baseLabel(null, el);
|
||||
const until = Number(el.dataset && el.dataset.freezeUntilMs);
|
||||
if (!Number.isFinite(until) || until <= Date.now()) {
|
||||
if (el.dataset && el.dataset.freezeUntilMs) {
|
||||
setNormalBadge(el);
|
||||
} else {
|
||||
el.textContent = label;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const cd = formatRemaining((until - Date.now()) / 1000);
|
||||
el.textContent = cd ? `${label} · ${cd}` : label;
|
||||
}
|
||||
|
||||
function applyToElement(el, riskStatus) {
|
||||
if (!el || !riskStatus) return;
|
||||
const st = riskStatus.status || "normal";
|
||||
el.className = "risk-status-badge risk-status-" + st;
|
||||
el.dataset.statusLabel = baseLabel(riskStatus, el);
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
if (until) {
|
||||
el.dataset.freezeUntilMs = String(until);
|
||||
} else if (el.dataset) {
|
||||
delete el.dataset.freezeUntilMs;
|
||||
}
|
||||
el.textContent = badgeText(riskStatus);
|
||||
el.title = riskStatus.reason || "";
|
||||
}
|
||||
|
||||
function formatBadgeHtml(riskStatus, esc) {
|
||||
if (!riskStatus || typeof riskStatus !== "object") return "";
|
||||
const safe = typeof esc === "function" ? esc : (s) => String(s);
|
||||
const st = riskStatus.status || "normal";
|
||||
const label = safe(riskStatus.status_label || "正常");
|
||||
const title = safe(riskStatus.reason || "");
|
||||
const text = safe(badgeText(riskStatus));
|
||||
const until = resolveFreezeUntilMs(riskStatus);
|
||||
const untilAttr =
|
||||
until != null
|
||||
? ` data-freeze-until-ms="${safe(String(Math.floor(until)))}"`
|
||||
: "";
|
||||
return (
|
||||
`<span class="risk-status-badge risk-status-${safe(st)}" role="status"` +
|
||||
` title="${title}" data-status-label="${label}"${untilAttr}>${text}</span>`
|
||||
);
|
||||
}
|
||||
|
||||
function tickAll(root) {
|
||||
const scope = root || document;
|
||||
scope.querySelectorAll(".risk-status-badge[data-freeze-until-ms]").forEach(refreshElement);
|
||||
}
|
||||
|
||||
let timer = null;
|
||||
function startTicker() {
|
||||
if (timer) return;
|
||||
tickAll();
|
||||
timer = setInterval(() => tickAll(), 1000);
|
||||
}
|
||||
|
||||
global.AccountRiskBadge = {
|
||||
formatRemaining,
|
||||
badgeText,
|
||||
refreshElement,
|
||||
applyToElement,
|
||||
formatBadgeHtml,
|
||||
tickAll,
|
||||
startTicker,
|
||||
};
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
|
||||
@@ -1,269 +1,269 @@
|
||||
/**
|
||||
* 四所实例共用 UI:复盘详情、盈亏着色等。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s == null ? "" : s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function pnlClassFromValue(val) {
|
||||
const n = Number(String(val == null ? "" : val).replace(/[^\d.-]/g, ""));
|
||||
if (!Number.isFinite(n) || n === 0) return "";
|
||||
return n > 0 ? "pnl-profit" : "pnl-loss";
|
||||
}
|
||||
|
||||
function formatPnlSpan(val, suffix) {
|
||||
const sfx = suffix == null ? "U" : suffix;
|
||||
const cls = pnlClassFromValue(val);
|
||||
const text = escapeHtml(val == null || val === "" ? "-" : val) + sfx;
|
||||
return cls ? `<span class="${cls}">${text}</span>` : text;
|
||||
}
|
||||
|
||||
function buildJournalDetailHtml(o, formatExitLine) {
|
||||
const moodTags =
|
||||
Array.isArray(o.mood_issues) && o.mood_issues.length
|
||||
? o.mood_issues.join(",")
|
||||
: o.mood_issues || "无";
|
||||
const exitText =
|
||||
typeof formatExitLine === "function" ? formatExitLine(o) : o.exit_reason || "无";
|
||||
const lines = [
|
||||
`币种/周期:${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "-")}`,
|
||||
`开仓时间:${escapeHtml(o.open_datetime || "-")}`,
|
||||
`平仓时间:${escapeHtml(o.close_datetime || "-")}`,
|
||||
`持仓时长:${escapeHtml(o.hold_duration || "-")}`,
|
||||
`盈亏:${formatPnlSpan(o.pnl)}`,
|
||||
`开仓类型:${escapeHtml(o.entry_reason || "无")}`,
|
||||
`平仓/离场:${escapeHtml(exitText)}`,
|
||||
`预期RR:${escapeHtml(o.expect_rr || "-")}`,
|
||||
`实际RR:${escapeHtml(o.real_rr || "-")}`,
|
||||
`保本后盯盘:${escapeHtml(o.post_breakeven_stare || "-")}`,
|
||||
`占用时新开仓:${escapeHtml(o.new_trade_while_occupied || "-")}`,
|
||||
`心态标签:${escapeHtml(moodTags)}`,
|
||||
`备注:${escapeHtml(o.note || "无")}`,
|
||||
];
|
||||
return lines.join("<br>");
|
||||
}
|
||||
|
||||
function setJournalDetailBody(o, formatExitLine) {
|
||||
const body = document.getElementById("detailBody");
|
||||
if (!body) return;
|
||||
body.classList.remove("md-review", "trade-record-detail-wrap");
|
||||
body.classList.add("journal-detail-meta");
|
||||
body.innerHTML = buildJournalDetailHtml(o, formatExitLine);
|
||||
}
|
||||
|
||||
function openJournalDetailModal(id, journalCache, formatExitLine) {
|
||||
const o = journalCache && journalCache[id];
|
||||
if (!o) return;
|
||||
const titleEl = document.getElementById("detailTitle");
|
||||
if (titleEl) {
|
||||
titleEl.innerText = `交易复盘详情|${o.coin || "-"} ${o.tf || "-"}`;
|
||||
}
|
||||
setJournalDetailBody(o, formatExitLine);
|
||||
clearDetailActions();
|
||||
const imgEl = document.getElementById("detailImage");
|
||||
if (imgEl) {
|
||||
if (o.image) {
|
||||
imgEl.src = `/static/images/${o.image}`;
|
||||
imgEl.style.display = "block";
|
||||
} else {
|
||||
imgEl.src = "";
|
||||
imgEl.style.display = "none";
|
||||
}
|
||||
}
|
||||
if (typeof setDetailModalFullscreen === "function") {
|
||||
setDetailModalFullscreen(false);
|
||||
}
|
||||
const modal = document.getElementById("detailModal");
|
||||
if (modal) modal.style.display = "flex";
|
||||
}
|
||||
|
||||
function isMobileCompactRecords() {
|
||||
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||
return window.matchMedia("(max-width: 720px)").matches;
|
||||
}
|
||||
|
||||
function inferJournalDirection(o) {
|
||||
const text = String((o && o.entry_reason) || "");
|
||||
if (/做空|空头|short/i.test(text)) {
|
||||
return { text: "做空", cls: "direction-short" };
|
||||
}
|
||||
if (/做多|多头|long/i.test(text)) {
|
||||
return { text: "做多", cls: "direction-long" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderJournalListHtml(data) {
|
||||
if (!data || !data.length) return "";
|
||||
const mobile = isMobileCompactRecords();
|
||||
return data
|
||||
.map(function (o) {
|
||||
if (mobile) {
|
||||
const dir = inferJournalDirection(o);
|
||||
const pnlCls = pnlClassFromValue(o.pnl);
|
||||
const dirHtml = dir
|
||||
? `<span class="badge ${dir.cls}">${escapeHtml(dir.text)}</span>`
|
||||
: `<span class="mrr-muted">-</span>`;
|
||||
const id = escapeHtml(o.id);
|
||||
return `<div class="mobile-record-row-wrap">
|
||||
<button type="button" class="mobile-record-row" onclick="openJournalDetail('${id}')">
|
||||
<span class="mrr-symbol">${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "")}</span>
|
||||
<span class="mrr-dir">${dirHtml}</span>
|
||||
<span class="mrr-pnl ${pnlCls}">${escapeHtml(o.pnl == null || o.pnl === "" ? "-" : o.pnl)}U</span>
|
||||
</button>
|
||||
<button type="button" class="mobile-record-del" title="删除" onclick="deleteJournal('${id}')">×</button>
|
||||
</div>`;
|
||||
}
|
||||
const moodTags = (o.mood_issues || []).join(",") || "无";
|
||||
const id = escapeHtml(o.id);
|
||||
return `<div class="entry">
|
||||
<div><strong>${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "-")}</strong> | 盈亏:${escapeHtml(o.pnl == null || o.pnl === "" ? "-" : o.pnl)}U</div>
|
||||
<div>开:${escapeHtml(o.open_datetime || "-")} 平:${escapeHtml(o.close_datetime || "-")} 持仓:${escapeHtml(o.hold_duration || "-")}</div>
|
||||
<div>心态标签:${escapeHtml(moodTags)}</div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:6px">
|
||||
<button type="button" class="btn-del" style="border:none;cursor:pointer;background:#1f3a5a;color:#8fc8ff" onclick="openJournalDetail('${id}')">查看详情</button>
|
||||
<button type="button" class="btn-del" onclick="deleteJournal('${id}')">删除</button>
|
||||
</div>
|
||||
</div>`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
function parseTradeRecordRow(tr) {
|
||||
const cells = tr.querySelectorAll("td");
|
||||
if (cells.length < 14) return null;
|
||||
const dirBadge = cells[2].querySelector(".badge");
|
||||
return {
|
||||
rowId: tr.id,
|
||||
symbol: cells[0].textContent.trim(),
|
||||
type: cells[1].textContent.trim(),
|
||||
directionHtml: (dirBadge ? dirBadge.outerHTML : cells[2].innerHTML).trim(),
|
||||
directionText: cells[2].textContent.trim(),
|
||||
trigger: cells[3].textContent.trim(),
|
||||
stopLoss: cells[4].textContent.trim(),
|
||||
takeProfit: cells[5].textContent.trim(),
|
||||
margin: cells[6].textContent.trim(),
|
||||
leverage: cells[7].textContent.trim(),
|
||||
holdMinutes: cells[8].textContent.trim(),
|
||||
openedAt: cells[9].textContent.trim(),
|
||||
closedAt: cells[10].textContent.trim(),
|
||||
pnlHtml: cells[11].innerHTML.trim(),
|
||||
pnlText: cells[11].textContent.trim(),
|
||||
resultHtml: cells[12].innerHTML.trim(),
|
||||
resultText: cells[12].textContent.trim(),
|
||||
actionsHtml: cells[13].innerHTML,
|
||||
};
|
||||
}
|
||||
|
||||
function renderMobileTradeRow(tr) {
|
||||
const row = parseTradeRecordRow(tr);
|
||||
if (!row) return "";
|
||||
const pnlCls = pnlClassFromValue(row.pnlText);
|
||||
return `<button type="button" class="mobile-record-row" data-row-id="${escapeHtml(row.rowId)}">
|
||||
<span class="mrr-symbol">${escapeHtml(row.symbol)}</span>
|
||||
<span class="mrr-dir">${row.directionHtml}</span>
|
||||
<span class="mrr-pnl ${pnlCls}">${escapeHtml(row.pnlText || "-")}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function tradeDetailRow(label, valueHtml) {
|
||||
return `<div class="trd-row"><span class="trd-label">${escapeHtml(label)}</span><span class="trd-value">${valueHtml}</span></div>`;
|
||||
}
|
||||
|
||||
function buildTradeRecordDetailHtml(row) {
|
||||
return `<div class="trade-record-detail">${
|
||||
tradeDetailRow("品种", escapeHtml(row.symbol)) +
|
||||
tradeDetailRow("类型", escapeHtml(row.type)) +
|
||||
tradeDetailRow("方向", row.directionHtml) +
|
||||
tradeDetailRow("成交价", escapeHtml(row.trigger)) +
|
||||
tradeDetailRow("止损(开仓)", escapeHtml(row.stopLoss)) +
|
||||
tradeDetailRow("止盈", escapeHtml(row.takeProfit)) +
|
||||
tradeDetailRow("基数", escapeHtml(row.margin)) +
|
||||
tradeDetailRow("杠杆", escapeHtml(row.leverage)) +
|
||||
tradeDetailRow("持仓分钟", escapeHtml(row.holdMinutes)) +
|
||||
tradeDetailRow("开仓时间", escapeHtml(row.openedAt)) +
|
||||
tradeDetailRow("平仓时间", escapeHtml(row.closedAt)) +
|
||||
tradeDetailRow("盈亏U", row.pnlHtml) +
|
||||
tradeDetailRow("结果", row.resultHtml)
|
||||
}</div>`;
|
||||
}
|
||||
|
||||
function clearDetailActions() {
|
||||
const el = document.getElementById("detailActions");
|
||||
if (el) {
|
||||
el.innerHTML = "";
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function setDetailActionsHtml(html) {
|
||||
let el = document.getElementById("detailActions");
|
||||
if (!el) {
|
||||
const panel = document.querySelector("#detailModal .panel");
|
||||
if (!panel) return;
|
||||
el = document.createElement("div");
|
||||
el.id = "detailActions";
|
||||
el.className = "detail-actions";
|
||||
const body = document.getElementById("detailBody");
|
||||
if (body && body.parentNode === panel) {
|
||||
panel.insertBefore(el, body.nextSibling);
|
||||
} else {
|
||||
panel.appendChild(el);
|
||||
}
|
||||
}
|
||||
el.innerHTML = html || "";
|
||||
el.style.display = html ? "flex" : "none";
|
||||
}
|
||||
|
||||
function openTradeRecordDetailModal(tr) {
|
||||
const row = parseTradeRecordRow(tr);
|
||||
if (!row) return;
|
||||
const titleEl = document.getElementById("detailTitle");
|
||||
if (titleEl) {
|
||||
titleEl.innerText = `交易记录|${row.symbol}`;
|
||||
}
|
||||
const body = document.getElementById("detailBody");
|
||||
if (body) {
|
||||
body.classList.remove("md-review", "journal-detail-meta");
|
||||
body.classList.add("trade-record-detail-wrap");
|
||||
body.innerHTML = buildTradeRecordDetailHtml(row);
|
||||
}
|
||||
setDetailActionsHtml(
|
||||
`<div class="detail-actions-inner">${row.actionsHtml}</div>`
|
||||
);
|
||||
const imgEl = document.getElementById("detailImage");
|
||||
if (imgEl) {
|
||||
imgEl.src = "";
|
||||
imgEl.style.display = "none";
|
||||
}
|
||||
if (typeof setDetailModalFullscreen === "function") {
|
||||
setDetailModalFullscreen(false);
|
||||
}
|
||||
const modal = document.getElementById("detailModal");
|
||||
if (modal) modal.style.display = "flex";
|
||||
}
|
||||
|
||||
global.InstanceUI = {
|
||||
escapeHtml: escapeHtml,
|
||||
pnlClassFromValue: pnlClassFromValue,
|
||||
formatPnlSpan: formatPnlSpan,
|
||||
buildJournalDetailHtml: buildJournalDetailHtml,
|
||||
setJournalDetailBody: setJournalDetailBody,
|
||||
openJournalDetailModal: openJournalDetailModal,
|
||||
isMobileCompactRecords: isMobileCompactRecords,
|
||||
inferJournalDirection: inferJournalDirection,
|
||||
renderJournalListHtml: renderJournalListHtml,
|
||||
parseTradeRecordRow: parseTradeRecordRow,
|
||||
renderMobileTradeRow: renderMobileTradeRow,
|
||||
buildTradeRecordDetailHtml: buildTradeRecordDetailHtml,
|
||||
openTradeRecordDetailModal: openTradeRecordDetailModal,
|
||||
clearDetailActions: clearDetailActions,
|
||||
};
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
/**
|
||||
* 三所实例共用 UI:复盘详情、盈亏着色等。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s == null ? "" : s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function pnlClassFromValue(val) {
|
||||
const n = Number(String(val == null ? "" : val).replace(/[^\d.-]/g, ""));
|
||||
if (!Number.isFinite(n) || n === 0) return "";
|
||||
return n > 0 ? "pnl-profit" : "pnl-loss";
|
||||
}
|
||||
|
||||
function formatPnlSpan(val, suffix) {
|
||||
const sfx = suffix == null ? "U" : suffix;
|
||||
const cls = pnlClassFromValue(val);
|
||||
const text = escapeHtml(val == null || val === "" ? "-" : val) + sfx;
|
||||
return cls ? `<span class="${cls}">${text}</span>` : text;
|
||||
}
|
||||
|
||||
function buildJournalDetailHtml(o, formatExitLine) {
|
||||
const moodTags =
|
||||
Array.isArray(o.mood_issues) && o.mood_issues.length
|
||||
? o.mood_issues.join(",")
|
||||
: o.mood_issues || "无";
|
||||
const exitText =
|
||||
typeof formatExitLine === "function" ? formatExitLine(o) : o.exit_reason || "无";
|
||||
const lines = [
|
||||
`币种/周期:${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "-")}`,
|
||||
`开仓时间:${escapeHtml(o.open_datetime || "-")}`,
|
||||
`平仓时间:${escapeHtml(o.close_datetime || "-")}`,
|
||||
`持仓时长:${escapeHtml(o.hold_duration || "-")}`,
|
||||
`盈亏:${formatPnlSpan(o.pnl)}`,
|
||||
`开仓类型:${escapeHtml(o.entry_reason || "无")}`,
|
||||
`平仓/离场:${escapeHtml(exitText)}`,
|
||||
`预期RR:${escapeHtml(o.expect_rr || "-")}`,
|
||||
`实际RR:${escapeHtml(o.real_rr || "-")}`,
|
||||
`保本后盯盘:${escapeHtml(o.post_breakeven_stare || "-")}`,
|
||||
`占用时新开仓:${escapeHtml(o.new_trade_while_occupied || "-")}`,
|
||||
`心态标签:${escapeHtml(moodTags)}`,
|
||||
`备注:${escapeHtml(o.note || "无")}`,
|
||||
];
|
||||
return lines.join("<br>");
|
||||
}
|
||||
|
||||
function setJournalDetailBody(o, formatExitLine) {
|
||||
const body = document.getElementById("detailBody");
|
||||
if (!body) return;
|
||||
body.classList.remove("md-review", "trade-record-detail-wrap");
|
||||
body.classList.add("journal-detail-meta");
|
||||
body.innerHTML = buildJournalDetailHtml(o, formatExitLine);
|
||||
}
|
||||
|
||||
function openJournalDetailModal(id, journalCache, formatExitLine) {
|
||||
const o = journalCache && journalCache[id];
|
||||
if (!o) return;
|
||||
const titleEl = document.getElementById("detailTitle");
|
||||
if (titleEl) {
|
||||
titleEl.innerText = `交易复盘详情|${o.coin || "-"} ${o.tf || "-"}`;
|
||||
}
|
||||
setJournalDetailBody(o, formatExitLine);
|
||||
clearDetailActions();
|
||||
const imgEl = document.getElementById("detailImage");
|
||||
if (imgEl) {
|
||||
if (o.image) {
|
||||
imgEl.src = `/static/images/${o.image}`;
|
||||
imgEl.style.display = "block";
|
||||
} else {
|
||||
imgEl.src = "";
|
||||
imgEl.style.display = "none";
|
||||
}
|
||||
}
|
||||
if (typeof setDetailModalFullscreen === "function") {
|
||||
setDetailModalFullscreen(false);
|
||||
}
|
||||
const modal = document.getElementById("detailModal");
|
||||
if (modal) modal.style.display = "flex";
|
||||
}
|
||||
|
||||
function isMobileCompactRecords() {
|
||||
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||
return window.matchMedia("(max-width: 720px)").matches;
|
||||
}
|
||||
|
||||
function inferJournalDirection(o) {
|
||||
const text = String((o && o.entry_reason) || "");
|
||||
if (/做空|空头|short/i.test(text)) {
|
||||
return { text: "做空", cls: "direction-short" };
|
||||
}
|
||||
if (/做多|多头|long/i.test(text)) {
|
||||
return { text: "做多", cls: "direction-long" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderJournalListHtml(data) {
|
||||
if (!data || !data.length) return "";
|
||||
const mobile = isMobileCompactRecords();
|
||||
return data
|
||||
.map(function (o) {
|
||||
if (mobile) {
|
||||
const dir = inferJournalDirection(o);
|
||||
const pnlCls = pnlClassFromValue(o.pnl);
|
||||
const dirHtml = dir
|
||||
? `<span class="badge ${dir.cls}">${escapeHtml(dir.text)}</span>`
|
||||
: `<span class="mrr-muted">-</span>`;
|
||||
const id = escapeHtml(o.id);
|
||||
return `<div class="mobile-record-row-wrap">
|
||||
<button type="button" class="mobile-record-row" onclick="openJournalDetail('${id}')">
|
||||
<span class="mrr-symbol">${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "")}</span>
|
||||
<span class="mrr-dir">${dirHtml}</span>
|
||||
<span class="mrr-pnl ${pnlCls}">${escapeHtml(o.pnl == null || o.pnl === "" ? "-" : o.pnl)}U</span>
|
||||
</button>
|
||||
<button type="button" class="mobile-record-del" title="删除" onclick="deleteJournal('${id}')">×</button>
|
||||
</div>`;
|
||||
}
|
||||
const moodTags = (o.mood_issues || []).join(",") || "无";
|
||||
const id = escapeHtml(o.id);
|
||||
return `<div class="entry">
|
||||
<div><strong>${escapeHtml(o.coin || "-")} ${escapeHtml(o.tf || "-")}</strong> | 盈亏:${escapeHtml(o.pnl == null || o.pnl === "" ? "-" : o.pnl)}U</div>
|
||||
<div>开:${escapeHtml(o.open_datetime || "-")} 平:${escapeHtml(o.close_datetime || "-")} 持仓:${escapeHtml(o.hold_duration || "-")}</div>
|
||||
<div>心态标签:${escapeHtml(moodTags)}</div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:6px">
|
||||
<button type="button" class="btn-del" style="border:none;cursor:pointer;background:#1f3a5a;color:#8fc8ff" onclick="openJournalDetail('${id}')">查看详情</button>
|
||||
<button type="button" class="btn-del" onclick="deleteJournal('${id}')">删除</button>
|
||||
</div>
|
||||
</div>`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
function parseTradeRecordRow(tr) {
|
||||
const cells = tr.querySelectorAll("td");
|
||||
if (cells.length < 14) return null;
|
||||
const dirBadge = cells[2].querySelector(".badge");
|
||||
return {
|
||||
rowId: tr.id,
|
||||
symbol: cells[0].textContent.trim(),
|
||||
type: cells[1].textContent.trim(),
|
||||
directionHtml: (dirBadge ? dirBadge.outerHTML : cells[2].innerHTML).trim(),
|
||||
directionText: cells[2].textContent.trim(),
|
||||
trigger: cells[3].textContent.trim(),
|
||||
stopLoss: cells[4].textContent.trim(),
|
||||
takeProfit: cells[5].textContent.trim(),
|
||||
margin: cells[6].textContent.trim(),
|
||||
leverage: cells[7].textContent.trim(),
|
||||
holdMinutes: cells[8].textContent.trim(),
|
||||
openedAt: cells[9].textContent.trim(),
|
||||
closedAt: cells[10].textContent.trim(),
|
||||
pnlHtml: cells[11].innerHTML.trim(),
|
||||
pnlText: cells[11].textContent.trim(),
|
||||
resultHtml: cells[12].innerHTML.trim(),
|
||||
resultText: cells[12].textContent.trim(),
|
||||
actionsHtml: cells[13].innerHTML,
|
||||
};
|
||||
}
|
||||
|
||||
function renderMobileTradeRow(tr) {
|
||||
const row = parseTradeRecordRow(tr);
|
||||
if (!row) return "";
|
||||
const pnlCls = pnlClassFromValue(row.pnlText);
|
||||
return `<button type="button" class="mobile-record-row" data-row-id="${escapeHtml(row.rowId)}">
|
||||
<span class="mrr-symbol">${escapeHtml(row.symbol)}</span>
|
||||
<span class="mrr-dir">${row.directionHtml}</span>
|
||||
<span class="mrr-pnl ${pnlCls}">${escapeHtml(row.pnlText || "-")}</span>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function tradeDetailRow(label, valueHtml) {
|
||||
return `<div class="trd-row"><span class="trd-label">${escapeHtml(label)}</span><span class="trd-value">${valueHtml}</span></div>`;
|
||||
}
|
||||
|
||||
function buildTradeRecordDetailHtml(row) {
|
||||
return `<div class="trade-record-detail">${
|
||||
tradeDetailRow("品种", escapeHtml(row.symbol)) +
|
||||
tradeDetailRow("类型", escapeHtml(row.type)) +
|
||||
tradeDetailRow("方向", row.directionHtml) +
|
||||
tradeDetailRow("成交价", escapeHtml(row.trigger)) +
|
||||
tradeDetailRow("止损(开仓)", escapeHtml(row.stopLoss)) +
|
||||
tradeDetailRow("止盈", escapeHtml(row.takeProfit)) +
|
||||
tradeDetailRow("基数", escapeHtml(row.margin)) +
|
||||
tradeDetailRow("杠杆", escapeHtml(row.leverage)) +
|
||||
tradeDetailRow("持仓分钟", escapeHtml(row.holdMinutes)) +
|
||||
tradeDetailRow("开仓时间", escapeHtml(row.openedAt)) +
|
||||
tradeDetailRow("平仓时间", escapeHtml(row.closedAt)) +
|
||||
tradeDetailRow("盈亏U", row.pnlHtml) +
|
||||
tradeDetailRow("结果", row.resultHtml)
|
||||
}</div>`;
|
||||
}
|
||||
|
||||
function clearDetailActions() {
|
||||
const el = document.getElementById("detailActions");
|
||||
if (el) {
|
||||
el.innerHTML = "";
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function setDetailActionsHtml(html) {
|
||||
let el = document.getElementById("detailActions");
|
||||
if (!el) {
|
||||
const panel = document.querySelector("#detailModal .panel");
|
||||
if (!panel) return;
|
||||
el = document.createElement("div");
|
||||
el.id = "detailActions";
|
||||
el.className = "detail-actions";
|
||||
const body = document.getElementById("detailBody");
|
||||
if (body && body.parentNode === panel) {
|
||||
panel.insertBefore(el, body.nextSibling);
|
||||
} else {
|
||||
panel.appendChild(el);
|
||||
}
|
||||
}
|
||||
el.innerHTML = html || "";
|
||||
el.style.display = html ? "flex" : "none";
|
||||
}
|
||||
|
||||
function openTradeRecordDetailModal(tr) {
|
||||
const row = parseTradeRecordRow(tr);
|
||||
if (!row) return;
|
||||
const titleEl = document.getElementById("detailTitle");
|
||||
if (titleEl) {
|
||||
titleEl.innerText = `交易记录|${row.symbol}`;
|
||||
}
|
||||
const body = document.getElementById("detailBody");
|
||||
if (body) {
|
||||
body.classList.remove("md-review", "journal-detail-meta");
|
||||
body.classList.add("trade-record-detail-wrap");
|
||||
body.innerHTML = buildTradeRecordDetailHtml(row);
|
||||
}
|
||||
setDetailActionsHtml(
|
||||
`<div class="detail-actions-inner">${row.actionsHtml}</div>`
|
||||
);
|
||||
const imgEl = document.getElementById("detailImage");
|
||||
if (imgEl) {
|
||||
imgEl.src = "";
|
||||
imgEl.style.display = "none";
|
||||
}
|
||||
if (typeof setDetailModalFullscreen === "function") {
|
||||
setDetailModalFullscreen(false);
|
||||
}
|
||||
const modal = document.getElementById("detailModal");
|
||||
if (modal) modal.style.display = "flex";
|
||||
}
|
||||
|
||||
global.InstanceUI = {
|
||||
escapeHtml: escapeHtml,
|
||||
pnlClassFromValue: pnlClassFromValue,
|
||||
formatPnlSpan: formatPnlSpan,
|
||||
buildJournalDetailHtml: buildJournalDetailHtml,
|
||||
setJournalDetailBody: setJournalDetailBody,
|
||||
openJournalDetailModal: openJournalDetailModal,
|
||||
isMobileCompactRecords: isMobileCompactRecords,
|
||||
inferJournalDirection: inferJournalDirection,
|
||||
renderJournalListHtml: renderJournalListHtml,
|
||||
parseTradeRecordRow: parseTradeRecordRow,
|
||||
renderMobileTradeRow: renderMobileTradeRow,
|
||||
buildTradeRecordDetailHtml: buildTradeRecordDetailHtml,
|
||||
openTradeRecordDetailModal: openTradeRecordDetailModal,
|
||||
clearDetailActions: clearDetailActions,
|
||||
};
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
|
||||
@@ -1,160 +1,160 @@
|
||||
/**
|
||||
* 关键位监控添加表单:类型切换显隐、成交量排名校验(四所实例共用)。
|
||||
*/
|
||||
(function (global) {
|
||||
const RS_TYPES = new Set([
|
||||
"关键支撑阻力",
|
||||
"关键阻力位",
|
||||
"关键支撑位",
|
||||
]);
|
||||
|
||||
function syncKeyMonitorFormFields() {
|
||||
const typeEl = document.querySelector('#key-form [name="type"]');
|
||||
const dirEl = document.getElementById("key-direction");
|
||||
const modeEl = document.getElementById("key-sl-tp-mode");
|
||||
const manualTp = document.getElementById("key-manual-tp");
|
||||
const beWrap = document.getElementById("key-breakeven-wrap");
|
||||
if (!typeEl) return;
|
||||
const t = (typeEl.value || "").trim();
|
||||
const autoTypes = new Set(["箱体突破", "收敛突破"]);
|
||||
const fibTypes = new Set(["斐波回调0.618", "斐波回调0.786"]);
|
||||
const fbTypes = new Set(["假突破"]);
|
||||
const teTypes = new Set(["回调触价开仓", "突破触价开仓", "触价开仓"]);
|
||||
const showAuto = autoTypes.has(t);
|
||||
const showFb = fbTypes.has(t);
|
||||
const showTe = teTypes.has(t);
|
||||
const showBe = showAuto || fibTypes.has(t) || showFb || showTe;
|
||||
const showDir = !RS_TYPES.has(t);
|
||||
const upperEl = document.getElementById("key-upper");
|
||||
const lowerEl = document.getElementById("key-lower");
|
||||
const fbPriceEl = document.getElementById("key-fb-price");
|
||||
const teEntryEl = document.getElementById("key-trigger-entry");
|
||||
const teSlEl = document.getElementById("key-trigger-sl");
|
||||
const teTpEl = document.getElementById("key-trigger-tp");
|
||||
if (dirEl) {
|
||||
dirEl.style.display = showDir ? "" : "none";
|
||||
dirEl.required = showDir;
|
||||
if (!showDir) dirEl.value = "";
|
||||
}
|
||||
if (modeEl) modeEl.style.display = showAuto ? "" : "none";
|
||||
if (manualTp) {
|
||||
const trend = showAuto && modeEl && modeEl.value === "trend_manual";
|
||||
manualTp.style.display = trend ? "" : "none";
|
||||
manualTp.required = !!trend;
|
||||
}
|
||||
if (beWrap) beWrap.style.display = showBe ? "inline-flex" : "none";
|
||||
if (global.TimeCloseUI) global.TimeCloseUI.syncKeyTimeCloseVisibility(showBe);
|
||||
const hideBounds = showFb || showTe;
|
||||
if (upperEl) {
|
||||
upperEl.style.display = hideBounds ? "none" : "";
|
||||
upperEl.required = !hideBounds;
|
||||
if (hideBounds) upperEl.value = "";
|
||||
}
|
||||
if (lowerEl) {
|
||||
lowerEl.style.display = hideBounds ? "none" : "";
|
||||
lowerEl.required = !hideBounds;
|
||||
if (hideBounds) lowerEl.value = "";
|
||||
}
|
||||
if (fbPriceEl) {
|
||||
fbPriceEl.style.display = showFb ? "" : "none";
|
||||
fbPriceEl.required = showFb;
|
||||
if (!showFb) fbPriceEl.value = "";
|
||||
fbPriceEl.placeholder =
|
||||
dirEl && dirEl.value === "short"
|
||||
? "高点(阻力)"
|
||||
: dirEl && dirEl.value === "long"
|
||||
? "低点(支撑)"
|
||||
: "做空填高点/做多填低点";
|
||||
}
|
||||
[teEntryEl, teSlEl, teTpEl].forEach((el) => {
|
||||
if (!el) return;
|
||||
el.style.display = showTe ? "" : "none";
|
||||
el.required = showTe;
|
||||
if (!showTe) el.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
function submitKeyForm(keyForm, label) {
|
||||
if (
|
||||
document.body &&
|
||||
document.body.getAttribute("data-embed-shell") === "1" &&
|
||||
global.InstanceEmbed &&
|
||||
typeof global.InstanceEmbed.postFormAndReload === "function"
|
||||
) {
|
||||
global.InstanceEmbed.postFormAndReload(keyForm, label || "提交中…");
|
||||
return;
|
||||
}
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.nativeSubmitOnce(keyForm, label || "提交中…");
|
||||
else keyForm.submit();
|
||||
}
|
||||
|
||||
function bindKeyMonitorForm() {
|
||||
const keyForm = document.getElementById("key-form");
|
||||
const keyTypeSel = document.querySelector('#key-form [name="type"]');
|
||||
const keyModeSel = document.getElementById("key-sl-tp-mode");
|
||||
const keyDirSel = document.getElementById("key-direction");
|
||||
if (keyTypeSel) keyTypeSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
if (keyModeSel) keyModeSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
if (keyDirSel) keyDirSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
syncKeyMonitorFormFields();
|
||||
if (global.TimeCloseUI) {
|
||||
global.TimeCloseUI.bindTimeCloseForm(
|
||||
"key-time-close-cb",
|
||||
"key-time-close-hours",
|
||||
"key-time-close-wrap"
|
||||
);
|
||||
}
|
||||
if (!keyForm || keyForm.dataset.keyFormBound === "1") return;
|
||||
keyForm.dataset.keyFormBound = "1";
|
||||
keyForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
if (global.FormSubmitGuard && global.FormSubmitGuard.isLocked(keyForm)) return;
|
||||
const symbolEl = keyForm.querySelector('[name="symbol"]');
|
||||
const symbol = (symbolEl ? symbolEl.value : "").trim();
|
||||
if (!symbol) {
|
||||
alert("请先输入交易对");
|
||||
return;
|
||||
}
|
||||
const typeVal = (keyForm.querySelector('[name="type"]') || {}).value || "";
|
||||
if (typeVal === "假突破") {
|
||||
submitKeyForm(keyForm, "提交中…");
|
||||
return;
|
||||
}
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.lock(keyForm, "校验排名中…");
|
||||
fetch(`/api/symbol_liquidity_rank?symbol=${encodeURIComponent(symbol)}`)
|
||||
.then((r) => r.json().then((d) => ({ status: r.status, data: d })))
|
||||
.then(({ status, data }) => {
|
||||
if (status >= 400 || !data.ok) {
|
||||
alert((data && data.msg) || "日成交量排名读取失败");
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
return;
|
||||
}
|
||||
const rankMax = data.rank_max || 30;
|
||||
const inTop = data.in_top != null ? data.in_top : data.in_top30;
|
||||
if (data.rank == null || !inTop) {
|
||||
alert(
|
||||
`${data.symbol} 当前日成交量排名 ${data.rank == null ? "—" : data.rank}/${data.total},不在前${rankMax},已拦截。`
|
||||
);
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
return;
|
||||
}
|
||||
submitKeyForm(keyForm, "提交中…");
|
||||
})
|
||||
.catch(() => {
|
||||
alert("日成交量排名检查失败,请稍后重试");
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
global.KeyMonitorForm = {
|
||||
syncFields: syncKeyMonitorFormFields,
|
||||
init: bindKeyMonitorForm,
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", bindKeyMonitorForm);
|
||||
} else {
|
||||
bindKeyMonitorForm();
|
||||
}
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
/**
|
||||
* 关键位监控添加表单:类型切换显隐、成交量排名校验(三所实例共用)。
|
||||
*/
|
||||
(function (global) {
|
||||
const RS_TYPES = new Set([
|
||||
"关键支撑阻力",
|
||||
"关键阻力位",
|
||||
"关键支撑位",
|
||||
]);
|
||||
|
||||
function syncKeyMonitorFormFields() {
|
||||
const typeEl = document.querySelector('#key-form [name="type"]');
|
||||
const dirEl = document.getElementById("key-direction");
|
||||
const modeEl = document.getElementById("key-sl-tp-mode");
|
||||
const manualTp = document.getElementById("key-manual-tp");
|
||||
const beWrap = document.getElementById("key-breakeven-wrap");
|
||||
if (!typeEl) return;
|
||||
const t = (typeEl.value || "").trim();
|
||||
const autoTypes = new Set(["箱体突破", "收敛突破"]);
|
||||
const fibTypes = new Set(["斐波回调0.618", "斐波回调0.786"]);
|
||||
const fbTypes = new Set(["假突破"]);
|
||||
const teTypes = new Set(["回调触价开仓", "突破触价开仓", "触价开仓"]);
|
||||
const showAuto = autoTypes.has(t);
|
||||
const showFb = fbTypes.has(t);
|
||||
const showTe = teTypes.has(t);
|
||||
const showBe = showAuto || fibTypes.has(t) || showFb || showTe;
|
||||
const showDir = !RS_TYPES.has(t);
|
||||
const upperEl = document.getElementById("key-upper");
|
||||
const lowerEl = document.getElementById("key-lower");
|
||||
const fbPriceEl = document.getElementById("key-fb-price");
|
||||
const teEntryEl = document.getElementById("key-trigger-entry");
|
||||
const teSlEl = document.getElementById("key-trigger-sl");
|
||||
const teTpEl = document.getElementById("key-trigger-tp");
|
||||
if (dirEl) {
|
||||
dirEl.style.display = showDir ? "" : "none";
|
||||
dirEl.required = showDir;
|
||||
if (!showDir) dirEl.value = "";
|
||||
}
|
||||
if (modeEl) modeEl.style.display = showAuto ? "" : "none";
|
||||
if (manualTp) {
|
||||
const trend = showAuto && modeEl && modeEl.value === "trend_manual";
|
||||
manualTp.style.display = trend ? "" : "none";
|
||||
manualTp.required = !!trend;
|
||||
}
|
||||
if (beWrap) beWrap.style.display = showBe ? "inline-flex" : "none";
|
||||
if (global.TimeCloseUI) global.TimeCloseUI.syncKeyTimeCloseVisibility(showBe);
|
||||
const hideBounds = showFb || showTe;
|
||||
if (upperEl) {
|
||||
upperEl.style.display = hideBounds ? "none" : "";
|
||||
upperEl.required = !hideBounds;
|
||||
if (hideBounds) upperEl.value = "";
|
||||
}
|
||||
if (lowerEl) {
|
||||
lowerEl.style.display = hideBounds ? "none" : "";
|
||||
lowerEl.required = !hideBounds;
|
||||
if (hideBounds) lowerEl.value = "";
|
||||
}
|
||||
if (fbPriceEl) {
|
||||
fbPriceEl.style.display = showFb ? "" : "none";
|
||||
fbPriceEl.required = showFb;
|
||||
if (!showFb) fbPriceEl.value = "";
|
||||
fbPriceEl.placeholder =
|
||||
dirEl && dirEl.value === "short"
|
||||
? "高点(阻力)"
|
||||
: dirEl && dirEl.value === "long"
|
||||
? "低点(支撑)"
|
||||
: "做空填高点/做多填低点";
|
||||
}
|
||||
[teEntryEl, teSlEl, teTpEl].forEach((el) => {
|
||||
if (!el) return;
|
||||
el.style.display = showTe ? "" : "none";
|
||||
el.required = showTe;
|
||||
if (!showTe) el.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
function submitKeyForm(keyForm, label) {
|
||||
if (
|
||||
document.body &&
|
||||
document.body.getAttribute("data-embed-shell") === "1" &&
|
||||
global.InstanceEmbed &&
|
||||
typeof global.InstanceEmbed.postFormAndReload === "function"
|
||||
) {
|
||||
global.InstanceEmbed.postFormAndReload(keyForm, label || "提交中…");
|
||||
return;
|
||||
}
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.nativeSubmitOnce(keyForm, label || "提交中…");
|
||||
else keyForm.submit();
|
||||
}
|
||||
|
||||
function bindKeyMonitorForm() {
|
||||
const keyForm = document.getElementById("key-form");
|
||||
const keyTypeSel = document.querySelector('#key-form [name="type"]');
|
||||
const keyModeSel = document.getElementById("key-sl-tp-mode");
|
||||
const keyDirSel = document.getElementById("key-direction");
|
||||
if (keyTypeSel) keyTypeSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
if (keyModeSel) keyModeSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
if (keyDirSel) keyDirSel.addEventListener("change", syncKeyMonitorFormFields);
|
||||
syncKeyMonitorFormFields();
|
||||
if (global.TimeCloseUI) {
|
||||
global.TimeCloseUI.bindTimeCloseForm(
|
||||
"key-time-close-cb",
|
||||
"key-time-close-hours",
|
||||
"key-time-close-wrap"
|
||||
);
|
||||
}
|
||||
if (!keyForm || keyForm.dataset.keyFormBound === "1") return;
|
||||
keyForm.dataset.keyFormBound = "1";
|
||||
keyForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
if (global.FormSubmitGuard && global.FormSubmitGuard.isLocked(keyForm)) return;
|
||||
const symbolEl = keyForm.querySelector('[name="symbol"]');
|
||||
const symbol = (symbolEl ? symbolEl.value : "").trim();
|
||||
if (!symbol) {
|
||||
alert("请先输入交易对");
|
||||
return;
|
||||
}
|
||||
const typeVal = (keyForm.querySelector('[name="type"]') || {}).value || "";
|
||||
if (typeVal === "假突破") {
|
||||
submitKeyForm(keyForm, "提交中…");
|
||||
return;
|
||||
}
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.lock(keyForm, "校验排名中…");
|
||||
fetch(`/api/symbol_liquidity_rank?symbol=${encodeURIComponent(symbol)}`)
|
||||
.then((r) => r.json().then((d) => ({ status: r.status, data: d })))
|
||||
.then(({ status, data }) => {
|
||||
if (status >= 400 || !data.ok) {
|
||||
alert((data && data.msg) || "日成交量排名读取失败");
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
return;
|
||||
}
|
||||
const rankMax = data.rank_max || 30;
|
||||
const inTop = data.in_top != null ? data.in_top : data.in_top30;
|
||||
if (data.rank == null || !inTop) {
|
||||
alert(
|
||||
`${data.symbol} 当前日成交量排名 ${data.rank == null ? "—" : data.rank}/${data.total},不在前${rankMax},已拦截。`
|
||||
);
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
return;
|
||||
}
|
||||
submitKeyForm(keyForm, "提交中…");
|
||||
})
|
||||
.catch(() => {
|
||||
alert("日成交量排名检查失败,请稍后重试");
|
||||
if (global.FormSubmitGuard) global.FormSubmitGuard.unlock(keyForm);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
global.KeyMonitorForm = {
|
||||
syncFields: syncKeyMonitorFormFields,
|
||||
init: bindKeyMonitorForm,
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", bindKeyMonitorForm);
|
||||
} else {
|
||||
bindKeyMonitorForm();
|
||||
}
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
|
||||
@@ -1,160 +1,160 @@
|
||||
/* 交易日历:内照明心 + 四所统计分析共用,随 data-theme 浅/深切换 */
|
||||
.trade-cal-wrap {
|
||||
--trade-cal-wrap-bg: var(--inset-surface, rgba(0, 0, 0, 0.22));
|
||||
--trade-cal-cell-bg: var(--section-surface, var(--inset-surface, rgba(0, 0, 0, 0.32)));
|
||||
--trade-cal-cell-hover-bg: color-mix(in srgb, var(--accent, #6366f1) 12%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-cell-hover-border: color-mix(in srgb, var(--accent, #6366f1) 45%, transparent);
|
||||
--trade-cal-selected-border: rgba(59, 130, 246, 0.85);
|
||||
--trade-cal-selected-bg: color-mix(in srgb, #3b82f6 16%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-selected-shadow: rgba(59, 130, 246, 0.45);
|
||||
--trade-cal-sick-bg: color-mix(in srgb, var(--red, #ef4444) 14%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-sick-border: color-mix(in srgb, var(--red, #ef4444) 55%, transparent);
|
||||
--trade-cal-sick-shadow: color-mix(in srgb, var(--red, #ef4444) 45%, transparent);
|
||||
--trade-cal-sick-tag-bg: color-mix(in srgb, var(--red, #ef4444) 25%, transparent);
|
||||
--trade-cal-sick-tag-fg: color-mix(in srgb, var(--red, #ef4444) 70%, #fff);
|
||||
--trade-cal-pos: var(--green, #22c55e);
|
||||
--trade-cal-neg: var(--red, #ef4444);
|
||||
margin-top: 4px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border-soft, rgba(120, 140, 200, 0.28));
|
||||
background: var(--trade-cal-wrap-bg);
|
||||
}
|
||||
.stats-calendar-wrap {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell {
|
||||
background: var(--trade-cal-cell-bg) !important;
|
||||
background-image: none !important;
|
||||
border: 1px solid transparent;
|
||||
padding: 4px 3px;
|
||||
min-height: 68px;
|
||||
width: 100%;
|
||||
box-shadow: none;
|
||||
line-height: 1.15;
|
||||
font-size: inherit;
|
||||
text-align: center;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell:disabled {
|
||||
opacity: 1;
|
||||
cursor: default;
|
||||
}
|
||||
.trade-cal-wrap .trade-cal-head .btn,
|
||||
.trade-cal-wrap .trade-cal-head button {
|
||||
min-height: 0;
|
||||
min-width: 34px;
|
||||
padding: 4px 12px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.trade-cal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.trade-cal-title {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
min-width: 120px;
|
||||
text-align: center;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-weekdays {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.trade-cal-wd {
|
||||
text-align: center;
|
||||
font-size: 0.72rem;
|
||||
color: var(--muted, #8892b0);
|
||||
}
|
||||
.trade-cal-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 4px;
|
||||
}
|
||||
.trade-cal-cell {
|
||||
min-height: 62px;
|
||||
padding: 4px 3px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
background: var(--trade-cal-cell-bg);
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: default;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 2px;
|
||||
}
|
||||
.trade-cal-cell.has-trade {
|
||||
cursor: pointer;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell.has-trade:hover {
|
||||
background: var(--trade-cal-cell-hover-bg) !important;
|
||||
background-image: none !important;
|
||||
border-color: var(--trade-cal-cell-hover-border);
|
||||
}
|
||||
.trade-cal-cell.is-selected {
|
||||
border-color: var(--trade-cal-selected-border);
|
||||
background: var(--trade-cal-selected-bg);
|
||||
box-shadow: 0 0 0 2px var(--trade-cal-selected-shadow);
|
||||
}
|
||||
.trade-cal-cell.is-sick-day {
|
||||
border-color: var(--trade-cal-sick-border);
|
||||
background: var(--trade-cal-sick-bg);
|
||||
}
|
||||
.trade-cal-cell.is-sick-day.is-selected {
|
||||
border-color: var(--trade-cal-selected-border);
|
||||
background: color-mix(in srgb, #3b82f6 14%, var(--trade-cal-sick-bg));
|
||||
box-shadow: 0 0 0 2px var(--trade-cal-selected-shadow);
|
||||
}
|
||||
.trade-cal-day-num {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-pnl {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-cell.pnl-pos .trade-cal-pnl {
|
||||
color: var(--trade-cal-pos);
|
||||
}
|
||||
.trade-cal-cell.pnl-neg .trade-cal-pnl {
|
||||
color: var(--trade-cal-neg);
|
||||
}
|
||||
.trade-cal-cnt {
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted, #8892b0);
|
||||
font-weight: 500;
|
||||
}
|
||||
.trade-cal-sick-tag {
|
||||
font-size: 0.62rem;
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--trade-cal-sick-tag-bg);
|
||||
color: var(--trade-cal-sick-tag-fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
.trade-cal-pad {
|
||||
background: transparent;
|
||||
border: none;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
html[data-theme="light"] .trade-cal-wrap {
|
||||
--trade-cal-wrap-bg: var(--inset-surface, #eef3f8);
|
||||
--trade-cal-cell-bg: var(--section-surface, #f6f9fc);
|
||||
--trade-cal-cell-hover-bg: color-mix(in srgb, var(--accent, #2563eb) 10%, #f6f9fc);
|
||||
--trade-cal-selected-border: rgba(37, 99, 235, 0.75);
|
||||
--trade-cal-selected-bg: color-mix(in srgb, #2563eb 12%, #f6f9fc);
|
||||
--trade-cal-selected-shadow: rgba(37, 99, 235, 0.35);
|
||||
--trade-cal-sick-tag-fg: #b91c1c;
|
||||
}
|
||||
/* 交易日历:内照明心 + 三所统计分析共用,随 data-theme 浅/深切换 */
|
||||
.trade-cal-wrap {
|
||||
--trade-cal-wrap-bg: var(--inset-surface, rgba(0, 0, 0, 0.22));
|
||||
--trade-cal-cell-bg: var(--section-surface, var(--inset-surface, rgba(0, 0, 0, 0.32)));
|
||||
--trade-cal-cell-hover-bg: color-mix(in srgb, var(--accent, #6366f1) 12%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-cell-hover-border: color-mix(in srgb, var(--accent, #6366f1) 45%, transparent);
|
||||
--trade-cal-selected-border: rgba(59, 130, 246, 0.85);
|
||||
--trade-cal-selected-bg: color-mix(in srgb, #3b82f6 16%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-selected-shadow: rgba(59, 130, 246, 0.45);
|
||||
--trade-cal-sick-bg: color-mix(in srgb, var(--red, #ef4444) 14%, var(--trade-cal-cell-bg));
|
||||
--trade-cal-sick-border: color-mix(in srgb, var(--red, #ef4444) 55%, transparent);
|
||||
--trade-cal-sick-shadow: color-mix(in srgb, var(--red, #ef4444) 45%, transparent);
|
||||
--trade-cal-sick-tag-bg: color-mix(in srgb, var(--red, #ef4444) 25%, transparent);
|
||||
--trade-cal-sick-tag-fg: color-mix(in srgb, var(--red, #ef4444) 70%, #fff);
|
||||
--trade-cal-pos: var(--green, #22c55e);
|
||||
--trade-cal-neg: var(--red, #ef4444);
|
||||
margin-top: 4px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border-soft, rgba(120, 140, 200, 0.28));
|
||||
background: var(--trade-cal-wrap-bg);
|
||||
}
|
||||
.stats-calendar-wrap {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell {
|
||||
background: var(--trade-cal-cell-bg) !important;
|
||||
background-image: none !important;
|
||||
border: 1px solid transparent;
|
||||
padding: 4px 3px;
|
||||
min-height: 68px;
|
||||
width: 100%;
|
||||
box-shadow: none;
|
||||
line-height: 1.15;
|
||||
font-size: inherit;
|
||||
text-align: center;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell:disabled {
|
||||
opacity: 1;
|
||||
cursor: default;
|
||||
}
|
||||
.trade-cal-wrap .trade-cal-head .btn,
|
||||
.trade-cal-wrap .trade-cal-head button {
|
||||
min-height: 0;
|
||||
min-width: 34px;
|
||||
padding: 4px 12px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.trade-cal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.trade-cal-title {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
min-width: 120px;
|
||||
text-align: center;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-weekdays {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.trade-cal-wd {
|
||||
text-align: center;
|
||||
font-size: 0.72rem;
|
||||
color: var(--muted, #8892b0);
|
||||
}
|
||||
.trade-cal-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 4px;
|
||||
}
|
||||
.trade-cal-cell {
|
||||
min-height: 62px;
|
||||
padding: 4px 3px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
background: var(--trade-cal-cell-bg);
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: default;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 2px;
|
||||
}
|
||||
.trade-cal-cell.has-trade {
|
||||
cursor: pointer;
|
||||
}
|
||||
.trade-cal-wrap button.trade-cal-cell.has-trade:hover {
|
||||
background: var(--trade-cal-cell-hover-bg) !important;
|
||||
background-image: none !important;
|
||||
border-color: var(--trade-cal-cell-hover-border);
|
||||
}
|
||||
.trade-cal-cell.is-selected {
|
||||
border-color: var(--trade-cal-selected-border);
|
||||
background: var(--trade-cal-selected-bg);
|
||||
box-shadow: 0 0 0 2px var(--trade-cal-selected-shadow);
|
||||
}
|
||||
.trade-cal-cell.is-sick-day {
|
||||
border-color: var(--trade-cal-sick-border);
|
||||
background: var(--trade-cal-sick-bg);
|
||||
}
|
||||
.trade-cal-cell.is-sick-day.is-selected {
|
||||
border-color: var(--trade-cal-selected-border);
|
||||
background: color-mix(in srgb, #3b82f6 14%, var(--trade-cal-sick-bg));
|
||||
box-shadow: 0 0 0 2px var(--trade-cal-selected-shadow);
|
||||
}
|
||||
.trade-cal-day-num {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-pnl {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
color: var(--text, #e8ecff);
|
||||
}
|
||||
.trade-cal-cell.pnl-pos .trade-cal-pnl {
|
||||
color: var(--trade-cal-pos);
|
||||
}
|
||||
.trade-cal-cell.pnl-neg .trade-cal-pnl {
|
||||
color: var(--trade-cal-neg);
|
||||
}
|
||||
.trade-cal-cnt {
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted, #8892b0);
|
||||
font-weight: 500;
|
||||
}
|
||||
.trade-cal-sick-tag {
|
||||
font-size: 0.62rem;
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--trade-cal-sick-tag-bg);
|
||||
color: var(--trade-cal-sick-tag-fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
.trade-cal-pad {
|
||||
background: transparent;
|
||||
border: none;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
html[data-theme="light"] .trade-cal-wrap {
|
||||
--trade-cal-wrap-bg: var(--inset-surface, #eef3f8);
|
||||
--trade-cal-cell-bg: var(--section-surface, #f6f9fc);
|
||||
--trade-cal-cell-hover-bg: color-mix(in srgb, var(--accent, #2563eb) 10%, #f6f9fc);
|
||||
--trade-cal-selected-border: rgba(37, 99, 235, 0.75);
|
||||
--trade-cal-selected-bg: color-mix(in srgb, #2563eb 12%, #f6f9fc);
|
||||
--trade-cal-selected-shadow: rgba(37, 99, 235, 0.35);
|
||||
--trade-cal-sick-tag-fg: #b91c1c;
|
||||
}
|
||||
|
||||
@@ -1,314 +1,314 @@
|
||||
/**
|
||||
* 交易日历组件:内照明心档案 + 四所统计分析共用。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
var WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"];
|
||||
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function monthLabel(y, m) {
|
||||
return y + "年" + m + "月";
|
||||
}
|
||||
|
||||
function formatCalPnl(pnl) {
|
||||
var n = Number(pnl);
|
||||
if (!Number.isFinite(n)) n = 0;
|
||||
return (n >= 0 ? "+" : "") + n.toFixed(1) + "U";
|
||||
}
|
||||
|
||||
function dayHasTrade(info) {
|
||||
if (!info) return false;
|
||||
var cnt = Number(info.open_count);
|
||||
if (Number.isFinite(cnt) && cnt > 0) return true;
|
||||
var pnl = Number(info.pnl_total);
|
||||
return Number.isFinite(pnl) && Math.abs(pnl) > 0.0001;
|
||||
}
|
||||
|
||||
function dayOpenCount(info) {
|
||||
var cnt = Number(info && info.open_count);
|
||||
return Number.isFinite(cnt) && cnt > 0 ? cnt : 0;
|
||||
}
|
||||
|
||||
function dayPnl(info) {
|
||||
return Number(info && info.pnl_total) || 0;
|
||||
}
|
||||
|
||||
function TradeStatsCalendar(config) {
|
||||
this.gridEl = config.gridEl;
|
||||
this.titleEl = config.titleEl;
|
||||
this.prevBtn = config.prevBtn || null;
|
||||
this.nextBtn = config.nextBtn || null;
|
||||
this.apiUrl = config.apiUrl || "/api/stats/calendar";
|
||||
this.buildQuery =
|
||||
config.buildQuery ||
|
||||
function (year, month) {
|
||||
var q = new URLSearchParams();
|
||||
q.set("year", String(year));
|
||||
q.set("month", String(month));
|
||||
return q;
|
||||
};
|
||||
this.parseResponse =
|
||||
config.parseResponse ||
|
||||
function (data) {
|
||||
if (data && data.ok === false) return {};
|
||||
return (data && data.days) || {};
|
||||
};
|
||||
this.fetchFn = config.fetchFn || null;
|
||||
this.showSick = config.showSick !== false;
|
||||
this.selectedDay = config.selectedDay || "";
|
||||
this.onDayClick = config.onDayClick || null;
|
||||
this.onMonthChange = config.onMonthChange || null;
|
||||
this.year = config.year || 0;
|
||||
this.month = config.month || 0;
|
||||
this.days = {};
|
||||
this.monthPnlTotal = 0;
|
||||
this.monthOpenCount = 0;
|
||||
this._navBound = false;
|
||||
this._bindNav();
|
||||
}
|
||||
|
||||
TradeStatsCalendar.prototype.ensureMonth = function (ref) {
|
||||
if (this.year > 0 && this.month > 0) return;
|
||||
var d;
|
||||
if (ref instanceof Date) d = ref;
|
||||
else if (typeof ref === "string" && ref.length >= 7) {
|
||||
var p = ref.slice(0, 10).split("-");
|
||||
this.year = parseInt(p[0], 10) || new Date().getFullYear();
|
||||
this.month = parseInt(p[1], 10) || new Date().getMonth() + 1;
|
||||
return;
|
||||
} else d = new Date();
|
||||
this.year = d.getFullYear();
|
||||
this.month = d.getMonth() + 1;
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.applyPayload = function (data) {
|
||||
if (!data) return;
|
||||
var y = Number(data.year);
|
||||
var m = Number(data.month);
|
||||
if (Number.isFinite(y) && y > 0) this.year = y;
|
||||
if (Number.isFinite(m) && m > 0) this.month = m;
|
||||
this.days = this.parseResponse(data) || {};
|
||||
this.monthPnlTotal = Number(data.month_pnl_total) || 0;
|
||||
this.monthOpenCount = Number(data.month_open_count) || 0;
|
||||
if (!this.monthOpenCount) {
|
||||
var self = this;
|
||||
Object.keys(this.days).forEach(function (k) {
|
||||
if (dayHasTrade(self.days[k])) {
|
||||
self.monthOpenCount += dayOpenCount(self.days[k]);
|
||||
self.monthPnlTotal += dayPnl(self.days[k]);
|
||||
}
|
||||
});
|
||||
this.monthPnlTotal = Math.round(this.monthPnlTotal * 10000) / 10000;
|
||||
}
|
||||
};
|
||||
|
||||
function readStatsCalendarBootstrap() {
|
||||
var el = document.getElementById("stats-calendar-bootstrap");
|
||||
if (!el || !el.textContent) return null;
|
||||
try {
|
||||
return JSON.parse(el.textContent);
|
||||
} catch (e) {
|
||||
console.warn("[trade calendar] bootstrap parse", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
TradeStatsCalendar.prototype.setSelectedDay = function (day) {
|
||||
this.selectedDay = day || "";
|
||||
this.render();
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.render = function () {
|
||||
if (!this.gridEl || !this.titleEl) return;
|
||||
if (this.year <= 0 || this.month <= 0) this.ensureMonth(new Date());
|
||||
var title = monthLabel(this.year, this.month);
|
||||
if (this.monthOpenCount > 0) {
|
||||
title +=
|
||||
" · " + formatCalPnl(this.monthPnlTotal) + " · " + this.monthOpenCount + "笔";
|
||||
}
|
||||
this.titleEl.textContent = title;
|
||||
var first = new Date(this.year, this.month - 1, 1);
|
||||
var lastDay = new Date(this.year, this.month, 0).getDate();
|
||||
var startWd = first.getDay();
|
||||
var html =
|
||||
'<div class="trade-cal-weekdays">' +
|
||||
WEEKDAYS.map(function (w) {
|
||||
return '<span class="trade-cal-wd">' + w + "</span>";
|
||||
}).join("") +
|
||||
'</div><div class="trade-cal-grid">';
|
||||
var i;
|
||||
for (i = 0; i < startWd; i++) {
|
||||
html += '<span class="trade-cal-cell trade-cal-pad"></span>';
|
||||
}
|
||||
for (var d = 1; d <= lastDay; d++) {
|
||||
var dayStr =
|
||||
this.year +
|
||||
"-" +
|
||||
String(this.month).padStart(2, "0") +
|
||||
"-" +
|
||||
String(d).padStart(2, "0");
|
||||
var info = this.days[dayStr];
|
||||
var hasTrade = dayHasTrade(info);
|
||||
var sick = this.showSick && info && info.has_sick;
|
||||
var pnl = hasTrade ? dayPnl(info) : null;
|
||||
var cnt = hasTrade ? dayOpenCount(info) : 0;
|
||||
var cls =
|
||||
"trade-cal-cell" +
|
||||
(hasTrade ? " has-trade" : "") +
|
||||
(sick ? " is-sick-day" : "") +
|
||||
(this.selectedDay === dayStr ? " is-selected" : "") +
|
||||
(pnl != null && pnl > 0.0001
|
||||
? " pnl-pos"
|
||||
: pnl != null && pnl < -0.0001
|
||||
? " pnl-neg"
|
||||
: "");
|
||||
var body = '<span class="trade-cal-day-num">' + d + "</span>";
|
||||
if (hasTrade) {
|
||||
body +=
|
||||
'<span class="trade-cal-pnl">' +
|
||||
esc(formatCalPnl(pnl)) +
|
||||
"</span>" +
|
||||
'<span class="trade-cal-cnt">' +
|
||||
cnt +
|
||||
"笔</span>";
|
||||
if (sick) body += '<span class="trade-cal-sick-tag">犯病</span>';
|
||||
}
|
||||
html +=
|
||||
'<button type="button" class="' +
|
||||
cls +
|
||||
'" data-day="' +
|
||||
dayStr +
|
||||
'" data-sick="' +
|
||||
(sick ? "1" : "0") +
|
||||
'"' +
|
||||
(hasTrade ? "" : " disabled") +
|
||||
">" +
|
||||
body +
|
||||
"</button>";
|
||||
}
|
||||
html += "</div>";
|
||||
this.gridEl.innerHTML = html;
|
||||
var self = this;
|
||||
this.gridEl.querySelectorAll(".trade-cal-cell[data-day]").forEach(function (btn) {
|
||||
btn.addEventListener("click", function () {
|
||||
var day = btn.getAttribute("data-day");
|
||||
if (!day || !self.onDayClick) return;
|
||||
self.selectedDay = day;
|
||||
self.render();
|
||||
self.onDayClick(day, btn.getAttribute("data-sick") === "1", self.days[day] || null);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.load = async function () {
|
||||
this.ensureMonth(new Date());
|
||||
this.render();
|
||||
var q = this.buildQuery(this.year, this.month);
|
||||
if (!q.has("year")) q.set("year", String(this.year));
|
||||
if (!q.has("month")) q.set("month", String(this.month));
|
||||
try {
|
||||
var data;
|
||||
if (this.fetchFn) {
|
||||
data = await this.fetchFn(q);
|
||||
} else {
|
||||
var resp = await fetch(this.apiUrl + "?" + q.toString(), {
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!resp.ok) {
|
||||
console.warn("[trade calendar] api", resp.status);
|
||||
this.render();
|
||||
return;
|
||||
}
|
||||
data = await resp.json();
|
||||
}
|
||||
this.applyPayload(data);
|
||||
this.render();
|
||||
if (this.onMonthChange) this.onMonthChange(this.year, this.month, this.days);
|
||||
} catch (e) {
|
||||
console.warn("[trade calendar]", e);
|
||||
this.render();
|
||||
}
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.shiftMonth = function (delta) {
|
||||
this.ensureMonth(new Date());
|
||||
this.month += delta;
|
||||
if (this.month > 12) {
|
||||
this.month = 1;
|
||||
this.year += 1;
|
||||
} else if (this.month < 1) {
|
||||
this.month = 12;
|
||||
this.year -= 1;
|
||||
}
|
||||
void this.load();
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype._bindNav = function () {
|
||||
if (this._navBound) return;
|
||||
var self = this;
|
||||
if (this.prevBtn) {
|
||||
this.prevBtn.addEventListener("click", function () {
|
||||
self.shiftMonth(-1);
|
||||
});
|
||||
}
|
||||
if (this.nextBtn) {
|
||||
this.nextBtn.addEventListener("click", function () {
|
||||
self.shiftMonth(1);
|
||||
});
|
||||
}
|
||||
this._navBound = true;
|
||||
};
|
||||
|
||||
global.TradeStatsCalendar = TradeStatsCalendar;
|
||||
|
||||
global.statsCalendarWidget = null;
|
||||
|
||||
global.initInstanceStatsCalendar = function () {
|
||||
var grid = document.getElementById("stats-calendar");
|
||||
if (!grid || !global.TradeStatsCalendar) return null;
|
||||
var bootstrap = readStatsCalendarBootstrap();
|
||||
if (
|
||||
global.statsCalendarWidget &&
|
||||
global.statsCalendarWidget.gridEl === grid
|
||||
) {
|
||||
if (bootstrap) global.statsCalendarWidget.applyPayload(bootstrap);
|
||||
global.statsCalendarWidget.render();
|
||||
void global.statsCalendarWidget.load();
|
||||
return global.statsCalendarWidget;
|
||||
}
|
||||
global.statsCalendarWidget = new TradeStatsCalendar({
|
||||
gridEl: grid,
|
||||
titleEl: document.getElementById("stats-cal-title"),
|
||||
prevBtn: document.getElementById("stats-cal-prev"),
|
||||
nextBtn: document.getElementById("stats-cal-next"),
|
||||
apiUrl: "/api/stats/calendar",
|
||||
showSick: false,
|
||||
buildQuery: function (year, month) {
|
||||
var q = new URLSearchParams();
|
||||
q.set("year", String(year));
|
||||
q.set("month", String(month));
|
||||
var sel = document.getElementById("stats-segment-select");
|
||||
if (sel) q.set("segment", sel.value || "all");
|
||||
return q;
|
||||
},
|
||||
parseResponse: function (data) {
|
||||
if (data && data.ok === false) return {};
|
||||
return (data && data.days) || {};
|
||||
},
|
||||
});
|
||||
if (bootstrap) global.statsCalendarWidget.applyPayload(bootstrap);
|
||||
global.statsCalendarWidget.render();
|
||||
void global.statsCalendarWidget.load();
|
||||
return global.statsCalendarWidget;
|
||||
};
|
||||
|
||||
global.initStatsCalendarWidget = global.initInstanceStatsCalendar;
|
||||
})(window);
|
||||
/**
|
||||
* 交易日历组件:内照明心档案 + 三所统计分析共用。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
var WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"];
|
||||
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function monthLabel(y, m) {
|
||||
return y + "年" + m + "月";
|
||||
}
|
||||
|
||||
function formatCalPnl(pnl) {
|
||||
var n = Number(pnl);
|
||||
if (!Number.isFinite(n)) n = 0;
|
||||
return (n >= 0 ? "+" : "") + n.toFixed(1) + "U";
|
||||
}
|
||||
|
||||
function dayHasTrade(info) {
|
||||
if (!info) return false;
|
||||
var cnt = Number(info.open_count);
|
||||
if (Number.isFinite(cnt) && cnt > 0) return true;
|
||||
var pnl = Number(info.pnl_total);
|
||||
return Number.isFinite(pnl) && Math.abs(pnl) > 0.0001;
|
||||
}
|
||||
|
||||
function dayOpenCount(info) {
|
||||
var cnt = Number(info && info.open_count);
|
||||
return Number.isFinite(cnt) && cnt > 0 ? cnt : 0;
|
||||
}
|
||||
|
||||
function dayPnl(info) {
|
||||
return Number(info && info.pnl_total) || 0;
|
||||
}
|
||||
|
||||
function TradeStatsCalendar(config) {
|
||||
this.gridEl = config.gridEl;
|
||||
this.titleEl = config.titleEl;
|
||||
this.prevBtn = config.prevBtn || null;
|
||||
this.nextBtn = config.nextBtn || null;
|
||||
this.apiUrl = config.apiUrl || "/api/stats/calendar";
|
||||
this.buildQuery =
|
||||
config.buildQuery ||
|
||||
function (year, month) {
|
||||
var q = new URLSearchParams();
|
||||
q.set("year", String(year));
|
||||
q.set("month", String(month));
|
||||
return q;
|
||||
};
|
||||
this.parseResponse =
|
||||
config.parseResponse ||
|
||||
function (data) {
|
||||
if (data && data.ok === false) return {};
|
||||
return (data && data.days) || {};
|
||||
};
|
||||
this.fetchFn = config.fetchFn || null;
|
||||
this.showSick = config.showSick !== false;
|
||||
this.selectedDay = config.selectedDay || "";
|
||||
this.onDayClick = config.onDayClick || null;
|
||||
this.onMonthChange = config.onMonthChange || null;
|
||||
this.year = config.year || 0;
|
||||
this.month = config.month || 0;
|
||||
this.days = {};
|
||||
this.monthPnlTotal = 0;
|
||||
this.monthOpenCount = 0;
|
||||
this._navBound = false;
|
||||
this._bindNav();
|
||||
}
|
||||
|
||||
TradeStatsCalendar.prototype.ensureMonth = function (ref) {
|
||||
if (this.year > 0 && this.month > 0) return;
|
||||
var d;
|
||||
if (ref instanceof Date) d = ref;
|
||||
else if (typeof ref === "string" && ref.length >= 7) {
|
||||
var p = ref.slice(0, 10).split("-");
|
||||
this.year = parseInt(p[0], 10) || new Date().getFullYear();
|
||||
this.month = parseInt(p[1], 10) || new Date().getMonth() + 1;
|
||||
return;
|
||||
} else d = new Date();
|
||||
this.year = d.getFullYear();
|
||||
this.month = d.getMonth() + 1;
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.applyPayload = function (data) {
|
||||
if (!data) return;
|
||||
var y = Number(data.year);
|
||||
var m = Number(data.month);
|
||||
if (Number.isFinite(y) && y > 0) this.year = y;
|
||||
if (Number.isFinite(m) && m > 0) this.month = m;
|
||||
this.days = this.parseResponse(data) || {};
|
||||
this.monthPnlTotal = Number(data.month_pnl_total) || 0;
|
||||
this.monthOpenCount = Number(data.month_open_count) || 0;
|
||||
if (!this.monthOpenCount) {
|
||||
var self = this;
|
||||
Object.keys(this.days).forEach(function (k) {
|
||||
if (dayHasTrade(self.days[k])) {
|
||||
self.monthOpenCount += dayOpenCount(self.days[k]);
|
||||
self.monthPnlTotal += dayPnl(self.days[k]);
|
||||
}
|
||||
});
|
||||
this.monthPnlTotal = Math.round(this.monthPnlTotal * 10000) / 10000;
|
||||
}
|
||||
};
|
||||
|
||||
function readStatsCalendarBootstrap() {
|
||||
var el = document.getElementById("stats-calendar-bootstrap");
|
||||
if (!el || !el.textContent) return null;
|
||||
try {
|
||||
return JSON.parse(el.textContent);
|
||||
} catch (e) {
|
||||
console.warn("[trade calendar] bootstrap parse", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
TradeStatsCalendar.prototype.setSelectedDay = function (day) {
|
||||
this.selectedDay = day || "";
|
||||
this.render();
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.render = function () {
|
||||
if (!this.gridEl || !this.titleEl) return;
|
||||
if (this.year <= 0 || this.month <= 0) this.ensureMonth(new Date());
|
||||
var title = monthLabel(this.year, this.month);
|
||||
if (this.monthOpenCount > 0) {
|
||||
title +=
|
||||
" · " + formatCalPnl(this.monthPnlTotal) + " · " + this.monthOpenCount + "笔";
|
||||
}
|
||||
this.titleEl.textContent = title;
|
||||
var first = new Date(this.year, this.month - 1, 1);
|
||||
var lastDay = new Date(this.year, this.month, 0).getDate();
|
||||
var startWd = first.getDay();
|
||||
var html =
|
||||
'<div class="trade-cal-weekdays">' +
|
||||
WEEKDAYS.map(function (w) {
|
||||
return '<span class="trade-cal-wd">' + w + "</span>";
|
||||
}).join("") +
|
||||
'</div><div class="trade-cal-grid">';
|
||||
var i;
|
||||
for (i = 0; i < startWd; i++) {
|
||||
html += '<span class="trade-cal-cell trade-cal-pad"></span>';
|
||||
}
|
||||
for (var d = 1; d <= lastDay; d++) {
|
||||
var dayStr =
|
||||
this.year +
|
||||
"-" +
|
||||
String(this.month).padStart(2, "0") +
|
||||
"-" +
|
||||
String(d).padStart(2, "0");
|
||||
var info = this.days[dayStr];
|
||||
var hasTrade = dayHasTrade(info);
|
||||
var sick = this.showSick && info && info.has_sick;
|
||||
var pnl = hasTrade ? dayPnl(info) : null;
|
||||
var cnt = hasTrade ? dayOpenCount(info) : 0;
|
||||
var cls =
|
||||
"trade-cal-cell" +
|
||||
(hasTrade ? " has-trade" : "") +
|
||||
(sick ? " is-sick-day" : "") +
|
||||
(this.selectedDay === dayStr ? " is-selected" : "") +
|
||||
(pnl != null && pnl > 0.0001
|
||||
? " pnl-pos"
|
||||
: pnl != null && pnl < -0.0001
|
||||
? " pnl-neg"
|
||||
: "");
|
||||
var body = '<span class="trade-cal-day-num">' + d + "</span>";
|
||||
if (hasTrade) {
|
||||
body +=
|
||||
'<span class="trade-cal-pnl">' +
|
||||
esc(formatCalPnl(pnl)) +
|
||||
"</span>" +
|
||||
'<span class="trade-cal-cnt">' +
|
||||
cnt +
|
||||
"笔</span>";
|
||||
if (sick) body += '<span class="trade-cal-sick-tag">犯病</span>';
|
||||
}
|
||||
html +=
|
||||
'<button type="button" class="' +
|
||||
cls +
|
||||
'" data-day="' +
|
||||
dayStr +
|
||||
'" data-sick="' +
|
||||
(sick ? "1" : "0") +
|
||||
'"' +
|
||||
(hasTrade ? "" : " disabled") +
|
||||
">" +
|
||||
body +
|
||||
"</button>";
|
||||
}
|
||||
html += "</div>";
|
||||
this.gridEl.innerHTML = html;
|
||||
var self = this;
|
||||
this.gridEl.querySelectorAll(".trade-cal-cell[data-day]").forEach(function (btn) {
|
||||
btn.addEventListener("click", function () {
|
||||
var day = btn.getAttribute("data-day");
|
||||
if (!day || !self.onDayClick) return;
|
||||
self.selectedDay = day;
|
||||
self.render();
|
||||
self.onDayClick(day, btn.getAttribute("data-sick") === "1", self.days[day] || null);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.load = async function () {
|
||||
this.ensureMonth(new Date());
|
||||
this.render();
|
||||
var q = this.buildQuery(this.year, this.month);
|
||||
if (!q.has("year")) q.set("year", String(this.year));
|
||||
if (!q.has("month")) q.set("month", String(this.month));
|
||||
try {
|
||||
var data;
|
||||
if (this.fetchFn) {
|
||||
data = await this.fetchFn(q);
|
||||
} else {
|
||||
var resp = await fetch(this.apiUrl + "?" + q.toString(), {
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!resp.ok) {
|
||||
console.warn("[trade calendar] api", resp.status);
|
||||
this.render();
|
||||
return;
|
||||
}
|
||||
data = await resp.json();
|
||||
}
|
||||
this.applyPayload(data);
|
||||
this.render();
|
||||
if (this.onMonthChange) this.onMonthChange(this.year, this.month, this.days);
|
||||
} catch (e) {
|
||||
console.warn("[trade calendar]", e);
|
||||
this.render();
|
||||
}
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype.shiftMonth = function (delta) {
|
||||
this.ensureMonth(new Date());
|
||||
this.month += delta;
|
||||
if (this.month > 12) {
|
||||
this.month = 1;
|
||||
this.year += 1;
|
||||
} else if (this.month < 1) {
|
||||
this.month = 12;
|
||||
this.year -= 1;
|
||||
}
|
||||
void this.load();
|
||||
};
|
||||
|
||||
TradeStatsCalendar.prototype._bindNav = function () {
|
||||
if (this._navBound) return;
|
||||
var self = this;
|
||||
if (this.prevBtn) {
|
||||
this.prevBtn.addEventListener("click", function () {
|
||||
self.shiftMonth(-1);
|
||||
});
|
||||
}
|
||||
if (this.nextBtn) {
|
||||
this.nextBtn.addEventListener("click", function () {
|
||||
self.shiftMonth(1);
|
||||
});
|
||||
}
|
||||
this._navBound = true;
|
||||
};
|
||||
|
||||
global.TradeStatsCalendar = TradeStatsCalendar;
|
||||
|
||||
global.statsCalendarWidget = null;
|
||||
|
||||
global.initInstanceStatsCalendar = function () {
|
||||
var grid = document.getElementById("stats-calendar");
|
||||
if (!grid || !global.TradeStatsCalendar) return null;
|
||||
var bootstrap = readStatsCalendarBootstrap();
|
||||
if (
|
||||
global.statsCalendarWidget &&
|
||||
global.statsCalendarWidget.gridEl === grid
|
||||
) {
|
||||
if (bootstrap) global.statsCalendarWidget.applyPayload(bootstrap);
|
||||
global.statsCalendarWidget.render();
|
||||
void global.statsCalendarWidget.load();
|
||||
return global.statsCalendarWidget;
|
||||
}
|
||||
global.statsCalendarWidget = new TradeStatsCalendar({
|
||||
gridEl: grid,
|
||||
titleEl: document.getElementById("stats-cal-title"),
|
||||
prevBtn: document.getElementById("stats-cal-prev"),
|
||||
nextBtn: document.getElementById("stats-cal-next"),
|
||||
apiUrl: "/api/stats/calendar",
|
||||
showSick: false,
|
||||
buildQuery: function (year, month) {
|
||||
var q = new URLSearchParams();
|
||||
q.set("year", String(year));
|
||||
q.set("month", String(month));
|
||||
var sel = document.getElementById("stats-segment-select");
|
||||
if (sel) q.set("segment", sel.value || "all");
|
||||
return q;
|
||||
},
|
||||
parseResponse: function (data) {
|
||||
if (data && data.ok === false) return {};
|
||||
return (data && data.days) || {};
|
||||
},
|
||||
});
|
||||
if (bootstrap) global.statsCalendarWidget.applyPayload(bootstrap);
|
||||
global.statsCalendarWidget.render();
|
||||
void global.statsCalendarWidget.load();
|
||||
return global.statsCalendarWidget;
|
||||
};
|
||||
|
||||
global.initStatsCalendarWidget = global.initInstanceStatsCalendar;
|
||||
})(window);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Gate.io ccxt 构造(ccxt 4.x 起类名由 gateio 改为 gate)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ccxt
|
||||
|
||||
|
||||
def gate_ccxt_class():
|
||||
"""返回 ccxt Gate 交易所类(兼容旧版 gateio 名称)。"""
|
||||
return getattr(ccxt, "gate", None) or ccxt.gateio
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Gate.io 资金划转(crypto_monitor_gate / crypto_monitor_gate_bot 共用)。"""
|
||||
"""Gate.io 资金划转(crypto_monitor_gate 共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""中控备份与恢复:四所 SQLite、K 线库、env、hub JSON。"""
|
||||
"""中控备份与恢复:三所 SQLite、K 线库、env、hub JSON。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -22,7 +22,6 @@ EXCHANGE_DIRS: list[tuple[str, str]] = [
|
||||
("binance", "crypto_monitor_binance"),
|
||||
("okx", "crypto_monitor_okx"),
|
||||
("gate", "crypto_monitor_gate"),
|
||||
("gate_bot", "crypto_monitor_gate_bot"),
|
||||
]
|
||||
|
||||
HUB_JSON_FILES = (
|
||||
|
||||
@@ -42,7 +42,7 @@ def _merge_query_into_path(path: str, **params: str) -> str:
|
||||
|
||||
|
||||
def install_instance_theme_static(app) -> None:
|
||||
"""仓库 lib/common/static 下 instance_theme.* 等供四所页面共用。"""
|
||||
"""仓库 lib/common/static 下 instance_theme.* 等供三所页面共用。"""
|
||||
import os
|
||||
|
||||
from flask import Response, send_file
|
||||
@@ -96,7 +96,7 @@ def register_trade_stats_calendar_route(
|
||||
reset_hour: int,
|
||||
get_db_fn=None,
|
||||
):
|
||||
"""四所统计分析页:按月返回各交易日盈亏/笔数。"""
|
||||
"""三所统计分析页:按月返回各交易日盈亏/笔数。"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from lib.trade.trade_stats_calendar_lib import build_trade_stats_calendar
|
||||
@@ -630,6 +630,7 @@ def register_hub_routes(app):
|
||||
fetch_trades_for_trading_day,
|
||||
summarize_trades,
|
||||
)
|
||||
from lib.trade.daily_open_limit_lib import count_opens_for_trading_day
|
||||
|
||||
c = _ctx()
|
||||
get_db = c.get("get_db")
|
||||
@@ -651,6 +652,7 @@ def register_hub_routes(app):
|
||||
row_to_dict_fn=c.get("row_to_dict"),
|
||||
reset_hour=reset_hour,
|
||||
)
|
||||
opens_today = count_opens_for_trading_day(conn, trading_day)
|
||||
finally:
|
||||
conn.close()
|
||||
stats = summarize_trades(trades)
|
||||
@@ -659,6 +661,7 @@ def register_hub_routes(app):
|
||||
"ok": True,
|
||||
"trading_day": trading_day,
|
||||
"trading_day_reset_hour": reset_hour,
|
||||
"opens_today": opens_today,
|
||||
"trades": trades,
|
||||
"stats": stats,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""监控区看板:三所当日统计聚合。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _coerce_float(value: Any) -> float | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def position_unrealized_pnl(pos: dict[str, Any]) -> float:
|
||||
for key in ("unrealized_pnl", "unrealizedPnl", "upnl"):
|
||||
v = _coerce_float(pos.get(key))
|
||||
if v is not None:
|
||||
return v
|
||||
return 0.0
|
||||
|
||||
|
||||
def _open_positions(agent: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
if not isinstance(agent, dict):
|
||||
return []
|
||||
positions = agent.get("positions")
|
||||
if not isinstance(positions, list):
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for p in positions:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
try:
|
||||
c = abs(float(p.get("contracts") or 0))
|
||||
except (TypeError, ValueError):
|
||||
c = 0.0
|
||||
if c > 1e-12:
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
|
||||
def aggregate_monitor_board_totals(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
trading_day: str,
|
||||
reset_hour: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
"""汇总监控 board 各行 → 左上统计卡数据。"""
|
||||
open_count = 0
|
||||
closed_count = 0
|
||||
win_count = 0
|
||||
loss_count = 0
|
||||
win_pnl_u = 0.0
|
||||
loss_pnl_u = 0.0
|
||||
open_position_count = 0
|
||||
float_pnl_u = 0.0
|
||||
|
||||
for row in rows or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
day_stats = row.get("day_stats") if isinstance(row.get("day_stats"), dict) else {}
|
||||
if day_stats.get("ok"):
|
||||
open_count += int(day_stats.get("opens_today") or 0)
|
||||
st = day_stats.get("trade_stats") if isinstance(day_stats.get("trade_stats"), dict) else {}
|
||||
closed_count += int(st.get("closed_count") or 0)
|
||||
win_count += int(st.get("win_count") or 0)
|
||||
loss_count += int(st.get("loss_count") or 0)
|
||||
win_pnl_u += float(st.get("win_pnl_u") or 0)
|
||||
loss_pnl_u += float(st.get("loss_pnl_u") or 0)
|
||||
|
||||
ag = row.get("agent") if isinstance(row.get("agent"), dict) else {}
|
||||
open_pos = _open_positions(ag)
|
||||
open_position_count += len(open_pos)
|
||||
agent_upnl = _coerce_float(ag.get("total_unrealized_pnl"))
|
||||
if agent_upnl is not None:
|
||||
float_pnl_u += agent_upnl
|
||||
else:
|
||||
float_pnl_u += sum(position_unrealized_pnl(p) for p in open_pos)
|
||||
|
||||
return {
|
||||
"trading_day": trading_day,
|
||||
"reset_hour": int(reset_hour),
|
||||
"open_count": open_count,
|
||||
"closed_count": closed_count,
|
||||
"win_count": win_count,
|
||||
"loss_count": loss_count,
|
||||
"win_pnl_u": round(win_pnl_u, 4),
|
||||
"loss_pnl_u": round(loss_pnl_u, 4),
|
||||
"realized_pnl_u": round(win_pnl_u + loss_pnl_u, 4),
|
||||
"open_position_count": open_position_count,
|
||||
"float_pnl_u": round(float_pnl_u, 4),
|
||||
}
|
||||
@@ -1,252 +1,252 @@
|
||||
"""ccxt 持仓标记价解析(实例 price_snapshot 与中控子代理共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _finite_or_none(x: Any) -> float | None:
|
||||
try:
|
||||
f = float(x)
|
||||
return f if math.isfinite(f) else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _coerce_float(*values: Any) -> float | None:
|
||||
for v in values:
|
||||
if v is None or v == "":
|
||||
continue
|
||||
px = _finite_or_none(v)
|
||||
if px is not None and px > 0:
|
||||
return px
|
||||
return None
|
||||
|
||||
|
||||
def position_contracts(p: dict[str, Any]) -> float:
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
# OKX 等:info.pos 为交易所张数,优先于 ccxt contracts(加仓后后者可能滞后)
|
||||
for k in ("pos", "positionAmt", "positionamt", "size"):
|
||||
if k in info:
|
||||
try:
|
||||
v = float(info[k])
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
raw = p.get("contracts")
|
||||
if raw is not None:
|
||||
try:
|
||||
v = float(raw)
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return 0.0
|
||||
|
||||
|
||||
def position_side_from_ccxt(p: dict[str, Any], contracts: float | None = None) -> str:
|
||||
s = (p.get("side") or "").lower()
|
||||
if s in ("long", "short"):
|
||||
return s
|
||||
c = contracts if contracts is not None else position_contracts(p)
|
||||
if c > 0:
|
||||
return "long"
|
||||
if c < 0:
|
||||
return "short"
|
||||
return "long"
|
||||
|
||||
|
||||
def parse_position_entry_price(p: dict[str, Any]) -> float | None:
|
||||
"""四所 ccxt 持仓开仓均价。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
return _coerce_float(
|
||||
p.get("entryPrice"),
|
||||
p.get("entry_price"),
|
||||
p.get("average"),
|
||||
info.get("entryPrice"),
|
||||
info.get("entry_price"),
|
||||
info.get("avgPx"),
|
||||
info.get("avgEntryPrice"),
|
||||
info.get("avg_entry_price"),
|
||||
info.get("avgPrice"),
|
||||
info.get("openAvgPx"),
|
||||
)
|
||||
|
||||
|
||||
def estimate_linear_swap_upnl_usdt(
|
||||
side: str,
|
||||
entry: float | None,
|
||||
mark: float | None,
|
||||
contracts: float | None,
|
||||
contract_size: float | None = None,
|
||||
) -> float | None:
|
||||
"""U 本位线性永续:浮盈 = (标记价 - 开仓价) × 张数 × contractSize(空头取反)。"""
|
||||
e = _finite_or_none(entry)
|
||||
m = _finite_or_none(mark)
|
||||
c = _finite_or_none(contracts)
|
||||
if e is None or m is None or c is None or c <= 0:
|
||||
return None
|
||||
mult = _finite_or_none(contract_size)
|
||||
if mult is None or mult <= 0:
|
||||
mult = 1.0
|
||||
diff = (m - e) if (side or "long").strip().lower() == "long" else (e - m)
|
||||
return round(diff * abs(c) * mult, 2)
|
||||
|
||||
|
||||
def resolve_position_display_upnl(
|
||||
side: str,
|
||||
entry: float | None,
|
||||
mark: float | None,
|
||||
contracts: float | None,
|
||||
contract_size: float | None,
|
||||
exchange_upnl: float | None,
|
||||
) -> float | None:
|
||||
"""展示用浮盈:优先与标记价/张数一致的推算;与交易所值偏差过大时用推算值。"""
|
||||
computed = estimate_linear_swap_upnl_usdt(
|
||||
side, entry, mark, contracts, contract_size
|
||||
)
|
||||
if computed is None:
|
||||
return exchange_upnl
|
||||
if exchange_upnl is None:
|
||||
return computed
|
||||
ref = max(abs(computed), 1.0)
|
||||
if abs(exchange_upnl - computed) / ref > 0.2:
|
||||
return computed
|
||||
return exchange_upnl
|
||||
|
||||
|
||||
def _coerce_signed(*values: Any) -> float | None:
|
||||
"""解析可正可负的数值(未实现盈亏等)。"""
|
||||
for v in values:
|
||||
if v is None or v == "":
|
||||
continue
|
||||
f = _finite_or_none(v)
|
||||
if f is not None:
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def parse_position_unrealized_pnl(p: dict[str, Any]) -> float | None:
|
||||
"""四所 ccxt 持仓统一解析未实现盈亏(Gate/OKX/Binance 字段名不一致)。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
return _coerce_signed(
|
||||
p.get("unrealizedPnl"),
|
||||
p.get("unrealisedPnl"),
|
||||
p.get("unrealized_pnl"),
|
||||
p.get("unrealised_pnl"),
|
||||
info.get("unrealised_pnl"),
|
||||
info.get("unrealized_pnl"),
|
||||
info.get("unrealisedPnl"),
|
||||
info.get("unrealizedPnl"),
|
||||
info.get("upl"),
|
||||
info.get("uplLast"),
|
||||
)
|
||||
|
||||
|
||||
def enrich_ccxt_position_metrics_out(
|
||||
position: dict[str, Any],
|
||||
out: dict[str, Any],
|
||||
*,
|
||||
contract_size: float = 1.0,
|
||||
funds_decimals: int = 2,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
四所 parse_ccxt_position_metrics 产出后统一:
|
||||
- 标记价用 hub 兜底
|
||||
- 未实现盈亏 = resolve(交易所值, entry/mark/张数/contractSize 推算)
|
||||
"""
|
||||
if not isinstance(position, dict) or not isinstance(out, dict):
|
||||
return out
|
||||
mark = _finite_or_none(out.get("mark_price"))
|
||||
if mark is None or mark <= 0:
|
||||
mp = parse_position_mark_price(position)
|
||||
if mp is not None and mp > 0:
|
||||
out["mark_price"] = round(mp, 8)
|
||||
mark = mp
|
||||
exchange_upnl = parse_position_unrealized_pnl(position)
|
||||
if exchange_upnl is None:
|
||||
exchange_upnl = _coerce_signed(out.get("unrealized_pnl"))
|
||||
c = position_contracts(position)
|
||||
if abs(c) < 1e-12:
|
||||
return out
|
||||
side = position_side_from_ccxt(position, c)
|
||||
entry = parse_position_entry_price(position)
|
||||
if entry is not None and entry > 0:
|
||||
out["entry_price"] = round(entry, 8)
|
||||
cs = contract_size if contract_size and contract_size > 0 else 1.0
|
||||
upnl = resolve_position_display_upnl(
|
||||
side, entry, mark, abs(c), cs, exchange_upnl
|
||||
)
|
||||
if upnl is not None:
|
||||
out["unrealized_pnl"] = round(upnl, funds_decimals)
|
||||
return out
|
||||
|
||||
|
||||
def parse_position_mark_price(p: dict[str, Any]) -> float | None:
|
||||
"""四所 ccxt 持仓统一解析标记价(与 crypto_monitor_* parse_ccxt_position_metrics 口径一致)。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
mark = _coerce_float(
|
||||
p.get("markPrice"),
|
||||
p.get("mark_price"),
|
||||
p.get("mark"),
|
||||
info.get("markPx"),
|
||||
info.get("mark_price"),
|
||||
info.get("markPrice"),
|
||||
)
|
||||
if mark is not None:
|
||||
return mark
|
||||
contracts = position_contracts(p)
|
||||
if abs(contracts) >= 1e-12:
|
||||
notional = _finite_or_none(p.get("notional"))
|
||||
if notional is not None and abs(notional) > 0:
|
||||
return abs(notional) / abs(contracts)
|
||||
return None
|
||||
|
||||
|
||||
def build_position_marks_list(
|
||||
positions: list,
|
||||
*,
|
||||
format_mark_display: Callable[[str, float], str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从 fetch_positions 结果生成 position_marks,供 price_snapshot / 中控合并。"""
|
||||
out: list[dict[str, Any]] = []
|
||||
for p in positions or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
c = position_contracts(p)
|
||||
if abs(c) < 1e-12:
|
||||
continue
|
||||
mark = parse_position_mark_price(p)
|
||||
if mark is None or mark <= 0:
|
||||
continue
|
||||
sym = (p.get("symbol") or "").strip()
|
||||
side = position_side_from_ccxt(p, c)
|
||||
row: dict[str, Any] = {
|
||||
"symbol": sym,
|
||||
"side": side,
|
||||
"mark_price": mark,
|
||||
}
|
||||
if format_mark_display and sym:
|
||||
try:
|
||||
row["mark_price_display"] = format_mark_display(sym, mark)
|
||||
except Exception:
|
||||
row["mark_price_display"] = f"{mark:g}"
|
||||
else:
|
||||
row["mark_price_display"] = f"{mark:g}"
|
||||
out.append(row)
|
||||
return out
|
||||
"""ccxt 持仓标记价解析(实例 price_snapshot 与中控子代理共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _finite_or_none(x: Any) -> float | None:
|
||||
try:
|
||||
f = float(x)
|
||||
return f if math.isfinite(f) else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _coerce_float(*values: Any) -> float | None:
|
||||
for v in values:
|
||||
if v is None or v == "":
|
||||
continue
|
||||
px = _finite_or_none(v)
|
||||
if px is not None and px > 0:
|
||||
return px
|
||||
return None
|
||||
|
||||
|
||||
def position_contracts(p: dict[str, Any]) -> float:
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
# OKX 等:info.pos 为交易所张数,优先于 ccxt contracts(加仓后后者可能滞后)
|
||||
for k in ("pos", "positionAmt", "positionamt", "size"):
|
||||
if k in info:
|
||||
try:
|
||||
v = float(info[k])
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
raw = p.get("contracts")
|
||||
if raw is not None:
|
||||
try:
|
||||
v = float(raw)
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return 0.0
|
||||
|
||||
|
||||
def position_side_from_ccxt(p: dict[str, Any], contracts: float | None = None) -> str:
|
||||
s = (p.get("side") or "").lower()
|
||||
if s in ("long", "short"):
|
||||
return s
|
||||
c = contracts if contracts is not None else position_contracts(p)
|
||||
if c > 0:
|
||||
return "long"
|
||||
if c < 0:
|
||||
return "short"
|
||||
return "long"
|
||||
|
||||
|
||||
def parse_position_entry_price(p: dict[str, Any]) -> float | None:
|
||||
"""三所 ccxt 持仓开仓均价。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
return _coerce_float(
|
||||
p.get("entryPrice"),
|
||||
p.get("entry_price"),
|
||||
p.get("average"),
|
||||
info.get("entryPrice"),
|
||||
info.get("entry_price"),
|
||||
info.get("avgPx"),
|
||||
info.get("avgEntryPrice"),
|
||||
info.get("avg_entry_price"),
|
||||
info.get("avgPrice"),
|
||||
info.get("openAvgPx"),
|
||||
)
|
||||
|
||||
|
||||
def estimate_linear_swap_upnl_usdt(
|
||||
side: str,
|
||||
entry: float | None,
|
||||
mark: float | None,
|
||||
contracts: float | None,
|
||||
contract_size: float | None = None,
|
||||
) -> float | None:
|
||||
"""U 本位线性永续:浮盈 = (标记价 - 开仓价) × 张数 × contractSize(空头取反)。"""
|
||||
e = _finite_or_none(entry)
|
||||
m = _finite_or_none(mark)
|
||||
c = _finite_or_none(contracts)
|
||||
if e is None or m is None or c is None or c <= 0:
|
||||
return None
|
||||
mult = _finite_or_none(contract_size)
|
||||
if mult is None or mult <= 0:
|
||||
mult = 1.0
|
||||
diff = (m - e) if (side or "long").strip().lower() == "long" else (e - m)
|
||||
return round(diff * abs(c) * mult, 2)
|
||||
|
||||
|
||||
def resolve_position_display_upnl(
|
||||
side: str,
|
||||
entry: float | None,
|
||||
mark: float | None,
|
||||
contracts: float | None,
|
||||
contract_size: float | None,
|
||||
exchange_upnl: float | None,
|
||||
) -> float | None:
|
||||
"""展示用浮盈:优先与标记价/张数一致的推算;与交易所值偏差过大时用推算值。"""
|
||||
computed = estimate_linear_swap_upnl_usdt(
|
||||
side, entry, mark, contracts, contract_size
|
||||
)
|
||||
if computed is None:
|
||||
return exchange_upnl
|
||||
if exchange_upnl is None:
|
||||
return computed
|
||||
ref = max(abs(computed), 1.0)
|
||||
if abs(exchange_upnl - computed) / ref > 0.2:
|
||||
return computed
|
||||
return exchange_upnl
|
||||
|
||||
|
||||
def _coerce_signed(*values: Any) -> float | None:
|
||||
"""解析可正可负的数值(未实现盈亏等)。"""
|
||||
for v in values:
|
||||
if v is None or v == "":
|
||||
continue
|
||||
f = _finite_or_none(v)
|
||||
if f is not None:
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def parse_position_unrealized_pnl(p: dict[str, Any]) -> float | None:
|
||||
"""三所 ccxt 持仓统一解析未实现盈亏(Gate/OKX/Binance 字段名不一致)。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
return _coerce_signed(
|
||||
p.get("unrealizedPnl"),
|
||||
p.get("unrealisedPnl"),
|
||||
p.get("unrealized_pnl"),
|
||||
p.get("unrealised_pnl"),
|
||||
info.get("unrealised_pnl"),
|
||||
info.get("unrealized_pnl"),
|
||||
info.get("unrealisedPnl"),
|
||||
info.get("unrealizedPnl"),
|
||||
info.get("upl"),
|
||||
info.get("uplLast"),
|
||||
)
|
||||
|
||||
|
||||
def enrich_ccxt_position_metrics_out(
|
||||
position: dict[str, Any],
|
||||
out: dict[str, Any],
|
||||
*,
|
||||
contract_size: float = 1.0,
|
||||
funds_decimals: int = 2,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
三所 parse_ccxt_position_metrics 产出后统一:
|
||||
- 标记价用 hub 兜底
|
||||
- 未实现盈亏 = resolve(交易所值, entry/mark/张数/contractSize 推算)
|
||||
"""
|
||||
if not isinstance(position, dict) or not isinstance(out, dict):
|
||||
return out
|
||||
mark = _finite_or_none(out.get("mark_price"))
|
||||
if mark is None or mark <= 0:
|
||||
mp = parse_position_mark_price(position)
|
||||
if mp is not None and mp > 0:
|
||||
out["mark_price"] = round(mp, 8)
|
||||
mark = mp
|
||||
exchange_upnl = parse_position_unrealized_pnl(position)
|
||||
if exchange_upnl is None:
|
||||
exchange_upnl = _coerce_signed(out.get("unrealized_pnl"))
|
||||
c = position_contracts(position)
|
||||
if abs(c) < 1e-12:
|
||||
return out
|
||||
side = position_side_from_ccxt(position, c)
|
||||
entry = parse_position_entry_price(position)
|
||||
if entry is not None and entry > 0:
|
||||
out["entry_price"] = round(entry, 8)
|
||||
cs = contract_size if contract_size and contract_size > 0 else 1.0
|
||||
upnl = resolve_position_display_upnl(
|
||||
side, entry, mark, abs(c), cs, exchange_upnl
|
||||
)
|
||||
if upnl is not None:
|
||||
out["unrealized_pnl"] = round(upnl, funds_decimals)
|
||||
return out
|
||||
|
||||
|
||||
def parse_position_mark_price(p: dict[str, Any]) -> float | None:
|
||||
"""三所 ccxt 持仓统一解析标记价(与 crypto_monitor_* parse_ccxt_position_metrics 口径一致)。"""
|
||||
if not isinstance(p, dict):
|
||||
return None
|
||||
info = p.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
mark = _coerce_float(
|
||||
p.get("markPrice"),
|
||||
p.get("mark_price"),
|
||||
p.get("mark"),
|
||||
info.get("markPx"),
|
||||
info.get("mark_price"),
|
||||
info.get("markPrice"),
|
||||
)
|
||||
if mark is not None:
|
||||
return mark
|
||||
contracts = position_contracts(p)
|
||||
if abs(contracts) >= 1e-12:
|
||||
notional = _finite_or_none(p.get("notional"))
|
||||
if notional is not None and abs(notional) > 0:
|
||||
return abs(notional) / abs(contracts)
|
||||
return None
|
||||
|
||||
|
||||
def build_position_marks_list(
|
||||
positions: list,
|
||||
*,
|
||||
format_mark_display: Callable[[str, float], str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从 fetch_positions 结果生成 position_marks,供 price_snapshot / 中控合并。"""
|
||||
out: list[dict[str, Any]] = []
|
||||
for p in positions or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
c = position_contracts(p)
|
||||
if abs(c) < 1e-12:
|
||||
continue
|
||||
mark = parse_position_mark_price(p)
|
||||
if mark is None or mark <= 0:
|
||||
continue
|
||||
sym = (p.get("symbol") or "").strip()
|
||||
side = position_side_from_ccxt(p, c)
|
||||
row: dict[str, Any] = {
|
||||
"symbol": sym,
|
||||
"side": side,
|
||||
"mark_price": mark,
|
||||
}
|
||||
if format_mark_display and sym:
|
||||
try:
|
||||
row["mark_price_display"] = format_mark_display(sym, mark)
|
||||
except Exception:
|
||||
row["mark_price_display"] = f"{mark:g}"
|
||||
else:
|
||||
row["mark_price_display"] = f"{mark:g}"
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Hub 中控市价全平后立即同步 order_monitors(三所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def reconcile_hub_external_close_impl(
|
||||
conn,
|
||||
symbol: str,
|
||||
direction: str,
|
||||
*,
|
||||
exchange_configured: Callable[[], bool],
|
||||
not_configured_msg: str,
|
||||
symbols_match: Callable[[str, str], bool],
|
||||
get_opened_at_value: Callable[[Any], str],
|
||||
resolve_monitor_exchange_symbol: Callable[[Any], str],
|
||||
get_live_position_contracts: Callable[[str, str], float | None],
|
||||
cancel_conditional_orders: Callable[[str], None],
|
||||
resolve_synced_flat_close: Callable[..., tuple],
|
||||
finalize_stopped_monitor: Callable[..., None],
|
||||
sync_trade_records: Callable[..., None] | None = None,
|
||||
reconcile_flat_streak: dict | None = None,
|
||||
to_ms_with_fallback: Callable[..., int | None] | None = None,
|
||||
prefer_manual_resolve: bool = False,
|
||||
order_row_monitor_type: Callable[[Any], str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if not exchange_configured():
|
||||
return {"ok": False, "msg": not_configured_msg, "synced": 0}
|
||||
sym_req = (symbol or "").strip()
|
||||
dir_l = (direction or "").strip().lower()
|
||||
if dir_l not in ("long", "short"):
|
||||
return {"ok": False, "msg": "side 须为 long 或 short", "synced": 0}
|
||||
synced = 0
|
||||
streak = reconcile_flat_streak if reconcile_flat_streak is not None else {}
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM order_monitors WHERE status IN ('active', 'error')"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
if not symbols_match(str(r["symbol"] or ""), sym_req):
|
||||
continue
|
||||
if (r["direction"] or "").strip().lower() != dir_l:
|
||||
continue
|
||||
oid = int(r["id"])
|
||||
if r["status"] == "error":
|
||||
opened_at_chk = get_opened_at_value(r)
|
||||
mtype = order_row_monitor_type(r) if order_row_monitor_type else r["monitor_type"]
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM trade_records WHERE symbol=? AND opened_at=? AND monitor_type=? LIMIT 1",
|
||||
(r["symbol"], opened_at_chk, mtype),
|
||||
).fetchone()
|
||||
if existing:
|
||||
conn.execute("UPDATE order_monitors SET status='stopped' WHERE id=?", (oid,))
|
||||
synced += 1
|
||||
continue
|
||||
exchange_symbol = resolve_monitor_exchange_symbol(r)
|
||||
live_contracts = get_live_position_contracts(exchange_symbol, r["direction"])
|
||||
if live_contracts is None:
|
||||
continue
|
||||
if live_contracts > 0:
|
||||
time.sleep(0.6)
|
||||
live_contracts = get_live_position_contracts(exchange_symbol, r["direction"])
|
||||
if live_contracts is None or live_contracts > 0:
|
||||
continue
|
||||
streak.pop(oid, None)
|
||||
cancel_conditional_orders(exchange_symbol)
|
||||
opened_at = get_opened_at_value(r)
|
||||
opened_at_ms = None
|
||||
if to_ms_with_fallback is not None:
|
||||
keys = r.keys() if hasattr(r, "keys") else ()
|
||||
opened_at_ms = to_ms_with_fallback(
|
||||
r["opened_at_ms"] if "opened_at_ms" in keys else None,
|
||||
opened_at,
|
||||
)
|
||||
resolve_kw = {"opened_at_ms": opened_at_ms}
|
||||
if prefer_manual_resolve:
|
||||
resolve_kw["prefer_manual"] = True
|
||||
result, pnl_amount, closed_at, miss_reason = resolve_synced_flat_close(
|
||||
r, opened_at, **resolve_kw
|
||||
)
|
||||
finalize_stopped_monitor(
|
||||
conn,
|
||||
r,
|
||||
result=result,
|
||||
pnl_amount=pnl_amount,
|
||||
closed_at=closed_at,
|
||||
miss_reason=miss_reason,
|
||||
)
|
||||
synced += 1
|
||||
if sync_trade_records is not None:
|
||||
try:
|
||||
sync_trade_records(conn, force=True)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "synced": synced}
|
||||
@@ -616,6 +616,8 @@ def fetch_trades_for_archive(
|
||||
def summarize_trades(trades: list[dict]) -> dict[str, Any]:
|
||||
"""单笔列表 → 笔数 / 盈亏 / 胜败统计。"""
|
||||
total_pnl = 0.0
|
||||
win_pnl = 0.0
|
||||
loss_pnl = 0.0
|
||||
win = loss = flat = 0
|
||||
for t in trades or []:
|
||||
try:
|
||||
@@ -625,8 +627,10 @@ def summarize_trades(trades: list[dict]) -> dict[str, Any]:
|
||||
total_pnl += pnl
|
||||
if pnl > 1e-9:
|
||||
win += 1
|
||||
win_pnl += pnl
|
||||
elif pnl < -1e-9:
|
||||
loss += 1
|
||||
loss_pnl += pnl
|
||||
else:
|
||||
flat += 1
|
||||
return {
|
||||
@@ -635,4 +639,6 @@ def summarize_trades(trades: list[dict]) -> dict[str, Any]:
|
||||
"loss_count": loss,
|
||||
"flat_count": flat,
|
||||
"total_pnl_u": round(total_pnl, 4),
|
||||
"win_pnl_u": round(win_pnl, 4),
|
||||
"loss_pnl_u": round(loss_pnl, 4),
|
||||
}
|
||||
|
||||
@@ -365,7 +365,7 @@ def _collect_scores(exchange, exchange_id: str) -> list[tuple[str, str, float]]:
|
||||
return _scores_from_okx(exchange)
|
||||
if ex_id == "binance":
|
||||
return _scores_from_binance(exchange)
|
||||
if ex_id in ("gateio", "gate", "gate_bot"):
|
||||
if ex_id in ("gateio", "gate"):
|
||||
return _scores_from_gate(exchange)
|
||||
tickers = exchange.fetch_tickers()
|
||||
return _scores_from_markets(exchange, tickers or {}, ex_id)
|
||||
@@ -373,7 +373,7 @@ def _collect_scores(exchange, exchange_id: str) -> list[tuple[str, str, float]]:
|
||||
|
||||
def _uses_lightweight_volume_scores(exchange_id: str) -> bool:
|
||||
ex_id = str(exchange_id or "").lower()
|
||||
return ex_id in ("okx", "binance", "gateio", "gate", "gate_bot")
|
||||
return ex_id in ("okx", "binance", "gateio", "gate")
|
||||
|
||||
|
||||
def build_usdt_swap_volume_ranks(
|
||||
|
||||
@@ -33,7 +33,6 @@ PATH_TO_EMBED_TAB: dict[str, str] = {
|
||||
|
||||
ORDER_RULE_TIPS_BY_EXCHANGE: dict[str, str] = {
|
||||
"gate": "order_monitor_rule_tips_gate.html",
|
||||
"gate_bot": "order_monitor_rule_tips_gate.html",
|
||||
"binance": "order_monitor_rule_tips_binance.html",
|
||||
"okx": "order_monitor_rule_tips_okx.html",
|
||||
}
|
||||
@@ -45,7 +44,7 @@ def order_rule_tips_template(exchange_key: str) -> str:
|
||||
|
||||
|
||||
def include_transfer_block(exchange_key: str) -> bool:
|
||||
return (exchange_key or "").strip().lower() in ("gate", "gate_bot")
|
||||
return (exchange_key or "").strip().lower() == "gate"
|
||||
|
||||
|
||||
def path_to_embed_tab(path: str) -> str | None:
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""关键位监控表结构迁移(四所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def ensure_key_monitor_schema(conn: Any) -> None:
|
||||
for sql in (
|
||||
"ALTER TABLE key_monitors ADD COLUMN last_mark_price REAL",
|
||||
):
|
||||
try:
|
||||
conn.execute(sql)
|
||||
except Exception:
|
||||
pass
|
||||
"""关键位监控表结构迁移(三所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def ensure_key_monitor_schema(conn: Any) -> None:
|
||||
for sql in (
|
||||
"ALTER TABLE key_monitors ADD COLUMN last_mark_price REAL",
|
||||
):
|
||||
try:
|
||||
conn.execute(sql)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""回调/突破触价开仓关键位监控:程序盯价、触达计划入场后市价成交(四所共用逻辑)。"""
|
||||
"""回调/突破触价开仓关键位监控:程序盯价、触达计划入场后市价成交(三所共用逻辑)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
@@ -37,6 +37,34 @@ KEY_ENTRY_REASON_CALLBACK = "关键位回调触价开仓"
|
||||
KEY_ENTRY_REASON_BREAKOUT = "关键位突破触价开仓"
|
||||
KEY_ENTRY_REASON_TRIGGER_LEGACY = "关键位触价开仓"
|
||||
|
||||
TRIGGER_ENTRY_IN_FLIGHT_OID = "__trigger_entry_in_flight__"
|
||||
|
||||
|
||||
def is_trigger_entry_in_flight_row(row: Any) -> bool:
|
||||
if row is None:
|
||||
return False
|
||||
try:
|
||||
v = row["fib_limit_order_id"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
v = getattr(row, "fib_limit_order_id", None)
|
||||
return (v or "").strip() == TRIGGER_ENTRY_IN_FLIGHT_OID
|
||||
|
||||
|
||||
def acquire_trigger_entry_exec_lock(conn: Any, monitor_id: int) -> bool:
|
||||
cur = conn.execute(
|
||||
"UPDATE key_monitors SET fib_limit_order_id=? WHERE id=? "
|
||||
"AND (fib_limit_order_id IS NULL OR fib_limit_order_id='')",
|
||||
(TRIGGER_ENTRY_IN_FLIGHT_OID, int(monitor_id)),
|
||||
)
|
||||
return int(cur.rowcount or 0) == 1
|
||||
|
||||
|
||||
def release_trigger_entry_exec_lock(conn: Any, monitor_id: int) -> None:
|
||||
conn.execute(
|
||||
"UPDATE key_monitors SET fib_limit_order_id=NULL WHERE id=? AND fib_limit_order_id=?",
|
||||
(int(monitor_id), TRIGGER_ENTRY_IN_FLIGHT_OID),
|
||||
)
|
||||
|
||||
|
||||
def normalize_trigger_entry_monitor_type(monitor_type: Optional[str]) -> str:
|
||||
mt = (monitor_type or "").strip()
|
||||
|
||||
@@ -1,230 +1,230 @@
|
||||
"""各交易所 app 模块 → strategy_register 配置(统一工厂)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
|
||||
def resolve_trading_app_module(app_module: Any = None) -> Any:
|
||||
"""
|
||||
须在 login_required 定义之后调用。
|
||||
PM2 / python app.py 时 __name__ 为 __main__,请传入 sys.modules[__name__]。
|
||||
"""
|
||||
if app_module is None:
|
||||
main = sys.modules.get("__main__")
|
||||
if main is not None and hasattr(main, "login_required"):
|
||||
m = main
|
||||
else:
|
||||
import inspect
|
||||
|
||||
m = None
|
||||
for fr in inspect.stack():
|
||||
g = fr.frame.f_globals
|
||||
if callable(g.get("login_required")) and callable(g.get("get_db")):
|
||||
m = g
|
||||
break
|
||||
if m is None:
|
||||
raise RuntimeError(
|
||||
"策略交易注册失败:请使用 install_strategy_trading(app, repo_root, app_module=sys.modules[__name__])"
|
||||
)
|
||||
else:
|
||||
m = app_module
|
||||
if not hasattr(m, "login_required"):
|
||||
raise RuntimeError(
|
||||
"策略交易注册须在 login_required 定义之后执行(将 install_strategy_trading 放在 app.py 末尾)"
|
||||
)
|
||||
return m
|
||||
|
||||
|
||||
def build_strategy_config(
|
||||
app_module: Any = None, *, trend_enabled: bool = False, trend_disabled_note: str = ""
|
||||
) -> dict:
|
||||
m = resolve_trading_app_module(app_module)
|
||||
|
||||
def get_trading_capital_usdt(conn):
|
||||
if hasattr(m, "get_exchange_capitals"):
|
||||
_, tc = m.get_exchange_capitals(force=True)
|
||||
if tc is not None:
|
||||
return float(tc)
|
||||
if hasattr(m, "get_available_trading_usdt"):
|
||||
snap = m.get_available_trading_usdt()
|
||||
if snap is not None:
|
||||
return float(snap)
|
||||
day = m.get_trading_day(m.app_now())
|
||||
row = m.ensure_session(conn, day)
|
||||
return float(row["current_capital"])
|
||||
|
||||
def get_position(ex_sym, direction):
|
||||
qty = m.get_live_position_contracts(ex_sym, direction)
|
||||
entry = None
|
||||
try:
|
||||
rows = m.exchange.fetch_positions([ex_sym])
|
||||
for p in rows or []:
|
||||
matcher = getattr(m, "_row_matches_monitor_direction", None)
|
||||
if matcher and not matcher(direction, p):
|
||||
continue
|
||||
contracts = getattr(m, "_position_row_effective_contracts", lambda x: abs(float(x.get("contracts") or 0)))(p)
|
||||
if contracts <= 0:
|
||||
continue
|
||||
coerce = getattr(m, "_coerce_float", None)
|
||||
if coerce:
|
||||
entry = coerce(
|
||||
p.get("entryPrice"),
|
||||
p.get("average"),
|
||||
(p.get("info") or {}).get("entryPrice"),
|
||||
)
|
||||
if entry:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return {"contracts": float(qty or 0), "entry_price": entry}
|
||||
|
||||
def amount_to_precision(ex_sym, amount):
|
||||
try:
|
||||
return float(m.exchange.amount_to_precision(ex_sym, float(amount)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def price_to_precision(ex_sym, price):
|
||||
try:
|
||||
return float(m.exchange.price_to_precision(ex_sym, float(price)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def market_add(ex_sym, direction, amount, leverage):
|
||||
return m.place_exchange_order(ex_sym, direction, amount, leverage, stop_loss=None, take_profit=None)
|
||||
|
||||
def limit_add(ex_sym, direction, amount, price, leverage):
|
||||
m.exchange.set_leverage(int(leverage), ex_sym)
|
||||
side = "buy" if direction == "long" else "sell"
|
||||
if hasattr(m, "build_okx_order_params"):
|
||||
params = m.build_okx_order_params(direction, reduce_only=False)
|
||||
elif hasattr(m, "build_binance_order_params"):
|
||||
params = m.build_binance_order_params(direction, reduce_only=False)
|
||||
elif hasattr(m, "build_gate_order_params"):
|
||||
params = m.build_gate_order_params(direction, reduce_only=False)
|
||||
else:
|
||||
params = {}
|
||||
return m.exchange.create_order(
|
||||
ex_sym, "limit", side, float(amount), float(price), params if params is not None else {}
|
||||
)
|
||||
|
||||
def replace_tpsl(ex_sym, direction, sl, tp, order_row):
|
||||
row = order_row or {"symbol": ex_sym, "exchange_symbol": ex_sym, "direction": direction}
|
||||
m.replace_active_monitor_tpsl_on_exchange(row, sl, tp)
|
||||
|
||||
def count_trends(conn):
|
||||
try:
|
||||
return int(
|
||||
conn.execute(
|
||||
"SELECT COUNT(*) FROM trend_pullback_plans WHERE status='active'"
|
||||
).fetchone()[0]
|
||||
)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def friendly_error(err):
|
||||
fn = getattr(m, "friendly_exchange_error", None) or getattr(
|
||||
m, "friendly_okx_error", None
|
||||
)
|
||||
if not callable(fn):
|
||||
return str(err)
|
||||
try:
|
||||
snap = m.get_available_trading_usdt()
|
||||
except Exception:
|
||||
snap = None
|
||||
try:
|
||||
return fn(err, available_usdt=snap)
|
||||
except TypeError:
|
||||
return fn(err)
|
||||
|
||||
def limit_order_status(ex_sym, order_id):
|
||||
fn = getattr(m, "fib_limit_order_status", None)
|
||||
if callable(fn):
|
||||
return fn(ex_sym, order_id)
|
||||
return "unknown"
|
||||
|
||||
def cancel_limit_order(ex_sym, order_id):
|
||||
fn = getattr(m, "cancel_fib_limit_order", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn(ex_sym, order_id)
|
||||
except Exception:
|
||||
pass
|
||||
if not order_id:
|
||||
return False
|
||||
try:
|
||||
m.exchange.cancel_order(str(order_id), ex_sym)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def get_mark_price(symbol):
|
||||
fn = getattr(m, "get_symbol_mark_price", None) or getattr(m, "get_price", None)
|
||||
if not callable(fn):
|
||||
return None
|
||||
try:
|
||||
return fn(symbol)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def wechat_account_label():
|
||||
fn = getattr(m, "_wechat_account_label", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn()
|
||||
except Exception:
|
||||
pass
|
||||
return getattr(m, "EXCHANGE_DISPLAY_NAME", "") or ""
|
||||
|
||||
def wechat_direction_text(direction):
|
||||
fn = getattr(m, "_wechat_direction_text", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn(direction)
|
||||
except Exception:
|
||||
pass
|
||||
d = (direction or "long").strip().lower()
|
||||
return "做多" if d == "long" else "做空"
|
||||
|
||||
def send_wechat(content):
|
||||
fn = getattr(m, "send_wechat_msg", None)
|
||||
if callable(fn):
|
||||
fn(content)
|
||||
|
||||
note = trend_disabled_note or (
|
||||
"趋势回调(自动补仓)请在 Gate 趋势机器人实例使用:/strategy/trend"
|
||||
)
|
||||
return {
|
||||
"app_module": m,
|
||||
"exchange_display": getattr(m, "EXCHANGE_DISPLAY_NAME", ""),
|
||||
"trend_enabled": trend_enabled,
|
||||
"trend_disabled_note": note,
|
||||
"login_required": m.login_required,
|
||||
"get_db": m.get_db,
|
||||
"normalize_symbol_input": m.normalize_symbol_input,
|
||||
"normalize_exchange_symbol": m.normalize_exchange_symbol,
|
||||
"get_price": m.get_price,
|
||||
"get_trading_capital_usdt": get_trading_capital_usdt,
|
||||
"get_position": get_position,
|
||||
"amount_to_precision": amount_to_precision,
|
||||
"price_to_precision": price_to_precision,
|
||||
"market_add": market_add,
|
||||
"limit_add": limit_add,
|
||||
"replace_tpsl": replace_tpsl,
|
||||
"ensure_live_ready": m.ensure_exchange_live_ready,
|
||||
"default_risk_percent": float(getattr(m, "RISK_PERCENT", 2)),
|
||||
"default_leverage": m.infer_leverage,
|
||||
"friendly_error": friendly_error,
|
||||
"app_now_str": m.app_now_str,
|
||||
"resolve_fill_price": m.resolve_order_entry_price,
|
||||
"price_fmt": m.format_price_for_symbol,
|
||||
"count_active_trend_plans": count_trends if trend_enabled else count_trends,
|
||||
"limit_order_status": limit_order_status,
|
||||
"cancel_limit_order": cancel_limit_order,
|
||||
"get_mark_price": get_mark_price,
|
||||
"send_wechat": send_wechat,
|
||||
"format_price": getattr(m, "format_price_for_symbol", None),
|
||||
"wechat_account_label": wechat_account_label,
|
||||
"wechat_direction_text": wechat_direction_text,
|
||||
}
|
||||
"""各交易所 app 模块 → strategy_register 配置(统一工厂)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
|
||||
def resolve_trading_app_module(app_module: Any = None) -> Any:
|
||||
"""
|
||||
须在 login_required 定义之后调用。
|
||||
PM2 / python app.py 时 __name__ 为 __main__,请传入 sys.modules[__name__]。
|
||||
"""
|
||||
if app_module is None:
|
||||
main = sys.modules.get("__main__")
|
||||
if main is not None and hasattr(main, "login_required"):
|
||||
m = main
|
||||
else:
|
||||
import inspect
|
||||
|
||||
m = None
|
||||
for fr in inspect.stack():
|
||||
g = fr.frame.f_globals
|
||||
if callable(g.get("login_required")) and callable(g.get("get_db")):
|
||||
m = g
|
||||
break
|
||||
if m is None:
|
||||
raise RuntimeError(
|
||||
"策略交易注册失败:请使用 install_strategy_trading(app, repo_root, app_module=sys.modules[__name__])"
|
||||
)
|
||||
else:
|
||||
m = app_module
|
||||
if not hasattr(m, "login_required"):
|
||||
raise RuntimeError(
|
||||
"策略交易注册须在 login_required 定义之后执行(将 install_strategy_trading 放在 app.py 末尾)"
|
||||
)
|
||||
return m
|
||||
|
||||
|
||||
def build_strategy_config(
|
||||
app_module: Any = None, *, trend_enabled: bool = False, trend_disabled_note: str = ""
|
||||
) -> dict:
|
||||
m = resolve_trading_app_module(app_module)
|
||||
|
||||
def get_trading_capital_usdt(conn):
|
||||
if hasattr(m, "get_exchange_capitals"):
|
||||
_, tc = m.get_exchange_capitals(force=True)
|
||||
if tc is not None:
|
||||
return float(tc)
|
||||
if hasattr(m, "get_available_trading_usdt"):
|
||||
snap = m.get_available_trading_usdt()
|
||||
if snap is not None:
|
||||
return float(snap)
|
||||
day = m.get_trading_day(m.app_now())
|
||||
row = m.ensure_session(conn, day)
|
||||
return float(row["current_capital"])
|
||||
|
||||
def get_position(ex_sym, direction):
|
||||
qty = m.get_live_position_contracts(ex_sym, direction)
|
||||
entry = None
|
||||
try:
|
||||
rows = m.exchange.fetch_positions([ex_sym])
|
||||
for p in rows or []:
|
||||
matcher = getattr(m, "_row_matches_monitor_direction", None)
|
||||
if matcher and not matcher(direction, p):
|
||||
continue
|
||||
contracts = getattr(m, "_position_row_effective_contracts", lambda x: abs(float(x.get("contracts") or 0)))(p)
|
||||
if contracts <= 0:
|
||||
continue
|
||||
coerce = getattr(m, "_coerce_float", None)
|
||||
if coerce:
|
||||
entry = coerce(
|
||||
p.get("entryPrice"),
|
||||
p.get("average"),
|
||||
(p.get("info") or {}).get("entryPrice"),
|
||||
)
|
||||
if entry:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return {"contracts": float(qty or 0), "entry_price": entry}
|
||||
|
||||
def amount_to_precision(ex_sym, amount):
|
||||
try:
|
||||
return float(m.exchange.amount_to_precision(ex_sym, float(amount)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def price_to_precision(ex_sym, price):
|
||||
try:
|
||||
return float(m.exchange.price_to_precision(ex_sym, float(price)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def market_add(ex_sym, direction, amount, leverage):
|
||||
return m.place_exchange_order(ex_sym, direction, amount, leverage, stop_loss=None, take_profit=None)
|
||||
|
||||
def limit_add(ex_sym, direction, amount, price, leverage):
|
||||
m.exchange.set_leverage(int(leverage), ex_sym)
|
||||
side = "buy" if direction == "long" else "sell"
|
||||
if hasattr(m, "build_okx_order_params"):
|
||||
params = m.build_okx_order_params(direction, reduce_only=False)
|
||||
elif hasattr(m, "build_binance_order_params"):
|
||||
params = m.build_binance_order_params(direction, reduce_only=False)
|
||||
elif hasattr(m, "build_gate_order_params"):
|
||||
params = m.build_gate_order_params(direction, reduce_only=False)
|
||||
else:
|
||||
params = {}
|
||||
return m.exchange.create_order(
|
||||
ex_sym, "limit", side, float(amount), float(price), params if params is not None else {}
|
||||
)
|
||||
|
||||
def replace_tpsl(ex_sym, direction, sl, tp, order_row):
|
||||
row = order_row or {"symbol": ex_sym, "exchange_symbol": ex_sym, "direction": direction}
|
||||
m.replace_active_monitor_tpsl_on_exchange(row, sl, tp)
|
||||
|
||||
def count_trends(conn):
|
||||
try:
|
||||
return int(
|
||||
conn.execute(
|
||||
"SELECT COUNT(*) FROM trend_pullback_plans WHERE status='active'"
|
||||
).fetchone()[0]
|
||||
)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def friendly_error(err):
|
||||
fn = getattr(m, "friendly_exchange_error", None) or getattr(
|
||||
m, "friendly_okx_error", None
|
||||
)
|
||||
if not callable(fn):
|
||||
return str(err)
|
||||
try:
|
||||
snap = m.get_available_trading_usdt()
|
||||
except Exception:
|
||||
snap = None
|
||||
try:
|
||||
return fn(err, available_usdt=snap)
|
||||
except TypeError:
|
||||
return fn(err)
|
||||
|
||||
def limit_order_status(ex_sym, order_id):
|
||||
fn = getattr(m, "fib_limit_order_status", None)
|
||||
if callable(fn):
|
||||
return fn(ex_sym, order_id)
|
||||
return "unknown"
|
||||
|
||||
def cancel_limit_order(ex_sym, order_id):
|
||||
fn = getattr(m, "cancel_fib_limit_order", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn(ex_sym, order_id)
|
||||
except Exception:
|
||||
pass
|
||||
if not order_id:
|
||||
return False
|
||||
try:
|
||||
m.exchange.cancel_order(str(order_id), ex_sym)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def get_mark_price(symbol):
|
||||
fn = getattr(m, "get_symbol_mark_price", None) or getattr(m, "get_price", None)
|
||||
if not callable(fn):
|
||||
return None
|
||||
try:
|
||||
return fn(symbol)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def wechat_account_label():
|
||||
fn = getattr(m, "_wechat_account_label", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn()
|
||||
except Exception:
|
||||
pass
|
||||
return getattr(m, "EXCHANGE_DISPLAY_NAME", "") or ""
|
||||
|
||||
def wechat_direction_text(direction):
|
||||
fn = getattr(m, "_wechat_direction_text", None)
|
||||
if callable(fn):
|
||||
try:
|
||||
return fn(direction)
|
||||
except Exception:
|
||||
pass
|
||||
d = (direction or "long").strip().lower()
|
||||
return "做多" if d == "long" else "做空"
|
||||
|
||||
def send_wechat(content):
|
||||
fn = getattr(m, "send_wechat_msg", None)
|
||||
if callable(fn):
|
||||
fn(content)
|
||||
|
||||
note = trend_disabled_note or (
|
||||
"趋势回调(自动补仓)请在 Gate机器人实例使用:/strategy/trend"
|
||||
)
|
||||
return {
|
||||
"app_module": m,
|
||||
"exchange_display": getattr(m, "EXCHANGE_DISPLAY_NAME", ""),
|
||||
"trend_enabled": trend_enabled,
|
||||
"trend_disabled_note": note,
|
||||
"login_required": m.login_required,
|
||||
"get_db": m.get_db,
|
||||
"normalize_symbol_input": m.normalize_symbol_input,
|
||||
"normalize_exchange_symbol": m.normalize_exchange_symbol,
|
||||
"get_price": m.get_price,
|
||||
"get_trading_capital_usdt": get_trading_capital_usdt,
|
||||
"get_position": get_position,
|
||||
"amount_to_precision": amount_to_precision,
|
||||
"price_to_precision": price_to_precision,
|
||||
"market_add": market_add,
|
||||
"limit_add": limit_add,
|
||||
"replace_tpsl": replace_tpsl,
|
||||
"ensure_live_ready": m.ensure_exchange_live_ready,
|
||||
"default_risk_percent": float(getattr(m, "RISK_PERCENT", 2)),
|
||||
"default_leverage": m.infer_leverage,
|
||||
"friendly_error": friendly_error,
|
||||
"app_now_str": m.app_now_str,
|
||||
"resolve_fill_price": m.resolve_order_entry_price,
|
||||
"price_fmt": m.format_price_for_symbol,
|
||||
"count_active_trend_plans": count_trends if trend_enabled else count_trends,
|
||||
"limit_order_status": limit_order_status,
|
||||
"cancel_limit_order": cancel_limit_order,
|
||||
"get_mark_price": get_mark_price,
|
||||
"send_wechat": send_wechat,
|
||||
"format_price": getattr(m, "format_price_for_symbol", None),
|
||||
"wechat_account_label": wechat_account_label,
|
||||
"wechat_direction_text": wechat_direction_text,
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Gate.io USDT 永续 — 策略交易交易所侧能力。
|
||||
|
||||
实现方式:各 Gate 实例 app 通过 strategy_config.build_strategy_config(app_module) 注入
|
||||
ccxt 下单、精度、换 TP/SL;本文件为文档与类型锚点,避免在四个 app 重复实现滚仓公式。
|
||||
ccxt 下单、精度、换 TP/SL;本文件为文档与类型锚点,避免在各 app 重复实现滚仓公式。
|
||||
"""
|
||||
from lib.strategy.strategy_exchange_base import StrategyExchangeAdapter
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""策略交易记录页:已结束趋势 / 顺势加仓快照(四所统一)。"""
|
||||
"""策略交易记录页:已结束趋势 / 顺势加仓快照(三所统一)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
@@ -40,7 +40,8 @@ def check_roll_monitors(cfg: dict[str, Any]) -> None:
|
||||
_reconcile_roll_groups(conn, cfg)
|
||||
_check_pending_roll_legs(conn, cfg)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
print(f"[roll_monitor] {e}", flush=True)
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
@@ -408,7 +409,19 @@ def _execute_pending_roll_leg(
|
||||
return
|
||||
|
||||
oid = str(order.get("id") or "") if isinstance(order, dict) else ""
|
||||
cfg["replace_tpsl"](ex_sym, direction, sl, tp0, mon)
|
||||
try:
|
||||
cfg["replace_tpsl"](ex_sym, direction, sl, tp0, mon)
|
||||
except Exception as tpsl_err:
|
||||
fe = cfg.get("friendly_error")
|
||||
msg = fe(tpsl_err) if callable(fe) else str(tpsl_err)
|
||||
conn.execute(
|
||||
"""UPDATE roll_legs SET status='error', exchange_order_id=?, fill_price=?, amount=?
|
||||
WHERE id=? AND status='pending'""",
|
||||
(oid, fill, float(amount), leg_id),
|
||||
)
|
||||
_notify_roll_fail(cfg, group, leg, mark, f"加仓成交但止盈止损更新失败: {msg}")
|
||||
return
|
||||
|
||||
conn.execute(
|
||||
"""UPDATE roll_legs SET status='filled', fill_price=?, amount=?, exchange_order_id=?,
|
||||
new_stop_loss=? WHERE id=? AND status='pending'""",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""策略结束快照:趋势回调 / 顺势加仓(四所共用)。"""
|
||||
"""策略结束快照:趋势回调 / 顺势加仓(三所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
@@ -230,7 +230,7 @@ def compute_trend_plan_core(
|
||||
def calc_planned_reward_risk_ratio(
|
||||
direction: str, entry_price: float, stop_loss: float, take_profit: float
|
||||
) -> Optional[float]:
|
||||
"""盈亏比(reward/risk),与四所 calc_rr_ratio 口径一致。"""
|
||||
"""盈亏比(reward/risk),与三所 calc_rr_ratio 口径一致。"""
|
||||
try:
|
||||
entry = float(entry_price)
|
||||
sl = float(stop_loss)
|
||||
@@ -375,7 +375,7 @@ def trend_leg_grid_price(plan: dict, leg_idx: int) -> Optional[float]:
|
||||
|
||||
def trend_leg_display_price(plan: dict, leg_idx: int) -> Optional[float]:
|
||||
"""
|
||||
四所统一:单档展示价 = leg_fill_prices_json 实际记录,否则计划网格(首仓用均价/参考价)。
|
||||
三所统一:单档展示价 = leg_fill_prices_json 实际记录,否则计划网格(首仓用均价/参考价)。
|
||||
禁止为凑均价反推虚构成交价。
|
||||
"""
|
||||
p = plan or {}
|
||||
@@ -398,7 +398,7 @@ def trend_leg_display_price(plan: dict, leg_idx: int) -> Optional[float]:
|
||||
|
||||
|
||||
def reconcile_trend_leg_fill_prices(plan: dict) -> list[float]:
|
||||
"""首仓(0)+已补仓(1..legs_done) 展示价列表(四所共用 trend_leg_display_price)。"""
|
||||
"""首仓(0)+已补仓(1..legs_done) 展示价列表(三所共用 trend_leg_display_price)。"""
|
||||
p = plan or {}
|
||||
if int(p.get("first_order_done") or 0) == 0:
|
||||
return []
|
||||
@@ -563,7 +563,7 @@ def build_trend_preview_level_rows(preview: dict) -> tuple[dict, list[dict]]:
|
||||
|
||||
def enrich_trend_dca_levels_with_tp(plan: dict, levels: list[dict]) -> list[dict]:
|
||||
"""
|
||||
四所统一补仓表 enrich(实例策略页 + 中控 monitor 共用)。
|
||||
三所统一补仓表 enrich(实例策略页 + 中控 monitor 共用)。
|
||||
触发价:实际成交价或计划网格;末档加仓后均价用持仓均价;禁止反推虚构成交价。
|
||||
"""
|
||||
if not levels:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""趋势回调:路由、轮询、页面数据(四所共用,依赖各 app 模块交易所能力)。"""
|
||||
"""趋势回调:路由、轮询、页面数据(三所共用,依赖各 app 模块交易所能力)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
@@ -138,8 +138,8 @@ def summarize_trend_dca_probe(cfg: dict, row) -> dict:
|
||||
out["block_reason"] = "交易所无持仓"
|
||||
else:
|
||||
out["block_reason"] = (
|
||||
"标记价已触达,轮询应自动下单;若仍未补请确认 PM2 进程 crypto_gate_bot "
|
||||
"(非 manual-agent-gate-bot)在运行,并查看 pm2 logs crypto_gate_bot"
|
||||
"标记价已触达,轮询应自动下单;若仍未补请确认 PM2 进程 crypto_gate "
|
||||
"(或对应所 Flask 进程)在运行,并查看 pm2 logs"
|
||||
)
|
||||
elif not reached:
|
||||
out["block_reason"] = f"标记价 {pf} 未触达下一档 {level}"
|
||||
@@ -244,7 +244,7 @@ def _row(cfg, row) -> dict:
|
||||
return cfg["row_to_dict"](row)
|
||||
|
||||
|
||||
def precheck_trend_start(cfg: dict, conn) -> tuple[bool, str]:
|
||||
def precheck_trend_start(cfg: dict, conn, *, symbol: str = "", direction: str = "long") -> tuple[bool, str]:
|
||||
m = _m(cfg)
|
||||
mode = getattr(m, "POSITION_SIZING_MODE", None) or "risk"
|
||||
try:
|
||||
@@ -255,9 +255,41 @@ def precheck_trend_start(cfg: dict, conn) -> tuple[bool, str]:
|
||||
return False, src_msg
|
||||
except Exception:
|
||||
pass
|
||||
now = m.app_now()
|
||||
if not m.trading_day_reset_allows_new_open(now):
|
||||
return False, f"北京时间 {cfg['reset_hour']}:00 前不允许持仓"
|
||||
sym = (symbol or "").strip()
|
||||
dir_l = (direction or "long").strip().lower()
|
||||
if sym and dir_l in ("long", "short") and hasattr(m, "precheck_risk"):
|
||||
ok_risk, risk_msg = m.precheck_risk(conn, sym, dir_l)
|
||||
if not ok_risk:
|
||||
return False, risk_msg
|
||||
else:
|
||||
now = m.app_now()
|
||||
if not m.trading_day_reset_allows_new_open(now):
|
||||
return False, f"北京时间 {cfg['reset_hour']}:00 前不允许持仓"
|
||||
from lib.trade.account_risk_lib import account_risk_blocks_trading, position_limit_reached
|
||||
|
||||
ok_risk, risk_reason = account_risk_blocks_trading(
|
||||
conn,
|
||||
trading_day=m.get_trading_day(now),
|
||||
now=now,
|
||||
fmt_local_ms=getattr(m, "ms_to_app_local_str", lambda _x: ""),
|
||||
)
|
||||
if not ok_risk:
|
||||
return False, risk_reason
|
||||
reached, active_count, mx = position_limit_reached(
|
||||
conn, max_active_positions=cfg["max_active_positions"]
|
||||
)
|
||||
if reached:
|
||||
return False, f"已达最大持仓数({active_count}/{mx})"
|
||||
from lib.trade.daily_open_limit_lib import check_daily_open_hard_limit
|
||||
|
||||
ok_daily, daily_reason, _opens = check_daily_open_hard_limit(
|
||||
conn,
|
||||
m.get_trading_day(now),
|
||||
getattr(m, "DAILY_OPEN_HARD_LIMIT", 0),
|
||||
cfg["reset_hour"],
|
||||
)
|
||||
if not ok_daily:
|
||||
return False, daily_reason
|
||||
active = m.get_active_position_count(conn)
|
||||
if active >= cfg["max_active_positions"]:
|
||||
return (
|
||||
@@ -520,7 +552,7 @@ def _patch_hub_trend_views(app: Flask) -> None:
|
||||
|
||||
|
||||
def patch_trend_hub_enrich(app: Flask, cfg: dict) -> None:
|
||||
"""hub_bridge install 之后调用:四所 /api/hub/monitor 趋势字段与策略页一致。"""
|
||||
"""hub_bridge install 之后调用:三所 /api/hub/monitor 趋势字段与策略页一致。"""
|
||||
_patch_hub_monitor_enrich(app, cfg)
|
||||
|
||||
|
||||
@@ -1604,22 +1636,27 @@ def register_trend_routes(app: Flask, cfg: dict) -> None:
|
||||
def preview_trend_pullback():
|
||||
conn = get_db()
|
||||
init_strategy_tables(conn)
|
||||
okp, msg = precheck_trend_start(cfg, conn)
|
||||
if not okp:
|
||||
conn.close()
|
||||
flash(msg)
|
||||
return _redirect_trend()
|
||||
m = _m(cfg)
|
||||
ok_live, reason = m.ensure_exchange_live_ready()
|
||||
if not ok_live:
|
||||
conn.close()
|
||||
flash(reason)
|
||||
return _redirect_trend()
|
||||
payload, err = parse_trend_plan(cfg, request.form)
|
||||
if err:
|
||||
conn.close()
|
||||
flash(err)
|
||||
return _redirect_trend()
|
||||
okp, msg = precheck_trend_start(
|
||||
cfg,
|
||||
conn,
|
||||
symbol=str(payload.get("symbol") or ""),
|
||||
direction=str(payload.get("direction") or "long"),
|
||||
)
|
||||
if not okp:
|
||||
conn.close()
|
||||
flash(msg)
|
||||
return _redirect_trend()
|
||||
ok_live, reason = m.ensure_exchange_live_ready()
|
||||
if not ok_live:
|
||||
conn.close()
|
||||
flash(reason)
|
||||
return _redirect_trend()
|
||||
pid = str(uuid.uuid4())
|
||||
exp_ms = int(time.time() * 1000) + cfg["preview_ttl"] * 1000
|
||||
created = m.app_now_str()
|
||||
@@ -1678,7 +1715,12 @@ def register_trend_routes(app: Flask, cfg: dict) -> None:
|
||||
conn.close()
|
||||
flash("预览已过期或不存在,请重新生成预览")
|
||||
return _redirect_trend()
|
||||
okp, msg = precheck_trend_start(cfg, conn)
|
||||
okp, msg = precheck_trend_start(
|
||||
cfg,
|
||||
conn,
|
||||
symbol=str(pr["symbol"] or ""),
|
||||
direction=str(pr["direction"] or "long"),
|
||||
)
|
||||
if not okp:
|
||||
conn.close()
|
||||
flash(msg)
|
||||
@@ -1718,7 +1760,18 @@ def register_trend_routes(app: Flask, cfg: dict) -> None:
|
||||
exchange_symbol, direction, first_amt, leverage, stop_loss=None, take_profit=None
|
||||
)
|
||||
fill1 = m.resolve_order_entry_price(o1, exchange_symbol, live_price)
|
||||
trend_refresh_stop_only(cfg, exchange_symbol, direction, stop_loss)
|
||||
try:
|
||||
trend_refresh_stop_only(cfg, exchange_symbol, direction, stop_loss)
|
||||
except Exception as sl_err:
|
||||
from lib.strategy.strategy_trend_exchange import cancel_symbol_orders, trend_market_close
|
||||
|
||||
try:
|
||||
pos_qty = m.get_live_position_contracts(exchange_symbol, direction) or first_amt
|
||||
trend_market_close(cfg, exchange_symbol, direction, float(pos_qty), leverage)
|
||||
cancel_symbol_orders(cfg, exchange_symbol)
|
||||
except Exception as close_err:
|
||||
print(f"[trend_start] compensating close failed: {close_err}", flush=True)
|
||||
raise sl_err
|
||||
except Exception as e:
|
||||
conn.close()
|
||||
fe = getattr(m, "friendly_exchange_error", lambda x, **k: str(x))
|
||||
|
||||
@@ -77,9 +77,8 @@ def fetch_roll_page_data(
|
||||
|
||||
|
||||
DEFAULT_TREND_DISABLED_NOTE = (
|
||||
"趋势回调(预览、自动补仓、程序止盈)仅在 Gate 趋势机器人实例 "
|
||||
"(crypto_monitor_gate_bot,常见端口 5002)中启用。"
|
||||
"币安 / Gate 主站 / OKX 可使用本页「顺势加仓」;完整趋势回调请打开该实例。"
|
||||
"趋势回调(预览、自动补仓、程序止盈)须在本实例 .env 设置 "
|
||||
"`LIVE_TRADING_ENABLED=true` 并重启对应 PM2 进程(如 crypto_gate / crypto_okx / crypto_binance)。"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""策略计划(趋势回调 / 滚仓)开始与结束 — 企业微信推送(四所共用)。"""
|
||||
"""策略计划(趋势回调 / 滚仓)开始与结束 — 企业微信推送(三所共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<div class="box">
|
||||
<h1>趋势回调</h1>
|
||||
<p>{{ trend_note }}</p>
|
||||
<p style="color:#8892b0;font-size:.9rem">趋势回调含自动补仓档位,仅在 Gate 趋势机器人(crypto_monitor_gate_bot)实例中运行。</p>
|
||||
<p style="color:#8892b0;font-size:.9rem">趋势回调含自动补仓档位,在三所实例(Binance / Gate / OKX)中均可启用,须配置 LIVE_TRADING_ENABLED=true。</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<summary class="tip-collapse-summary">趋势回调说明(本实例未启用)</summary>
|
||||
<div class="tip-collapse-body rule-tip">
|
||||
{{ trend_disabled_note }}<br><br>
|
||||
趋势回调含自动补仓档位与预览执行,仅在 <strong>Gate 趋势机器人</strong>(<code>crypto_monitor_gate_bot</code>)实例中运行。
|
||||
请访问该实例同一菜单「策略交易 → 趋势回调」,或常用地址 <code>:5002/strategy/trend</code>。
|
||||
趋势回调含自动补仓档位与预览执行,在 <strong>Binance / Gate / OKX</strong> 各实例的「策略交易 → 趋势回调」中运行。
|
||||
请访问对应实例同一菜单,或常用地址如 Gate <code>:5000/strategy/trend</code>。
|
||||
</div>
|
||||
</details>
|
||||
<p style="margin-top:12px;font-size:.85rem">
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<strong>计划 #{{ p.plan_id }}</strong> 标记价 {{ p.mark_price }} 已触达补仓触发价 {{ p.next_trigger }},但未自动补仓:
|
||||
{{ p.block_reason }}。
|
||||
{% if not live_trading_enabled %}
|
||||
请在 <code>crypto_monitor_gate_bot/.env</code> 设置 <code>LIVE_TRADING_ENABLED=true</code> 后重启 PM2 进程 <strong>crypto_gate_bot</strong>(不是 manual-agent-gate-bot)。
|
||||
请在当前实例 <code>.env</code> 设置 <code>LIVE_TRADING_ENABLED=true</code> 后重启对应 PM2 进程(如 <strong>crypto_gate</strong>、<strong>crypto_okx</strong>、<strong>crypto_binance</strong>)。
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""账户冷静期 / 日冻结风控(四所实例共用)。"""
|
||||
"""账户冷静期 / 日冻结风控(三所实例共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""开仓后挂 TP/SL 失败时的补偿平仓(避免裸仓)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable
|
||||
|
||||
|
||||
def log_compensating_close_error(prefix: str, exc: BaseException) -> None:
|
||||
print(f"[{prefix}] {exc}", flush=True)
|
||||
|
||||
|
||||
def run_compensating_close(close_fn: Callable[[], None], *, log_prefix: str = "compensating_close") -> None:
|
||||
"""执行补偿平仓;二次失败只打日志,不掩盖原始异常。"""
|
||||
try:
|
||||
close_fn()
|
||||
except Exception as e:
|
||||
log_compensating_close_error(log_prefix, e)
|
||||
@@ -1,140 +1,140 @@
|
||||
"""单日开仓次数:软提醒阈值 + 硬上限(四所实例共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def parse_daily_open_alert_threshold(raw: Any = None, *, default: int = 5) -> int:
|
||||
"""AI 克制提醒阈值;至少 1。"""
|
||||
try:
|
||||
v = int(raw if raw is not None and str(raw).strip() != "" else default)
|
||||
except (TypeError, ValueError):
|
||||
v = default
|
||||
return max(1, v)
|
||||
|
||||
|
||||
def parse_daily_open_hard_limit(raw: Any = None, *, default: int = 0) -> int:
|
||||
"""硬上限;0 表示不启用。至少 0。"""
|
||||
try:
|
||||
v = int(raw if raw is not None and str(raw).strip() != "" else default)
|
||||
except (TypeError, ValueError):
|
||||
v = default
|
||||
return max(0, v)
|
||||
|
||||
|
||||
def load_daily_open_limits_from_env(
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> tuple[int, int]:
|
||||
"""从环境变量读取 (alert_threshold, hard_limit)。"""
|
||||
src = env if env is not None else os.environ
|
||||
alert = parse_daily_open_alert_threshold(src.get("DAILY_OPEN_ALERT_THRESHOLD"))
|
||||
hard = parse_daily_open_hard_limit(src.get("DAILY_OPEN_HARD_LIMIT"))
|
||||
return alert, hard
|
||||
|
||||
|
||||
def count_opens_for_trading_day(conn, trading_day: str) -> int:
|
||||
"""本交易日已成功写入 order_monitors 的开仓次数。"""
|
||||
td = (trading_day or "").strip()
|
||||
if not td:
|
||||
return 0
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) FROM order_monitors WHERE session_date=?",
|
||||
(td,),
|
||||
).fetchone()
|
||||
return int(row[0] if row else 0)
|
||||
|
||||
|
||||
def daily_open_hard_limit_blocks(opens_today: int, hard_limit: int) -> bool:
|
||||
return int(hard_limit) > 0 and int(opens_today) >= int(hard_limit)
|
||||
|
||||
|
||||
def hard_limit_block_reason(opens_today: int, hard_limit: int, reset_hour: int) -> str:
|
||||
return (
|
||||
f"本交易日开仓次数已达上限({int(opens_today)}/{int(hard_limit)}),"
|
||||
f"次日北京时间 {int(reset_hour)}:00 后恢复"
|
||||
)
|
||||
|
||||
|
||||
def check_daily_open_hard_limit(
|
||||
conn,
|
||||
trading_day: str,
|
||||
hard_limit: int,
|
||||
reset_hour: int,
|
||||
) -> tuple[bool, str, int]:
|
||||
"""返回 (允许继续开仓, 拒绝原因, 当日已开次数)。"""
|
||||
opens_today = count_opens_for_trading_day(conn, trading_day)
|
||||
if daily_open_hard_limit_blocks(opens_today, hard_limit):
|
||||
return False, hard_limit_block_reason(opens_today, hard_limit, reset_hour), opens_today
|
||||
return True, "", opens_today
|
||||
|
||||
|
||||
def can_trade_new_open(
|
||||
*,
|
||||
time_allows: bool,
|
||||
active_count: int,
|
||||
max_active_positions: int,
|
||||
opens_today: int,
|
||||
hard_limit: int,
|
||||
extra_blocks: bool = False,
|
||||
) -> bool:
|
||||
if extra_blocks:
|
||||
return False
|
||||
if not time_allows:
|
||||
return False
|
||||
if int(active_count) >= int(max_active_positions):
|
||||
return False
|
||||
if daily_open_hard_limit_blocks(opens_today, hard_limit):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def should_send_daily_open_alert(before: int, after: int, alert_threshold: int) -> bool:
|
||||
return int(before) < int(alert_threshold) <= int(after)
|
||||
|
||||
|
||||
def build_daily_open_alert_prompt(
|
||||
trading_day: str,
|
||||
opens_after: int,
|
||||
alert_threshold: int,
|
||||
*,
|
||||
hard_limit: int = 0,
|
||||
detail_line: str = "",
|
||||
) -> str:
|
||||
hard_txt = (
|
||||
f"硬上限 {hard_limit} 次(已达后将禁止新开仓直至下一交易日)。"
|
||||
if int(hard_limit) > 0
|
||||
else "未配置单日硬上限。"
|
||||
)
|
||||
extra = f" {detail_line}" if detail_line else ""
|
||||
return (
|
||||
f"用户在北京时间交易日 {trading_day} 已累计开仓 {opens_after} 次"
|
||||
f"(AI 提醒阈值 {alert_threshold};{hard_txt})"
|
||||
f"{extra}"
|
||||
f"用户自述“上头了”。请给克制提醒。"
|
||||
)
|
||||
|
||||
|
||||
def format_daily_open_counter_line(
|
||||
opens_today: int,
|
||||
alert_threshold: int,
|
||||
hard_limit: int,
|
||||
) -> str:
|
||||
if int(hard_limit) > 0:
|
||||
return (
|
||||
f"📅 当日开仓次数:{int(opens_today)} / 硬上限 {int(hard_limit)} 次"
|
||||
f"(AI 提醒阈值 {int(alert_threshold)})"
|
||||
)
|
||||
return (
|
||||
f"📅 当日开仓次数:{int(opens_today)} / AI 提醒阈值 {int(alert_threshold)} 次"
|
||||
)
|
||||
|
||||
|
||||
def format_daily_open_summary_short(
|
||||
opens_today: int,
|
||||
alert_threshold: int,
|
||||
hard_limit: int,
|
||||
) -> str:
|
||||
if int(hard_limit) > 0:
|
||||
return f"本交易日累计开仓:{int(opens_today)}(硬上限 {int(hard_limit)},提醒 {int(alert_threshold)})"
|
||||
return f"本交易日累计开仓:{int(opens_today)}(提醒阈值 {int(alert_threshold)})"
|
||||
"""单日开仓次数:软提醒阈值 + 硬上限(三所实例共用)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def parse_daily_open_alert_threshold(raw: Any = None, *, default: int = 5) -> int:
|
||||
"""AI 克制提醒阈值;至少 1。"""
|
||||
try:
|
||||
v = int(raw if raw is not None and str(raw).strip() != "" else default)
|
||||
except (TypeError, ValueError):
|
||||
v = default
|
||||
return max(1, v)
|
||||
|
||||
|
||||
def parse_daily_open_hard_limit(raw: Any = None, *, default: int = 0) -> int:
|
||||
"""硬上限;0 表示不启用。至少 0。"""
|
||||
try:
|
||||
v = int(raw if raw is not None and str(raw).strip() != "" else default)
|
||||
except (TypeError, ValueError):
|
||||
v = default
|
||||
return max(0, v)
|
||||
|
||||
|
||||
def load_daily_open_limits_from_env(
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> tuple[int, int]:
|
||||
"""从环境变量读取 (alert_threshold, hard_limit)。"""
|
||||
src = env if env is not None else os.environ
|
||||
alert = parse_daily_open_alert_threshold(src.get("DAILY_OPEN_ALERT_THRESHOLD"))
|
||||
hard = parse_daily_open_hard_limit(src.get("DAILY_OPEN_HARD_LIMIT"))
|
||||
return alert, hard
|
||||
|
||||
|
||||
def count_opens_for_trading_day(conn, trading_day: str) -> int:
|
||||
"""本交易日已成功写入 order_monitors 的开仓次数。"""
|
||||
td = (trading_day or "").strip()
|
||||
if not td:
|
||||
return 0
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) FROM order_monitors WHERE session_date=?",
|
||||
(td,),
|
||||
).fetchone()
|
||||
return int(row[0] if row else 0)
|
||||
|
||||
|
||||
def daily_open_hard_limit_blocks(opens_today: int, hard_limit: int) -> bool:
|
||||
return int(hard_limit) > 0 and int(opens_today) >= int(hard_limit)
|
||||
|
||||
|
||||
def hard_limit_block_reason(opens_today: int, hard_limit: int, reset_hour: int) -> str:
|
||||
return (
|
||||
f"本交易日开仓次数已达上限({int(opens_today)}/{int(hard_limit)}),"
|
||||
f"次日北京时间 {int(reset_hour)}:00 后恢复"
|
||||
)
|
||||
|
||||
|
||||
def check_daily_open_hard_limit(
|
||||
conn,
|
||||
trading_day: str,
|
||||
hard_limit: int,
|
||||
reset_hour: int,
|
||||
) -> tuple[bool, str, int]:
|
||||
"""返回 (允许继续开仓, 拒绝原因, 当日已开次数)。"""
|
||||
opens_today = count_opens_for_trading_day(conn, trading_day)
|
||||
if daily_open_hard_limit_blocks(opens_today, hard_limit):
|
||||
return False, hard_limit_block_reason(opens_today, hard_limit, reset_hour), opens_today
|
||||
return True, "", opens_today
|
||||
|
||||
|
||||
def can_trade_new_open(
|
||||
*,
|
||||
time_allows: bool,
|
||||
active_count: int,
|
||||
max_active_positions: int,
|
||||
opens_today: int,
|
||||
hard_limit: int,
|
||||
extra_blocks: bool = False,
|
||||
) -> bool:
|
||||
if extra_blocks:
|
||||
return False
|
||||
if not time_allows:
|
||||
return False
|
||||
if int(active_count) >= int(max_active_positions):
|
||||
return False
|
||||
if daily_open_hard_limit_blocks(opens_today, hard_limit):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def should_send_daily_open_alert(before: int, after: int, alert_threshold: int) -> bool:
|
||||
return int(before) < int(alert_threshold) <= int(after)
|
||||
|
||||
|
||||
def build_daily_open_alert_prompt(
|
||||
trading_day: str,
|
||||
opens_after: int,
|
||||
alert_threshold: int,
|
||||
*,
|
||||
hard_limit: int = 0,
|
||||
detail_line: str = "",
|
||||
) -> str:
|
||||
hard_txt = (
|
||||
f"硬上限 {hard_limit} 次(已达后将禁止新开仓直至下一交易日)。"
|
||||
if int(hard_limit) > 0
|
||||
else "未配置单日硬上限。"
|
||||
)
|
||||
extra = f" {detail_line}" if detail_line else ""
|
||||
return (
|
||||
f"用户在北京时间交易日 {trading_day} 已累计开仓 {opens_after} 次"
|
||||
f"(AI 提醒阈值 {alert_threshold};{hard_txt})"
|
||||
f"{extra}"
|
||||
f"用户自述“上头了”。请给克制提醒。"
|
||||
)
|
||||
|
||||
|
||||
def format_daily_open_counter_line(
|
||||
opens_today: int,
|
||||
alert_threshold: int,
|
||||
hard_limit: int,
|
||||
) -> str:
|
||||
if int(hard_limit) > 0:
|
||||
return (
|
||||
f"📅 当日开仓次数:{int(opens_today)} / 硬上限 {int(hard_limit)} 次"
|
||||
f"(AI 提醒阈值 {int(alert_threshold)})"
|
||||
)
|
||||
return (
|
||||
f"📅 当日开仓次数:{int(opens_today)} / AI 提醒阈值 {int(alert_threshold)} 次"
|
||||
)
|
||||
|
||||
|
||||
def format_daily_open_summary_short(
|
||||
opens_today: int,
|
||||
alert_threshold: int,
|
||||
hard_limit: int,
|
||||
) -> str:
|
||||
if int(hard_limit) > 0:
|
||||
return f"本交易日累计开仓:{int(opens_today)}(硬上限 {int(hard_limit)},提醒 {int(alert_threshold)})"
|
||||
return f"本交易日累计开仓:{int(opens_today)}(提醒阈值 {int(alert_threshold)})"
|
||||
|
||||
@@ -1,136 +1,136 @@
|
||||
"""
|
||||
四所共用:计仓模式 risk(以损定仓)| full_margin(全仓杠杆)。
|
||||
仅 env POSITION_SIZING_MODE 切换;须无持仓(由部署流程保证)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
MODE_RISK = "risk"
|
||||
MODE_FULL_MARGIN = "full_margin"
|
||||
VALID_MODES = frozenset({MODE_RISK, MODE_FULL_MARGIN})
|
||||
|
||||
OPEN_SOURCE_MANUAL = "manual"
|
||||
OPEN_SOURCE_KEY_AUTO = "key_auto"
|
||||
OPEN_SOURCE_KEY_FIB = "key_fib"
|
||||
OPEN_SOURCE_KEY_TRIGGER = "key_trigger"
|
||||
OPEN_SOURCE_TREND = "trend"
|
||||
OPEN_SOURCE_ROLL = "roll"
|
||||
|
||||
FULL_MARGIN_BLOCKED_SOURCES = frozenset(
|
||||
{OPEN_SOURCE_KEY_AUTO, OPEN_SOURCE_KEY_FIB, OPEN_SOURCE_TREND, OPEN_SOURCE_ROLL}
|
||||
)
|
||||
|
||||
|
||||
def normalize_position_sizing_mode(raw: Optional[str]) -> str:
|
||||
v = (raw or MODE_RISK).strip().lower()
|
||||
if v in ("full", "full_margin", "fullmargin", "全仓", "全仓杠杆"):
|
||||
return MODE_FULL_MARGIN
|
||||
return MODE_RISK if v in ("risk", "r", "以损定仓", "") else MODE_RISK
|
||||
|
||||
|
||||
def load_position_sizing_mode(env: Optional[dict] = None) -> str:
|
||||
e = env if env is not None else os.environ
|
||||
return normalize_position_sizing_mode(e.get("POSITION_SIZING_MODE"))
|
||||
|
||||
|
||||
def is_full_margin_mode(mode: str) -> bool:
|
||||
return normalize_position_sizing_mode(mode) == MODE_FULL_MARGIN
|
||||
|
||||
|
||||
def mode_label_zh(mode: str) -> str:
|
||||
return "全仓杠杆" if is_full_margin_mode(mode) else "以损定仓"
|
||||
|
||||
|
||||
def leverage_for_full_margin(symbol: str, btc_leverage: int, alt_leverage: int) -> int:
|
||||
sym = (symbol or "").strip().upper()
|
||||
if sym.startswith("BTC") or sym.startswith("ETH"):
|
||||
return max(1, int(btc_leverage or 10))
|
||||
return max(1, int(alt_leverage or 5))
|
||||
|
||||
|
||||
def round_funds(value: float, decimals: int = 2) -> float:
|
||||
return round(float(value), int(decimals))
|
||||
|
||||
|
||||
def risk_percent_for_storage(mode: str, risk_percent: float) -> Optional[float]:
|
||||
"""全仓杠杆:库内不写风险百分比(仅 risk_amount U)。"""
|
||||
if is_full_margin_mode(mode):
|
||||
return None
|
||||
return risk_percent
|
||||
|
||||
|
||||
def format_risk_display_text(
|
||||
mode: str,
|
||||
risk_percent: Optional[float],
|
||||
risk_amount: Optional[float],
|
||||
*,
|
||||
decimals: int = 2,
|
||||
) -> str:
|
||||
"""持仓/通知「风险」文案:全仓仅 U;以损定仓为 %≈U。"""
|
||||
amt: Optional[float] = None
|
||||
if risk_amount is not None and risk_amount != "":
|
||||
try:
|
||||
amt = float(risk_amount)
|
||||
except (TypeError, ValueError):
|
||||
amt = None
|
||||
if is_full_margin_mode(mode):
|
||||
if amt is None:
|
||||
return "—"
|
||||
return f"{round_funds(amt, decimals)}U"
|
||||
pct: Optional[float] = None
|
||||
if risk_percent is not None and risk_percent != "":
|
||||
try:
|
||||
pct = float(risk_percent)
|
||||
except (TypeError, ValueError):
|
||||
pct = None
|
||||
pct_txt = f"{pct:g}" if pct is not None else "—"
|
||||
amt_txt = round_funds(amt, decimals) if amt is not None else "—"
|
||||
return f"{pct_txt}%≈{amt_txt}U"
|
||||
|
||||
|
||||
def assert_open_source_allowed(mode: str, source: str) -> Tuple[bool, str]:
|
||||
if not is_full_margin_mode(mode):
|
||||
return True, ""
|
||||
src = (source or "").strip().lower()
|
||||
if src in FULL_MARGIN_BLOCKED_SOURCES:
|
||||
return False, (
|
||||
"当前为全仓杠杆模式(POSITION_SIZING_MODE=full_margin),"
|
||||
"不允许关键位突破/斐波自动开仓、趋势回调与顺势加仓;"
|
||||
"仅支持实盘人工下单与阻力/支撑提醒。"
|
||||
)
|
||||
return True, ""
|
||||
|
||||
|
||||
def full_margin_requires_flat_position(active_count: int) -> Tuple[bool, str]:
|
||||
if active_count > 0:
|
||||
return False, "全仓杠杆模式仅允许单仓且无其它持仓,请先平仓后再开仓"
|
||||
return True, ""
|
||||
|
||||
|
||||
def compute_full_margin_sizing(
|
||||
*,
|
||||
symbol: str,
|
||||
available_usdt: float,
|
||||
capital_base: float,
|
||||
buffer_ratio: float,
|
||||
btc_leverage: int,
|
||||
alt_leverage: int,
|
||||
funds_decimals: int = 2,
|
||||
) -> Tuple[Optional[dict[str, Any]], Optional[str]]:
|
||||
if available_usdt is None or float(available_usdt) <= 0:
|
||||
return None, "全仓杠杆:无法读取合约账户可用保证金"
|
||||
lev = leverage_for_full_margin(symbol, btc_leverage, alt_leverage)
|
||||
margin = round_funds(float(available_usdt) * float(buffer_ratio), funds_decimals)
|
||||
if margin <= 0:
|
||||
return None, "全仓杠杆:可用保证金不足"
|
||||
notional = round_funds(margin * lev, funds_decimals)
|
||||
ratio = round(margin / float(capital_base) * 100, 2) if capital_base else 0.0
|
||||
return {
|
||||
"margin_capital": margin,
|
||||
"leverage": lev,
|
||||
"notional_value": notional,
|
||||
"position_ratio": ratio,
|
||||
"mode": MODE_FULL_MARGIN,
|
||||
}, None
|
||||
"""
|
||||
三所共用:计仓模式 risk(以损定仓)| full_margin(全仓杠杆)。
|
||||
仅 env POSITION_SIZING_MODE 切换;须无持仓(由部署流程保证)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
MODE_RISK = "risk"
|
||||
MODE_FULL_MARGIN = "full_margin"
|
||||
VALID_MODES = frozenset({MODE_RISK, MODE_FULL_MARGIN})
|
||||
|
||||
OPEN_SOURCE_MANUAL = "manual"
|
||||
OPEN_SOURCE_KEY_AUTO = "key_auto"
|
||||
OPEN_SOURCE_KEY_FIB = "key_fib"
|
||||
OPEN_SOURCE_KEY_TRIGGER = "key_trigger"
|
||||
OPEN_SOURCE_TREND = "trend"
|
||||
OPEN_SOURCE_ROLL = "roll"
|
||||
|
||||
FULL_MARGIN_BLOCKED_SOURCES = frozenset(
|
||||
{OPEN_SOURCE_KEY_AUTO, OPEN_SOURCE_KEY_FIB, OPEN_SOURCE_TREND, OPEN_SOURCE_ROLL}
|
||||
)
|
||||
|
||||
|
||||
def normalize_position_sizing_mode(raw: Optional[str]) -> str:
|
||||
v = (raw or MODE_RISK).strip().lower()
|
||||
if v in ("full", "full_margin", "fullmargin", "全仓", "全仓杠杆"):
|
||||
return MODE_FULL_MARGIN
|
||||
return MODE_RISK if v in ("risk", "r", "以损定仓", "") else MODE_RISK
|
||||
|
||||
|
||||
def load_position_sizing_mode(env: Optional[dict] = None) -> str:
|
||||
e = env if env is not None else os.environ
|
||||
return normalize_position_sizing_mode(e.get("POSITION_SIZING_MODE"))
|
||||
|
||||
|
||||
def is_full_margin_mode(mode: str) -> bool:
|
||||
return normalize_position_sizing_mode(mode) == MODE_FULL_MARGIN
|
||||
|
||||
|
||||
def mode_label_zh(mode: str) -> str:
|
||||
return "全仓杠杆" if is_full_margin_mode(mode) else "以损定仓"
|
||||
|
||||
|
||||
def leverage_for_full_margin(symbol: str, btc_leverage: int, alt_leverage: int) -> int:
|
||||
sym = (symbol or "").strip().upper()
|
||||
if sym.startswith("BTC") or sym.startswith("ETH"):
|
||||
return max(1, int(btc_leverage or 10))
|
||||
return max(1, int(alt_leverage or 5))
|
||||
|
||||
|
||||
def round_funds(value: float, decimals: int = 2) -> float:
|
||||
return round(float(value), int(decimals))
|
||||
|
||||
|
||||
def risk_percent_for_storage(mode: str, risk_percent: float) -> Optional[float]:
|
||||
"""全仓杠杆:库内不写风险百分比(仅 risk_amount U)。"""
|
||||
if is_full_margin_mode(mode):
|
||||
return None
|
||||
return risk_percent
|
||||
|
||||
|
||||
def format_risk_display_text(
|
||||
mode: str,
|
||||
risk_percent: Optional[float],
|
||||
risk_amount: Optional[float],
|
||||
*,
|
||||
decimals: int = 2,
|
||||
) -> str:
|
||||
"""持仓/通知「风险」文案:全仓仅 U;以损定仓为 %≈U。"""
|
||||
amt: Optional[float] = None
|
||||
if risk_amount is not None and risk_amount != "":
|
||||
try:
|
||||
amt = float(risk_amount)
|
||||
except (TypeError, ValueError):
|
||||
amt = None
|
||||
if is_full_margin_mode(mode):
|
||||
if amt is None:
|
||||
return "—"
|
||||
return f"{round_funds(amt, decimals)}U"
|
||||
pct: Optional[float] = None
|
||||
if risk_percent is not None and risk_percent != "":
|
||||
try:
|
||||
pct = float(risk_percent)
|
||||
except (TypeError, ValueError):
|
||||
pct = None
|
||||
pct_txt = f"{pct:g}" if pct is not None else "—"
|
||||
amt_txt = round_funds(amt, decimals) if amt is not None else "—"
|
||||
return f"{pct_txt}%≈{amt_txt}U"
|
||||
|
||||
|
||||
def assert_open_source_allowed(mode: str, source: str) -> Tuple[bool, str]:
|
||||
if not is_full_margin_mode(mode):
|
||||
return True, ""
|
||||
src = (source or "").strip().lower()
|
||||
if src in FULL_MARGIN_BLOCKED_SOURCES:
|
||||
return False, (
|
||||
"当前为全仓杠杆模式(POSITION_SIZING_MODE=full_margin),"
|
||||
"不允许关键位突破/斐波自动开仓、趋势回调与顺势加仓;"
|
||||
"仅支持实盘人工下单与阻力/支撑提醒。"
|
||||
)
|
||||
return True, ""
|
||||
|
||||
|
||||
def full_margin_requires_flat_position(active_count: int) -> Tuple[bool, str]:
|
||||
if active_count > 0:
|
||||
return False, "全仓杠杆模式仅允许单仓且无其它持仓,请先平仓后再开仓"
|
||||
return True, ""
|
||||
|
||||
|
||||
def compute_full_margin_sizing(
|
||||
*,
|
||||
symbol: str,
|
||||
available_usdt: float,
|
||||
capital_base: float,
|
||||
buffer_ratio: float,
|
||||
btc_leverage: int,
|
||||
alt_leverage: int,
|
||||
funds_decimals: int = 2,
|
||||
) -> Tuple[Optional[dict[str, Any]], Optional[str]]:
|
||||
if available_usdt is None or float(available_usdt) <= 0:
|
||||
return None, "全仓杠杆:无法读取合约账户可用保证金"
|
||||
lev = leverage_for_full_margin(symbol, btc_leverage, alt_leverage)
|
||||
margin = round_funds(float(available_usdt) * float(buffer_ratio), funds_decimals)
|
||||
if margin <= 0:
|
||||
return None, "全仓杠杆:可用保证金不足"
|
||||
notional = round_funds(margin * lev, funds_decimals)
|
||||
ratio = round(margin / float(capital_base) * 100, 2) if capital_base else 0.0
|
||||
return {
|
||||
"margin_capital": margin,
|
||||
"leverage": lev,
|
||||
"notional_value": notional,
|
||||
"position_ratio": ratio,
|
||||
"mode": MODE_FULL_MARGIN,
|
||||
}, None
|
||||
|
||||
@@ -1,229 +1,229 @@
|
||||
"""平仓交易:交易所口径双边成交额与手续费(四所共用聚合逻辑)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def _coerce_ts_ms(raw: Any) -> int | None:
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
try:
|
||||
v = int(raw)
|
||||
return v if v > 1_000_000_000_000 else v * 1000
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def quote_turnover_usdt_from_fill(trade: dict, *, contract_size: float = 1.0) -> float:
|
||||
"""单笔成交的报价币成交额(USDT 口径)。"""
|
||||
info = trade.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
for key in ("quoteQty", "quote_qty", "fillNotionalUsd", "notional"):
|
||||
try:
|
||||
v = float(info.get(key) or 0)
|
||||
if v > 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
try:
|
||||
cost = float(trade.get("cost") or 0)
|
||||
if cost > 0:
|
||||
return abs(cost)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
try:
|
||||
price = float(trade.get("price") or 0)
|
||||
amount = float(trade.get("amount") or 0) * float(contract_size or 1.0)
|
||||
if price > 0 and amount > 0:
|
||||
return abs(price * amount)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return 0.0
|
||||
|
||||
|
||||
def commission_usdt_from_fill(trade: dict) -> float:
|
||||
"""单笔成交手续费(正数表示成本)。"""
|
||||
fee = trade.get("fee")
|
||||
if isinstance(fee, dict):
|
||||
try:
|
||||
cost = float(fee.get("cost") or 0)
|
||||
except (TypeError, ValueError):
|
||||
cost = 0.0
|
||||
if cost != 0:
|
||||
cur = str(fee.get("currency") or "USDT").upper()
|
||||
if cur in ("USDT", "USD", "BUSD", "USDC"):
|
||||
return abs(cost)
|
||||
return abs(cost)
|
||||
info = trade.get("info") or {}
|
||||
if isinstance(info, dict):
|
||||
for key in ("fee", "commission", "fillFee"):
|
||||
try:
|
||||
v = float(info.get(key) or 0)
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return 0.0
|
||||
|
||||
|
||||
def aggregate_bilateral_stats(
|
||||
fills: list[dict],
|
||||
*,
|
||||
contract_size: float = 1.0,
|
||||
) -> dict[str, float] | None:
|
||||
"""双边成交额 = 开+平所有相关 fill 的报价币成交额之和;手续费 = fill fee 之和。"""
|
||||
if not fills:
|
||||
return None
|
||||
turnover = 0.0
|
||||
commission = 0.0
|
||||
for t in fills:
|
||||
turnover += quote_turnover_usdt_from_fill(t, contract_size=contract_size)
|
||||
commission += commission_usdt_from_fill(t)
|
||||
if turnover <= 0 and commission <= 0:
|
||||
return None
|
||||
return {
|
||||
"exchange_turnover_usdt": round(turnover, 4),
|
||||
"exchange_commission_usdt": round(commission, 4),
|
||||
}
|
||||
|
||||
|
||||
def filter_position_lifecycle_fills(
|
||||
trades: list[dict],
|
||||
direction: str,
|
||||
open_ms: int | None,
|
||||
close_ms: int | None,
|
||||
*,
|
||||
hedge_mode: bool = False,
|
||||
close_buffer_ms: int = 15 * 60 * 1000,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
持仓生命周期内 fill:多=开买+平卖;空=开卖+平买。
|
||||
hedge_mode 时按 posSide 与 direction 过滤。
|
||||
"""
|
||||
direction = (direction or "long").strip().lower()
|
||||
open_side = "buy" if direction == "long" else "sell"
|
||||
close_side = "sell" if direction == "long" else "buy"
|
||||
allowed_sides = {open_side, close_side}
|
||||
upper = int(close_ms) + int(close_buffer_ms) if close_ms else None
|
||||
out: list[dict] = []
|
||||
for t in trades or []:
|
||||
side = (t.get("side") or "").lower()
|
||||
if side not in allowed_sides:
|
||||
continue
|
||||
ts = _coerce_ts_ms(t.get("timestamp"))
|
||||
if ts is None:
|
||||
continue
|
||||
if open_ms and ts < int(open_ms) - 60_000:
|
||||
continue
|
||||
if upper and ts > upper:
|
||||
continue
|
||||
if hedge_mode:
|
||||
info = t.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
pos_side = (info.get("posSide") or t.get("posSide") or "").lower()
|
||||
if pos_side in ("long", "short") and pos_side != direction:
|
||||
continue
|
||||
out.append(t)
|
||||
out.sort(key=lambda x: x.get("timestamp") or 0)
|
||||
return out
|
||||
|
||||
|
||||
def sum_binance_commission_income(entries: list[dict], trade_ids: set[str] | None) -> float | None:
|
||||
"""Binance income 流水中 COMMISSION 合计(负值取绝对值为成本)。"""
|
||||
if not entries:
|
||||
return None
|
||||
total = 0.0
|
||||
found = False
|
||||
for e in entries:
|
||||
it = (e.get("incomeType") or e.get("income_type") or "").strip()
|
||||
if it != "COMMISSION":
|
||||
continue
|
||||
if trade_ids:
|
||||
tid = str(e.get("tradeId") or e.get("trade_id") or "").strip()
|
||||
if tid and tid not in trade_ids:
|
||||
continue
|
||||
try:
|
||||
total += float(e.get("income") or 0)
|
||||
found = True
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not found:
|
||||
return None
|
||||
return round(abs(total), 4)
|
||||
|
||||
|
||||
def trade_ids_from_fills(fills: list[dict]) -> set[str]:
|
||||
out: set[str] = set()
|
||||
for t in fills or []:
|
||||
info = t.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
for key in ("id", "tradeId", "trade_id"):
|
||||
raw = t.get(key) if key in t else info.get(key)
|
||||
if raw is not None and str(raw).strip():
|
||||
out.add(str(raw).strip())
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def merge_commission_prefer_income(
|
||||
fill_commission: float,
|
||||
income_commission: float | None,
|
||||
) -> float:
|
||||
if income_commission is not None and income_commission > 0:
|
||||
return round(income_commission, 4)
|
||||
return round(max(fill_commission, 0.0), 4)
|
||||
|
||||
|
||||
def update_trade_record_stats_columns(
|
||||
conn: Any,
|
||||
trade_id: int,
|
||||
turnover_usdt: float | None,
|
||||
commission_usdt: float | None,
|
||||
) -> None:
|
||||
if turnover_usdt is None and commission_usdt is None:
|
||||
return
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE trade_records
|
||||
SET exchange_turnover_usdt = COALESCE(?, exchange_turnover_usdt),
|
||||
exchange_commission_usdt = COALESCE(?, exchange_commission_usdt)
|
||||
WHERE id = ?
|
||||
""",
|
||||
(turnover_usdt, commission_usdt, int(trade_id)),
|
||||
)
|
||||
|
||||
|
||||
def attach_exchange_stats_to_trade(
|
||||
conn: Any,
|
||||
trade_id: int,
|
||||
*,
|
||||
fetch_fills: Callable[[], list[dict]],
|
||||
contract_size: float = 1.0,
|
||||
income_commission: float | None = None,
|
||||
) -> dict[str, float] | None:
|
||||
"""拉 fill 并写库;仅在新单平仓路径调用。"""
|
||||
try:
|
||||
fills = fetch_fills() or []
|
||||
except Exception:
|
||||
fills = []
|
||||
stats = aggregate_bilateral_stats(fills, contract_size=contract_size)
|
||||
if not stats and income_commission is None:
|
||||
return None
|
||||
turnover = stats.get("exchange_turnover_usdt") if stats else None
|
||||
fill_comm = float(stats.get("exchange_commission_usdt") or 0) if stats else 0.0
|
||||
commission = merge_commission_prefer_income(fill_comm, income_commission)
|
||||
update_trade_record_stats_columns(
|
||||
conn,
|
||||
trade_id,
|
||||
turnover,
|
||||
commission if commission > 0 else None,
|
||||
)
|
||||
out = {}
|
||||
if turnover is not None:
|
||||
out["exchange_turnover_usdt"] = turnover
|
||||
if commission > 0:
|
||||
out["exchange_commission_usdt"] = commission
|
||||
return out or None
|
||||
"""平仓交易:交易所口径双边成交额与手续费(三所共用聚合逻辑)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def _coerce_ts_ms(raw: Any) -> int | None:
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
try:
|
||||
v = int(raw)
|
||||
return v if v > 1_000_000_000_000 else v * 1000
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def quote_turnover_usdt_from_fill(trade: dict, *, contract_size: float = 1.0) -> float:
|
||||
"""单笔成交的报价币成交额(USDT 口径)。"""
|
||||
info = trade.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
for key in ("quoteQty", "quote_qty", "fillNotionalUsd", "notional"):
|
||||
try:
|
||||
v = float(info.get(key) or 0)
|
||||
if v > 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
try:
|
||||
cost = float(trade.get("cost") or 0)
|
||||
if cost > 0:
|
||||
return abs(cost)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
try:
|
||||
price = float(trade.get("price") or 0)
|
||||
amount = float(trade.get("amount") or 0) * float(contract_size or 1.0)
|
||||
if price > 0 and amount > 0:
|
||||
return abs(price * amount)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return 0.0
|
||||
|
||||
|
||||
def commission_usdt_from_fill(trade: dict) -> float:
|
||||
"""单笔成交手续费(正数表示成本)。"""
|
||||
fee = trade.get("fee")
|
||||
if isinstance(fee, dict):
|
||||
try:
|
||||
cost = float(fee.get("cost") or 0)
|
||||
except (TypeError, ValueError):
|
||||
cost = 0.0
|
||||
if cost != 0:
|
||||
cur = str(fee.get("currency") or "USDT").upper()
|
||||
if cur in ("USDT", "USD", "BUSD", "USDC"):
|
||||
return abs(cost)
|
||||
return abs(cost)
|
||||
info = trade.get("info") or {}
|
||||
if isinstance(info, dict):
|
||||
for key in ("fee", "commission", "fillFee"):
|
||||
try:
|
||||
v = float(info.get(key) or 0)
|
||||
if v != 0:
|
||||
return abs(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return 0.0
|
||||
|
||||
|
||||
def aggregate_bilateral_stats(
|
||||
fills: list[dict],
|
||||
*,
|
||||
contract_size: float = 1.0,
|
||||
) -> dict[str, float] | None:
|
||||
"""双边成交额 = 开+平所有相关 fill 的报价币成交额之和;手续费 = fill fee 之和。"""
|
||||
if not fills:
|
||||
return None
|
||||
turnover = 0.0
|
||||
commission = 0.0
|
||||
for t in fills:
|
||||
turnover += quote_turnover_usdt_from_fill(t, contract_size=contract_size)
|
||||
commission += commission_usdt_from_fill(t)
|
||||
if turnover <= 0 and commission <= 0:
|
||||
return None
|
||||
return {
|
||||
"exchange_turnover_usdt": round(turnover, 4),
|
||||
"exchange_commission_usdt": round(commission, 4),
|
||||
}
|
||||
|
||||
|
||||
def filter_position_lifecycle_fills(
|
||||
trades: list[dict],
|
||||
direction: str,
|
||||
open_ms: int | None,
|
||||
close_ms: int | None,
|
||||
*,
|
||||
hedge_mode: bool = False,
|
||||
close_buffer_ms: int = 15 * 60 * 1000,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
持仓生命周期内 fill:多=开买+平卖;空=开卖+平买。
|
||||
hedge_mode 时按 posSide 与 direction 过滤。
|
||||
"""
|
||||
direction = (direction or "long").strip().lower()
|
||||
open_side = "buy" if direction == "long" else "sell"
|
||||
close_side = "sell" if direction == "long" else "buy"
|
||||
allowed_sides = {open_side, close_side}
|
||||
upper = int(close_ms) + int(close_buffer_ms) if close_ms else None
|
||||
out: list[dict] = []
|
||||
for t in trades or []:
|
||||
side = (t.get("side") or "").lower()
|
||||
if side not in allowed_sides:
|
||||
continue
|
||||
ts = _coerce_ts_ms(t.get("timestamp"))
|
||||
if ts is None:
|
||||
continue
|
||||
if open_ms and ts < int(open_ms) - 60_000:
|
||||
continue
|
||||
if upper and ts > upper:
|
||||
continue
|
||||
if hedge_mode:
|
||||
info = t.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
pos_side = (info.get("posSide") or t.get("posSide") or "").lower()
|
||||
if pos_side in ("long", "short") and pos_side != direction:
|
||||
continue
|
||||
out.append(t)
|
||||
out.sort(key=lambda x: x.get("timestamp") or 0)
|
||||
return out
|
||||
|
||||
|
||||
def sum_binance_commission_income(entries: list[dict], trade_ids: set[str] | None) -> float | None:
|
||||
"""Binance income 流水中 COMMISSION 合计(负值取绝对值为成本)。"""
|
||||
if not entries:
|
||||
return None
|
||||
total = 0.0
|
||||
found = False
|
||||
for e in entries:
|
||||
it = (e.get("incomeType") or e.get("income_type") or "").strip()
|
||||
if it != "COMMISSION":
|
||||
continue
|
||||
if trade_ids:
|
||||
tid = str(e.get("tradeId") or e.get("trade_id") or "").strip()
|
||||
if tid and tid not in trade_ids:
|
||||
continue
|
||||
try:
|
||||
total += float(e.get("income") or 0)
|
||||
found = True
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not found:
|
||||
return None
|
||||
return round(abs(total), 4)
|
||||
|
||||
|
||||
def trade_ids_from_fills(fills: list[dict]) -> set[str]:
|
||||
out: set[str] = set()
|
||||
for t in fills or []:
|
||||
info = t.get("info") or {}
|
||||
if not isinstance(info, dict):
|
||||
info = {}
|
||||
for key in ("id", "tradeId", "trade_id"):
|
||||
raw = t.get(key) if key in t else info.get(key)
|
||||
if raw is not None and str(raw).strip():
|
||||
out.add(str(raw).strip())
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def merge_commission_prefer_income(
|
||||
fill_commission: float,
|
||||
income_commission: float | None,
|
||||
) -> float:
|
||||
if income_commission is not None and income_commission > 0:
|
||||
return round(income_commission, 4)
|
||||
return round(max(fill_commission, 0.0), 4)
|
||||
|
||||
|
||||
def update_trade_record_stats_columns(
|
||||
conn: Any,
|
||||
trade_id: int,
|
||||
turnover_usdt: float | None,
|
||||
commission_usdt: float | None,
|
||||
) -> None:
|
||||
if turnover_usdt is None and commission_usdt is None:
|
||||
return
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE trade_records
|
||||
SET exchange_turnover_usdt = COALESCE(?, exchange_turnover_usdt),
|
||||
exchange_commission_usdt = COALESCE(?, exchange_commission_usdt)
|
||||
WHERE id = ?
|
||||
""",
|
||||
(turnover_usdt, commission_usdt, int(trade_id)),
|
||||
)
|
||||
|
||||
|
||||
def attach_exchange_stats_to_trade(
|
||||
conn: Any,
|
||||
trade_id: int,
|
||||
*,
|
||||
fetch_fills: Callable[[], list[dict]],
|
||||
contract_size: float = 1.0,
|
||||
income_commission: float | None = None,
|
||||
) -> dict[str, float] | None:
|
||||
"""拉 fill 并写库;仅在新单平仓路径调用。"""
|
||||
try:
|
||||
fills = fetch_fills() or []
|
||||
except Exception:
|
||||
fills = []
|
||||
stats = aggregate_bilateral_stats(fills, contract_size=contract_size)
|
||||
if not stats and income_commission is None:
|
||||
return None
|
||||
turnover = stats.get("exchange_turnover_usdt") if stats else None
|
||||
fill_comm = float(stats.get("exchange_commission_usdt") or 0) if stats else 0.0
|
||||
commission = merge_commission_prefer_income(fill_comm, income_commission)
|
||||
update_trade_record_stats_columns(
|
||||
conn,
|
||||
trade_id,
|
||||
turnover,
|
||||
commission if commission > 0 else None,
|
||||
)
|
||||
out = {}
|
||||
if turnover is not None:
|
||||
out["exchange_turnover_usdt"] = turnover
|
||||
if commission > 0:
|
||||
out["exchange_commission_usdt"] = commission
|
||||
return out or None
|
||||
|
||||
@@ -9,7 +9,7 @@ HUB_HOST=0.0.0.0
|
||||
HUB_PORT=5100
|
||||
# 仅本机访问可改为 127.0.0.1,并设 HUB_TRUST_LAN=false
|
||||
|
||||
# 与四实例 .env 中 HUB_BRIDGE_TOKEN 相同的长随机串
|
||||
# 与三实例 .env 中 HUB_BRIDGE_TOKEN 相同的长随机串
|
||||
# 中控 → 各 Flask:请求头 X-Hub-Token
|
||||
# 中控 → 各子代理:请求头 X-Control-Token(可与子代理 CONTROL_TOKEN 同值,hub 会用 HUB_BRIDGE_TOKEN 转发)
|
||||
# 中控「打开实例」SSO 链接也复用此令牌签名(默认 2 小时内有效、单次使用)
|
||||
@@ -41,10 +41,10 @@ HUB_PASSWORD=admin123
|
||||
# 限制可嵌入的父页来源(逗号分隔);默认 * 不限制
|
||||
# HUB_EMBED_ORIGINS=http://192.168.8.6:5070,https://hub.example.com
|
||||
|
||||
# 四实例允许被中控 iframe 内嵌(各 crypto_monitor_*/.env,与 hub 同步部署)
|
||||
# 三实例允许被中控 iframe 内嵌(各 crypto_monitor_*/.env,与 hub 同步部署)
|
||||
# APP_ALLOW_HUB_EMBED=true
|
||||
# HUB_EMBED_PARENT_ORIGINS=https://hub.example.com
|
||||
# HTTPS 跨子域 iframe 时四实例还须 APP_COOKIE_SECURE=true(见 crypto_monitor_*/.env.example)
|
||||
# HTTPS 跨子域 iframe 时三实例还须 APP_COOKIE_SECURE=true(见 crypto_monitor_*/.env.example)
|
||||
|
||||
# 浏览器打开的实例/复盘链接(hub_settings 里 flask_url 为 127.0.0.1 时替换为对外地址)
|
||||
# 局域网:填内网 IP,见《局域网与反代部署说明.md》
|
||||
@@ -53,7 +53,7 @@ HUB_PASSWORD=admin123
|
||||
# HUB_PUBLIC_HOST=192.168.1.100
|
||||
# HUB_PUBLIC_SCHEME=http
|
||||
|
||||
# 四实例网页登录(直链反代/IP:端口 访问时输入;中控点「打开实例」免输)
|
||||
# 三实例网页登录(直链反代/IP:端口 访问时输入;中控点「打开实例」免输)
|
||||
# 各 crypto_monitor_*/.env 统一:APP_USERNAME=... APP_PASSWORD=...
|
||||
|
||||
# 监控区:hub 后台每 N 秒聚合一次,浏览器经 SSE 收版本号再拉快照(默认 5 秒)
|
||||
@@ -82,7 +82,7 @@ HUB_PASSWORD=admin123
|
||||
# HOST=127.0.0.1
|
||||
|
||||
# ---------- 中控 AI 教练(/ai,模块 hub_ai/,存 hub_ai_*.json)----------
|
||||
# 与四实例相同变量名;默认 OpenAI 兼容网关(改 AI_PROVIDER=ollama 可走本机 Ollama)
|
||||
# 与三实例相同变量名;默认 OpenAI 兼容网关(改 AI_PROVIDER=ollama 可走本机 Ollama)
|
||||
# 详见 manual_trading_hub/AI教练说明.md 与仓库根 AI复盘与模型配置说明.md
|
||||
AI_TIMEOUT_SECONDS=120
|
||||
# AI 教练聊天(默认:输出 8192 token、续写 4 次、快照约 2 万字符、历史单条 1500 字)
|
||||
@@ -102,7 +102,7 @@ OPENAI_MODEL=gemma4:e4b
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
|
||||
# 交易日切分(与四实例 TRADING_DAY_RESET_HOUR 一致,定义「今日总结」的日期)
|
||||
# 交易日切分(与三实例 TRADING_DAY_RESET_HOUR 一致,定义「今日总结」的日期)
|
||||
TRADING_DAY_RESET_HOUR=8
|
||||
# 资金概况 / AI 上下文:分户资金快照保留交易日数(默认 180)
|
||||
# HUB_FUND_HISTORY_DAYS=180
|
||||
|
||||
@@ -1,66 +1,66 @@
|
||||
# 中控 AI 教练说明
|
||||
|
||||
中控 **AI 教练**(`/ai`)与四实例 `/records` 里的 **AI 复盘** 分离:模块在 `manual_trading_hub/hub_ai/`,数据存同目录 JSON。
|
||||
|
||||
## 能力
|
||||
|
||||
| 功能 | 说明 |
|
||||
|------|------|
|
||||
| **交易教练** | 口语化陪聊;注入四户监控快照与今日总结摘要(后台自动生成,不在页面展示) |
|
||||
| **普通聊天** | 不绑交易数据,适合闲聊、答疑 |
|
||||
| **交易监管** | 今日长会话;手动/中控开平仓与新开仓自动推送 + 企业微信 + 可回聊(见 [交易监管说明.md](./交易监管说明.md)) |
|
||||
| **会话历史** | 右侧列表:切换、删除;消息一键复制 |
|
||||
|
||||
页面保留 **交易教练 / 普通聊天 / 交易监管** 与聊天区;**今日总结** 已移至 **数据看板**(`/dashboard`)纯数据展示,不再在 AI 页生成。
|
||||
|
||||
## 存储
|
||||
|
||||
与 `hub_settings.json` 同目录(`manual_trading_hub/`):
|
||||
|
||||
- `hub_ai_summaries.json` — 历史总结(供交易教练上下文,可选 API 仍保留)
|
||||
- `hub_ai_chat.json` — 聊天会话(`active_session_id`、多会话、`bot_mode`)
|
||||
|
||||
升级 / 迁移时请一并备份(见 [本地数据迁移到云端.md](./本地数据迁移到云端.md))。
|
||||
|
||||
## 模型配置
|
||||
|
||||
在 **`manual_trading_hub/.env`** 配置,**变量名与四实例完全相同**;中控 `hub_ai/client.py` 共用仓库根 `ai_client.py`,**默认也是 OpenAI 兼容网关**(`AI_PROVIDER=openai`),与你在四所 `.env` 里配的那套一致即可。
|
||||
|
||||
**推荐(与四实例默认一致):**
|
||||
|
||||
```env
|
||||
AI_PROVIDER=openai
|
||||
OPENAI_API_BASE=https://op.bz121.com/v1
|
||||
OPENAI_API_KEY=你的密钥
|
||||
OPENAI_MODEL=gemma4:e4b
|
||||
|
||||
# 本机 Ollama 备用(仅当 AI_PROVIDER=ollama 时生效)
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
```
|
||||
|
||||
改走本机无限制模型时,将 `AI_PROVIDER=ollama`,并填好 `OLLAMA_API` / `AI_MODEL`;`OPENAI_*` 可保留不动。
|
||||
|
||||
总结与聊天使用**同一模型**(同一套 `OPENAI_MODEL` 或 `AI_MODEL`);总结 temperature≈0.15,聊天≈0.5。
|
||||
|
||||
可选:`TRADING_DAY_RESET_HOUR=8`(与实例一致,定义「今日」交易日)。
|
||||
|
||||
## 依赖接口
|
||||
|
||||
中控通过 HTTP 拉取各实例:
|
||||
|
||||
- `GET /api/hub/monitor`(已有)
|
||||
- `GET /api/hub/trades/today?trading_day=YYYY-MM-DD`(`hub_bridge` 注册,需四实例更新代码并重启)
|
||||
|
||||
子代理 `GET /status` 提供持仓与余额。
|
||||
|
||||
## 与实例 AI 复盘的分工
|
||||
|
||||
| | 中控 AI 教练 | 实例 AI 复盘 |
|
||||
|--|-------------|-------------|
|
||||
| 入口 | `/ai` | 各所 `/records` |
|
||||
| 数据 | 四户聚合 | 单户 `journal_entries` |
|
||||
| 语气 | 聊天搭档 | 结构化教练报告 |
|
||||
| 代码 | `hub_ai/*` | `ai_review_lib` + 各 `app.py` |
|
||||
|
||||
详见仓库根 [AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)(实例侧)。
|
||||
# 中控 AI 教练说明
|
||||
|
||||
中控 **AI 教练**(`/ai`)与三实例 `/records` 里的 **AI 复盘** 分离:模块在 `manual_trading_hub/hub_ai/`,数据存同目录 JSON。
|
||||
|
||||
## 能力
|
||||
|
||||
| 功能 | 说明 |
|
||||
|------|------|
|
||||
| **交易教练** | 口语化陪聊;注入三户监控快照与今日总结摘要(后台自动生成,不在页面展示) |
|
||||
| **普通聊天** | 不绑交易数据,适合闲聊、答疑 |
|
||||
| **交易监管** | 今日长会话;手动/中控开平仓与新开仓自动推送 + 企业微信 + 可回聊(见 [交易监管说明.md](./交易监管说明.md)) |
|
||||
| **会话历史** | 右侧列表:切换、删除;消息一键复制 |
|
||||
|
||||
页面保留 **交易教练 / 普通聊天 / 交易监管** 与聊天区;**今日总结** 已移至 **数据看板**(`/dashboard`)纯数据展示,不再在 AI 页生成。
|
||||
|
||||
## 存储
|
||||
|
||||
与 `hub_settings.json` 同目录(`manual_trading_hub/`):
|
||||
|
||||
- `hub_ai_summaries.json` — 历史总结(供交易教练上下文,可选 API 仍保留)
|
||||
- `hub_ai_chat.json` — 聊天会话(`active_session_id`、多会话、`bot_mode`)
|
||||
|
||||
升级 / 迁移时请一并备份(见 [本地数据迁移到云端.md](./本地数据迁移到云端.md))。
|
||||
|
||||
## 模型配置
|
||||
|
||||
在 **`manual_trading_hub/.env`** 配置,**变量名与三实例完全相同**;中控 `hub_ai/client.py` 共用仓库根 `ai_client.py`,**默认也是 OpenAI 兼容网关**(`AI_PROVIDER=openai`),与你在三所 `.env` 里配的那套一致即可。
|
||||
|
||||
**推荐(与三实例默认一致):**
|
||||
|
||||
```env
|
||||
AI_PROVIDER=openai
|
||||
OPENAI_API_BASE=https://op.bz121.com/v1
|
||||
OPENAI_API_KEY=你的密钥
|
||||
OPENAI_MODEL=gemma4:e4b
|
||||
|
||||
# 本机 Ollama 备用(仅当 AI_PROVIDER=ollama 时生效)
|
||||
OLLAMA_API=http://127.0.0.1:11434/api/generate
|
||||
AI_MODEL=huihui_ai/deepseek-r1-abliterated:latest
|
||||
```
|
||||
|
||||
改走本机无限制模型时,将 `AI_PROVIDER=ollama`,并填好 `OLLAMA_API` / `AI_MODEL`;`OPENAI_*` 可保留不动。
|
||||
|
||||
总结与聊天使用**同一模型**(同一套 `OPENAI_MODEL` 或 `AI_MODEL`);总结 temperature≈0.15,聊天≈0.5。
|
||||
|
||||
可选:`TRADING_DAY_RESET_HOUR=8`(与实例一致,定义「今日」交易日)。
|
||||
|
||||
## 依赖接口
|
||||
|
||||
中控通过 HTTP 拉取各实例:
|
||||
|
||||
- `GET /api/hub/monitor`(已有)
|
||||
- `GET /api/hub/trades/today?trading_day=YYYY-MM-DD`(`hub_bridge` 注册,需三实例更新代码并重启)
|
||||
|
||||
子代理 `GET /status` 提供持仓与余额。
|
||||
|
||||
## 与实例 AI 复盘的分工
|
||||
|
||||
| | 中控 AI 教练 | 实例 AI 复盘 |
|
||||
|--|-------------|-------------|
|
||||
| 入口 | `/ai` | 各所 `/records` |
|
||||
| 数据 | 三户聚合 | 单户 `journal_entries` |
|
||||
| 语气 | 聊天搭档 | 结构化教练报告 |
|
||||
| 代码 | `hub_ai/*` | `ai_review_lib` + 各 `app.py` |
|
||||
|
||||
详见仓库根 [AI复盘与模型配置说明.md](../AI复盘与模型配置说明.md)(实例侧)。
|
||||
|
||||
@@ -1,106 +1,105 @@
|
||||
# 复盘系统中控(manual_trading_hub)
|
||||
|
||||
> **完整说明**:[使用说明.md](./使用说明.md) · **资金概况**:[资金概况说明.md](./资金概况说明.md) · **数据看板**:[数据看板说明.md](./数据看板说明.md) · **AI 教练**:[AI教练说明.md](./AI教练说明.md) · **行情区**:[行情区说明.md](./行情区说明.md) · **部署**:[部署文档.md](./部署文档.md) · **云服务器**:[云服务器部署说明.md](./云服务器部署说明.md) · **本地→云端迁移**:[本地数据迁移到云端.md](./本地数据迁移到云端.md) · **局域网/反代**:[局域网与反代部署说明.md](./局域网与反代部署说明.md) · **故障**:[常见问题.md](./常见问题.md)
|
||||
|
||||
多账户 **监控聚合 + 紧急全平**;**不在中控网页下单**。人工下单、关键位、**策略交易**(`/strategy`)、复盘请在各 `crypto_monitor_*` 实例网页操作(监控卡片 **「实例」** / **「复盘」**)。**增加子账户**见 [使用说明 §4.3](./使用说明.md#43-增加账户例如再挂一个-gate)。
|
||||
|
||||
---
|
||||
|
||||
## 当前能力
|
||||
|
||||
| 能力 | 说明 |
|
||||
|------|------|
|
||||
| 监控区 | 持仓、余额、关键位摘要、趋势计划、机器人单(只读) |
|
||||
| 资金概况 | 总/分户资金(资金户+交易户)、180 日曲线、最大回撤 |
|
||||
| **数据看板** | 四户当日总览/分户/平仓明细,SSE 推送(`/dashboard`;见 [数据看板说明.md](./数据看板说明.md)) |
|
||||
| 行情区 | K 线(多周期、本地缓存、技术指标、从监控跳转持仓线) |
|
||||
| **AI 教练** | 交易教练 + 普通聊天、会话历史(`/ai`;见 [AI教练说明.md](./AI教练说明.md)) |
|
||||
| 紧急全平 | 单户 / 全局市价减仓 |
|
||||
| 系统设置 | `hub_settings.json` 管理 URL、启用、**监控关键位 / 监控趋势计划**(不控制策略交易页) |
|
||||
| Web 登录 | `.env` 设 `HUB_PASSWORD` 后用户名+密码保护(反代公网**务必**配置) |
|
||||
| ~~下单区~~ | **已移除**(避免与实例重复、减少故障面) |
|
||||
|
||||
---
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
浏览器 → hub.py (:5100) 监控 / 资金概况 / **数据看板** / 行情 / **AI 教练** / 设置 / 登录
|
||||
├→ agent.py × N (:15200~15203) 持仓、全平
|
||||
└→ 各 Flask (:5000/5001/5002/5004) /api/hub/monitor 只读聚合
|
||||
```
|
||||
|
||||
- 账户列表:**系统设置** 或默认 `settings_store.py`(不再使用环境变量 `HUB_AGENTS`)。
|
||||
- 四实例须注册 **hub_bridge**(仓库根 `hub_bridge.py`);PM2 建议 `PYTHONPATH=..`。
|
||||
|
||||
---
|
||||
|
||||
## 快速启动(Linux / PM2)
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/manual_trading_hub
|
||||
python3 -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
cp .env.example .env
|
||||
# 编辑 .env:HUB_PASSWORD、HUB_BRIDGE_TOKEN、HUB_PUBLIC_ORIGIN 等
|
||||
|
||||
pm2 start ecosystem.config.cjs # 4 agent + hub
|
||||
pm2 save
|
||||
|
||||
bash scripts/verify_hub_deploy.sh
|
||||
curl -s http://127.0.0.1:5100/api/ping
|
||||
```
|
||||
|
||||
浏览器:`http://<本机IP>:5100/monitor`(行情 `/market`;已设密码则先 `/login`)。
|
||||
|
||||
---
|
||||
|
||||
## 中控 `.env` 要点
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `HUB_PASSWORD` / `HUB_USERNAME` | 非空密码即启用登录 |
|
||||
| `HUB_BRIDGE_TOKEN` | 与四实例一致 |
|
||||
| `HUB_DISABLED_IDS` | 默认 `1` 关闭 OKX |
|
||||
| `HUB_PUBLIC_ORIGIN` | 其它设备打开复盘/实例外链(替换 127.0.0.1) |
|
||||
| `HUB_COOKIE_SECURE` | HTTPS 反代建议 `true` |
|
||||
|
||||
详见 [.env.example](./.env.example)。
|
||||
|
||||
---
|
||||
|
||||
## 子代理(agent)
|
||||
|
||||
每所策略目录单独进程,`EXCHANGE` + `PORT`(15200~15203),密钥来自**该目录 `.env`**。PM2 经 `scripts/run_agent.sh` 启动(自动 `source .env`、去 CRLF)。
|
||||
|
||||
| PORT | 目录 |
|
||||
|------|------|
|
||||
| 15200 | crypto_monitor_binance |
|
||||
| 15201 | crypto_monitor_okx |
|
||||
| 15202 | crypto_monitor_gate |
|
||||
| 15203 | crypto_monitor_gate_bot |
|
||||
|
||||
---
|
||||
|
||||
## 运维脚本
|
||||
|
||||
| 脚本 | 作用 |
|
||||
|------|------|
|
||||
| [scripts/fix_hub_deps.sh](./scripts/fix_hub_deps.sh) | 安装/更新 venv 依赖 |
|
||||
| [scripts/verify_hub_deploy.sh](./scripts/verify_hub_deploy.sh) | 验收代码版本与 ping |
|
||||
| [scripts/fix_env_crlf.sh](./scripts/fix_env_crlf.sh) | 修复 .env 的 Windows 换行 |
|
||||
| [scripts/pm2_hub.sh](./scripts/pm2_hub.sh) | PM2 启停 hub+agent |
|
||||
| [scripts/后台运行-Ubuntu.md](./scripts/后台运行-Ubuntu.md) | PM2 常驻 |
|
||||
| [docs/ubuntu-server.md](../docs/ubuntu-server.md) | Ubuntu / Python / Node / PM2 |
|
||||
|
||||
---
|
||||
|
||||
## 文档索引
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [使用说明.md](./使用说明.md) | 页面、API、环境变量、日常流程 |
|
||||
| [行情区说明.md](./行情区说明.md) | K 线周期、缓存、快捷键、拉取逻辑 |
|
||||
| [部署文档.md](./部署文档.md) | Ubuntu、PM2、反代、升级 |
|
||||
| [常见问题.md](./常见问题.md) | 已遇到问题与处理 |
|
||||
| [.env.example](./.env.example) | 环境变量模板 |
|
||||
# 复盘系统中控(manual_trading_hub)
|
||||
|
||||
> **完整说明**:[使用说明.md](./使用说明.md) · **资金概况**:[资金概况说明.md](./资金概况说明.md) · **数据看板**:[数据看板说明.md](./数据看板说明.md) · **AI 教练**:[AI教练说明.md](./AI教练说明.md) · **行情区**:[行情区说明.md](./行情区说明.md) · **部署**:[部署文档.md](./部署文档.md) · **云服务器**:[云服务器部署说明.md](./云服务器部署说明.md) · **本地→云端迁移**:[本地数据迁移到云端.md](./本地数据迁移到云端.md) · **局域网/反代**:[局域网与反代部署说明.md](./局域网与反代部署说明.md) · **故障**:[常见问题.md](./常见问题.md)
|
||||
|
||||
多账户 **监控聚合 + 紧急全平**;**不在中控网页下单**。人工下单、关键位、**策略交易**(`/strategy`)、复盘请在各 `crypto_monitor_*` 实例网页操作(监控卡片 **「实例」** / **「复盘」**)。**增加子账户**见 [使用说明 §4.3](./使用说明.md#43-增加账户例如再挂一个-gate)。
|
||||
|
||||
---
|
||||
|
||||
## 当前能力
|
||||
|
||||
| 能力 | 说明 |
|
||||
|------|------|
|
||||
| 监控区 | 持仓、余额、关键位摘要、趋势计划、机器人单(只读) |
|
||||
| 资金概况 | 总/分户资金(资金户+交易户)、180 日曲线、最大回撤 |
|
||||
| **数据看板** | 三户当日总览/分户/平仓明细,SSE 推送(`/dashboard`;见 [数据看板说明.md](./数据看板说明.md)) |
|
||||
| 行情区 | K 线(多周期、本地缓存、技术指标、从监控跳转持仓线) |
|
||||
| **AI 教练** | 交易教练 + 普通聊天、会话历史(`/ai`;见 [AI教练说明.md](./AI教练说明.md)) |
|
||||
| 紧急全平 | 单户 / 全局市价减仓 |
|
||||
| 系统设置 | `hub_settings.json` 管理 URL、启用、**监控关键位 / 监控趋势计划**(不控制策略交易页) |
|
||||
| Web 登录 | `.env` 设 `HUB_PASSWORD` 后用户名+密码保护(反代公网**务必**配置) |
|
||||
| ~~下单区~~ | **已移除**(避免与实例重复、减少故障面) |
|
||||
|
||||
---
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
浏览器 → hub.py (:5100) 监控 / 资金概况 / **数据看板** / 行情 / **AI 教练** / 设置 / 登录
|
||||
├→ agent.py × N (:15200~15202) 持仓、全平
|
||||
└→ 各 Flask (:5000/5001/5004) /api/hub/monitor 只读聚合
|
||||
```
|
||||
|
||||
- 账户列表:**系统设置** 或默认 `settings_store.py`(不再使用环境变量 `HUB_AGENTS`)。
|
||||
- 三实例须注册 **hub_bridge**(仓库根 `hub_bridge.py`);PM2 建议 `PYTHONPATH=..`。
|
||||
|
||||
---
|
||||
|
||||
## 快速启动(Linux / PM2)
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor/manual_trading_hub
|
||||
python3 -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
cp .env.example .env
|
||||
# 编辑 .env:HUB_PASSWORD、HUB_BRIDGE_TOKEN、HUB_PUBLIC_ORIGIN 等
|
||||
|
||||
pm2 start ecosystem.config.cjs # 3 agent + hub
|
||||
pm2 save
|
||||
|
||||
bash scripts/verify_hub_deploy.sh
|
||||
curl -s http://127.0.0.1:5100/api/ping
|
||||
```
|
||||
|
||||
浏览器:`http://<本机IP>:5100/monitor`(行情 `/market`;已设密码则先 `/login`)。
|
||||
|
||||
---
|
||||
|
||||
## 中控 `.env` 要点
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `HUB_PASSWORD` / `HUB_USERNAME` | 非空密码即启用登录 |
|
||||
| `HUB_BRIDGE_TOKEN` | 与三实例一致 |
|
||||
| `HUB_DISABLED_IDS` | 默认 `1` 关闭 OKX |
|
||||
| `HUB_PUBLIC_ORIGIN` | 其它设备打开复盘/实例外链(替换 127.0.0.1) |
|
||||
| `HUB_COOKIE_SECURE` | HTTPS 反代建议 `true` |
|
||||
|
||||
详见 [.env.example](./.env.example)。
|
||||
|
||||
---
|
||||
|
||||
## 子代理(agent)
|
||||
|
||||
每所策略目录单独进程,`EXCHANGE` + `PORT`(15200~15202),密钥来自**该目录 `.env`**。PM2 经 `scripts/run_agent.sh` 启动(自动 `source .env`、去 CRLF)。
|
||||
|
||||
| PORT | 目录 |
|
||||
|------|------|
|
||||
| 15200 | crypto_monitor_binance |
|
||||
| 15201 | crypto_monitor_okx |
|
||||
| 15202 | crypto_monitor_gate |
|
||||
|
||||
---
|
||||
|
||||
## 运维脚本
|
||||
|
||||
| 脚本 | 作用 |
|
||||
|------|------|
|
||||
| [scripts/fix_hub_deps.sh](./scripts/fix_hub_deps.sh) | 安装/更新 venv 依赖 |
|
||||
| [scripts/verify_hub_deploy.sh](./scripts/verify_hub_deploy.sh) | 验收代码版本与 ping |
|
||||
| [scripts/fix_env_crlf.sh](./scripts/fix_env_crlf.sh) | 修复 .env 的 Windows 换行 |
|
||||
| [scripts/pm2_hub.sh](./scripts/pm2_hub.sh) | PM2 启停 hub+agent |
|
||||
| [scripts/后台运行-Ubuntu.md](./scripts/后台运行-Ubuntu.md) | PM2 常驻 |
|
||||
| [docs/ubuntu-server.md](../docs/ubuntu-server.md) | Ubuntu / Python / Node / PM2 |
|
||||
|
||||
---
|
||||
|
||||
## 文档索引
|
||||
|
||||
| 文档 | 内容 |
|
||||
|------|------|
|
||||
| [使用说明.md](./使用说明.md) | 页面、API、环境变量、日常流程 |
|
||||
| [行情区说明.md](./行情区说明.md) | K 线周期、缓存、快捷键、拉取逻辑 |
|
||||
| [部署文档.md](./部署文档.md) | Ubuntu、PM2、反代、升级 |
|
||||
| [常见问题.md](./常见问题.md) | 已遇到问题与处理 |
|
||||
| [.env.example](./.env.example) | 环境变量模板 |
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
# 更新前快照(行情区 + K 线库)
|
||||
|
||||
> 行情区使用说明见 [行情区说明.md](./行情区说明.md)。
|
||||
|
||||
更新前已打 Git 标签,回滚方式:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor # 或你的仓库路径
|
||||
git fetch --tags
|
||||
git checkout snapshot/pre-hub-market-20260528
|
||||
# 恢复后重启:
|
||||
pm2 restart manual-trading-hub crypto_okx crypto_binance crypto_gate crypto_gate_bot
|
||||
```
|
||||
|
||||
回到最新主线:
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
git pull
|
||||
```
|
||||
|
||||
K 线数据库(不纳入 Git):`manual_trading_hub/data/hub_kline.db`,回滚代码不会自动删除该文件。
|
||||
# 更新前快照(行情区 + K 线库)
|
||||
|
||||
> 行情区使用说明见 [行情区说明.md](./行情区说明.md)。
|
||||
|
||||
更新前已打 Git 标签,回滚方式:
|
||||
|
||||
```bash
|
||||
cd /opt/crypto_monitor # 或你的仓库路径
|
||||
git fetch --tags
|
||||
git checkout snapshot/pre-hub-market-20260528
|
||||
# 恢复后重启:
|
||||
pm2 restart manual-trading-hub crypto_okx crypto_binance crypto_gate
|
||||
```
|
||||
|
||||
回到最新主线:
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
git pull
|
||||
```
|
||||
|
||||
K 线数据库(不纳入 Git):`manual_trading_hub/data/hub_kline.db`,回滚代码不会自动删除该文件。
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""
|
||||
子账户极轻代理:GET /status、挂单/条件单查询与撤销、POST /emergency/close-all、POST /emergency/close-position,仅监听 127.0.0.1。
|
||||
|
||||
与仓库内四个策略/监控目录一一对应时,典型用法(各目录自己的 .env 里已有密钥;子代理用环境变量 PORT,勿与 Flask 的 APP_PORT 相同):
|
||||
与仓库内三个策略/监控目录一一对应时,典型用法(各目录自己的 .env 里已有密钥;子代理用环境变量 PORT,勿与 Flask 的 APP_PORT 相同):
|
||||
EXCHANGE=binance → crypto_monitor_binance(BINANCE_*)
|
||||
EXCHANGE=okx → crypto_monitor_okx(OKX_*)
|
||||
EXCHANGE=gate → crypto_monitor_gate / crypto_monitor_gate_bot(GATE_*)
|
||||
EXCHANGE=gate → crypto_monitor_gate(GATE_*)
|
||||
|
||||
环境变量:
|
||||
EXCHANGE binance(默认)| okx | gate
|
||||
PORT 默认 15200(与 crypto_monitor_* 的 Flask APP_PORT 错开;中控默认聚合 15200–15203)
|
||||
PORT 默认 15200(与 crypto_monitor_* 的 Flask APP_PORT 错开;中控默认聚合 15200–15202)
|
||||
HOST 默认 127.0.0.1
|
||||
CONTROL_TOKEN 可选;请求头 X-Control-Token
|
||||
|
||||
@@ -158,7 +158,9 @@ def _make_exchange() -> Any:
|
||||
secret = (os.getenv("GATE_API_SECRET") or "").strip()
|
||||
if not key or not secret:
|
||||
raise RuntimeError("缺少 GATE_API_KEY / GATE_API_SECRET")
|
||||
ex = ccxt.gateio(
|
||||
from lib.exchange.gate_ccxt_lib import gate_ccxt_class
|
||||
|
||||
ex = gate_ccxt_class()(
|
||||
{
|
||||
"apiKey": key,
|
||||
"secret": secret,
|
||||
@@ -392,7 +394,7 @@ def _position_price_fmt(ex: Any, symbol: str, price: float | None) -> tuple[floa
|
||||
|
||||
|
||||
def _position_entry_price(p: dict[str, Any]) -> float | None:
|
||||
"""四所 ccxt 持仓统一解析开仓均价(Binance/OKX/Gate 字段名不一致)。"""
|
||||
"""三所 ccxt 持仓统一解析开仓均价(Binance/OKX/Gate 字段名不一致)。"""
|
||||
return parse_position_entry_price(p)
|
||||
|
||||
|
||||
@@ -406,7 +408,7 @@ def _position_contract_size(ex: Any, symbol: str) -> float:
|
||||
|
||||
|
||||
def _position_mark_price(p: dict[str, Any]) -> float | None:
|
||||
"""四所 ccxt 持仓统一解析标记价(与实例 parse_ccxt_position_metrics 一致)。"""
|
||||
"""三所 ccxt 持仓统一解析标记价(与实例 parse_ccxt_position_metrics 一致)。"""
|
||||
return parse_position_mark_price(p)
|
||||
|
||||
|
||||
@@ -740,7 +742,7 @@ def place_tpsl_orders(
|
||||
body: PlaceTpslBody,
|
||||
x_control_token: str | None = Header(default=None, alias="X-Control-Token"),
|
||||
):
|
||||
"""先撤该合约全部条件单,再挂止盈+止损(与四实例策略逻辑一致)。"""
|
||||
"""先撤该合约全部条件单,再挂止盈+止损(与三实例策略逻辑一致)。"""
|
||||
_check_token(x_control_token)
|
||||
sym = (body.symbol or "").strip()
|
||||
side = (body.side or "").strip().lower()
|
||||
@@ -866,7 +868,7 @@ def emergency_close_position(
|
||||
for p in raw:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
if (p.get("symbol") or "").strip() != sym:
|
||||
if not symbols_match(sym, (p.get("symbol") or "").strip()):
|
||||
continue
|
||||
c = _position_contracts(p)
|
||||
if abs(c) < 1e-12:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* PM2:中控 hub + 四路子代理 agent(一次启动全部)
|
||||
* PM2:中控 hub + 三路子代理 agent(一次启动全部)
|
||||
*
|
||||
* 前置:
|
||||
* cd manual_trading_hub
|
||||
@@ -49,7 +49,6 @@ module.exports = {
|
||||
agentApp("manual-agent-binance", "crypto_monitor_binance", "binance", 15200),
|
||||
agentApp("manual-agent-okx", "crypto_monitor_okx", "okx", 15201),
|
||||
agentApp("manual-agent-gate", "crypto_monitor_gate", "gate", 15202),
|
||||
agentApp("manual-agent-gate-bot", "crypto_monitor_gate_bot", "gate", 15203),
|
||||
{
|
||||
name: "manual-trading-hub",
|
||||
cwd: HUB_DIR,
|
||||
|
||||