修改币种精度

This commit is contained in:
dekun
2026-05-14 11:30:52 +08:00
parent 8290bbc060
commit 7978d40a74
14 changed files with 1254 additions and 263 deletions
+3 -2
View File
@@ -37,8 +37,9 @@ BTC_LEVERAGE=10
ALT_LEVERAGE=5
# 交易日重置小时(北京时间)
TRADING_DAY_RESET_HOUR=8
# 整点前禁止新开仓:true=启用(默认),false=关闭(仍可保留 8 点作为交易日划分)
TRADING_DAY_RESET_OPEN_GUARD_ENABLED=true
# Gate 平仓历史:同步「趋势回调」交易记录与交易所已实现盈亏(北京日期 00:00 起,与 APP_TIMEZONE 一致);留空则从近 90 天拉取
# EXCHANGE_POSITION_SYNC_FROM_BJ=2026-05-14
# EXCHANGE_POSITION_HISTORY_LIMIT=200
# 是否开启 Gate 实盘下单(false=只做本地流程,true=真实下单)
LIVE_TRADING_ENABLED=true
+514 -15
View File
@@ -93,6 +93,11 @@ TRADING_DAY_RESET_OPEN_GUARD_ENABLED = os.getenv(
"TRADING_DAY_RESET_OPEN_GUARD_ENABLED", "true"
).lower() in ("1", "true", "yes", "on")
APP_TIMEZONE = os.getenv("APP_TIMEZONE", "Asia/Shanghai")
# 交易所「平仓历史」同步:自北京日期 00:00 起(与 APP_TIMEZONE 一致);空则取最近 90 天
EXCHANGE_POSITION_SYNC_FROM_BJ = (os.getenv("EXCHANGE_POSITION_SYNC_FROM_BJ") or "").strip()
EXCHANGE_POSITION_HISTORY_LIMIT = max(50, min(1000, int(os.getenv("EXCHANGE_POSITION_HISTORY_LIMIT", "200"))))
_LAST_POSITION_HISTORY_SYNC_AT = 0.0
def _resolve_app_tz():
@@ -1182,6 +1187,26 @@ def init_db():
try:
c.execute("ALTER TABLE trade_records ADD COLUMN reviewed_entry_reason TEXT")
except: pass
try:
c.execute("ALTER TABLE trade_records ADD COLUMN trend_plan_id INTEGER")
except Exception:
pass
try:
c.execute("ALTER TABLE trade_records ADD COLUMN exchange_realized_pnl REAL")
except Exception:
pass
try:
c.execute("ALTER TABLE trade_records ADD COLUMN exchange_opened_at TEXT")
except Exception:
pass
try:
c.execute("ALTER TABLE trade_records ADD COLUMN exchange_closed_at TEXT")
except Exception:
pass
try:
c.execute("ALTER TABLE trade_records ADD COLUMN exchange_sync_key TEXT")
except Exception:
pass
try:
c.execute("ALTER TABLE journal_entries ADD COLUMN mood_ai_score INTEGER")
except: pass
@@ -1286,6 +1311,36 @@ def init_db():
)"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS trend_pullback_preview_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
preview_id TEXT NOT NULL UNIQUE,
symbol TEXT NOT NULL,
exchange_symbol TEXT NOT NULL,
direction TEXT NOT NULL,
leverage INTEGER NOT NULL,
stop_loss REAL NOT NULL,
add_upper REAL NOT NULL,
take_profit REAL NOT NULL,
risk_percent REAL NOT NULL,
snapshot_available_usdt REAL NOT NULL,
snapshot_at TEXT,
live_price_ref REAL,
plan_margin_capital REAL,
target_order_amount REAL,
first_order_amount REAL,
remainder_total REAL,
dca_legs INTEGER,
per_leg_amount REAL,
grid_prices_json TEXT,
leg_amounts_json TEXT,
expires_at_ms INTEGER NOT NULL,
preview_created_at TEXT,
outcome TEXT DEFAULT 'open',
executed_plan_id INTEGER
)"""
)
conn.commit()
conn.close()
@@ -1710,9 +1765,57 @@ def to_effective_trade_dict(row):
item["effective_hold_seconds"] = get_effective_trade_field(row, "reviewed_hold_seconds", "hold_seconds", item.get("hold_seconds"))
er_eff = get_effective_trade_field(row, "reviewed_entry_reason", "entry_reason", item.get("entry_reason"))
item["effective_entry_reason"] = (str(er_eff).strip() if er_eff is not None else "") or ""
mt = (item.get("monitor_type") or "").strip()
ex_pnl = item.get("exchange_realized_pnl")
ex_open = item.get("exchange_opened_at")
ex_close = item.get("exchange_closed_at")
if mt == MONITOR_TYPE_TREND and ex_pnl is not None and str(ex_pnl).strip() != "":
try:
item["display_pnl_amount"] = float(ex_pnl)
except (TypeError, ValueError):
item["display_pnl_amount"] = float(item.get("effective_pnl_amount") or 0)
item["display_pnl_source"] = "exchange"
eo = (str(ex_open).strip() if ex_open else "") or item.get("effective_opened_at") or ""
ec = (str(ex_close).strip() if ex_close else "") or item.get("effective_closed_at") or ""
item["display_opened_at"] = eo[:16] if eo else "-"
item["display_closed_at"] = ec[:16] if ec else "-"
else:
try:
item["display_pnl_amount"] = float(item.get("effective_pnl_amount") or 0)
except (TypeError, ValueError):
item["display_pnl_amount"] = 0.0
item["display_pnl_source"] = "local"
eo = item.get("effective_opened_at") or ""
ec = item.get("effective_closed_at") or ""
item["display_opened_at"] = (eo[:16] if eo else "-")
item["display_closed_at"] = (ec[:16] if ec else "-")
return item
def format_money_usdt(value):
"""资金类展示:固定两位小数(USDT)。"""
if value is None or value == "":
return ""
try:
return f"{round(float(value), 2):.2f}"
except (TypeError, ValueError):
return ""
def _exchange_unified_symbol_for_format(symbol_str):
if not symbol_str:
return None
s = str(symbol_str).strip()
if not s:
return None
try:
if ":" in s or "/" in s:
return normalize_exchange_symbol(s)
return normalize_exchange_symbol(f"{s}/USDT")
except Exception:
return None
def format_price_for_symbol(symbol, value):
if value in (None, ""):
return "-"
@@ -1722,8 +1825,14 @@ def format_price_for_symbol(symbol, value):
return str(value)
if v == 0:
return "0"
sym = _exchange_unified_symbol_for_format(symbol)
if sym and exchange_private_api_configured():
try:
ensure_markets_loaded()
return str(exchange.price_to_precision(sym, v))
except Exception:
pass
av = abs(v)
# 根据币价量级动态精度:低价币保留更多小数,高价币减少噪音位数
if av >= 10000:
d = 2
elif av >= 100:
@@ -1740,6 +1849,70 @@ def format_price_for_symbol(symbol, value):
return text.rstrip("0").rstrip(".") if "." in text else text
def format_amount_for_symbol(symbol, value):
"""合约张数等:尽量与交易所 amount 精度一致。"""
if value in (None, ""):
return "-"
try:
v = float(value)
except Exception:
return str(value)
sym = _exchange_unified_symbol_for_format(symbol)
if sym and exchange_private_api_configured():
try:
ensure_markets_loaded()
return str(exchange.amount_to_precision(sym, v))
except Exception:
pass
text = f"{v:.8f}"
return text.rstrip("0").rstrip(".") if "." in text else text
def insert_trend_preview_snapshot(conn, preview_id, created, exp_ms, pl):
"""生成预览成功后归档一条快照(与 trend_pullback_previews 同参)。"""
conn.execute(
"""INSERT INTO trend_pullback_preview_snapshots (
preview_id,symbol,exchange_symbol,direction,leverage,stop_loss,add_upper,take_profit,risk_percent,
snapshot_available_usdt,snapshot_at,live_price_ref,plan_margin_capital,target_order_amount,first_order_amount,remainder_total,
dca_legs,per_leg_amount,grid_prices_json,leg_amounts_json,expires_at_ms,preview_created_at
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
preview_id,
pl["symbol"],
pl["exchange_symbol"],
pl["direction"],
pl["leverage"],
pl["stop_loss"],
pl["add_upper"],
pl["take_profit"],
pl["risk_percent"],
pl["snapshot_available_usdt"],
pl["snapshot_at"],
pl["live_price_ref"],
pl["plan_margin_capital"],
pl["target_order_amount"],
pl["first_order_amount"],
pl["remainder_total"],
pl["dca_legs"],
pl["per_leg_amount"],
pl["grid_prices_json"],
pl["leg_amounts_json"],
exp_ms,
created,
),
)
def preview_snapshot_outcome_label(outcome):
o = (outcome or "").strip().lower()
return {
"open": "待确认",
"executed": "已执行",
"cancelled": "已取消",
"expired": "已过期",
}.get(o, outcome or "-")
def format_hold_minutes(minutes):
if not minutes:
return "0分钟"
@@ -1887,6 +2060,7 @@ def insert_trade_record(
closed_at=None,
closed_at_ms=None,
exchange_trade_id=None,
trend_plan_id=None,
):
hold_minutes = calc_hold_minutes(hold_seconds)
open_ts = opened_at or app_now_str()
@@ -1894,12 +2068,12 @@ def insert_trade_record(
open_ts_ms = _to_ms_with_fallback(opened_at_ms, open_ts)
close_ts_ms = _to_ms_with_fallback(closed_at_ms, close_ts)
conn.execute(
"INSERT INTO trade_records (symbol,monitor_type,direction,trigger_price,stop_loss,initial_stop_loss,take_profit,margin_capital,leverage,pnl_amount,hold_seconds,trade_style,risk_amount,planned_rr,actual_rr,hold_minutes,opened_at,opened_at_ms,closed_at,closed_at_ms,result,miss_reason,exchange_trade_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"INSERT INTO trade_records (symbol,monitor_type,direction,trigger_price,stop_loss,initial_stop_loss,take_profit,margin_capital,leverage,pnl_amount,hold_seconds,trade_style,risk_amount,planned_rr,actual_rr,hold_minutes,opened_at,opened_at_ms,closed_at,closed_at_ms,result,miss_reason,exchange_trade_id,trend_plan_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
symbol, monitor_type, direction, trigger_price, stop_loss, initial_stop_loss, take_profit,
margin_capital, leverage, pnl_amount, hold_seconds,
trade_style, risk_amount, planned_rr, actual_rr, hold_minutes,
open_ts, open_ts_ms, close_ts, close_ts_ms, result, miss_reason, exchange_trade_id
open_ts, open_ts_ms, close_ts, close_ts_ms, result, miss_reason, exchange_trade_id, trend_plan_id
)
)
@@ -2395,6 +2569,15 @@ def precheck_trend_pullback_start(conn):
def _trend_cleanup_stale_previews(conn):
ms = int(time.time() * 1000)
stale = conn.execute("SELECT id FROM trend_pullback_previews WHERE expires_at_ms < ?", (ms,)).fetchall()
for row in stale:
try:
conn.execute(
"UPDATE trend_pullback_preview_snapshots SET outcome='expired' WHERE preview_id=? AND outcome='open'",
(row["id"],),
)
except Exception:
pass
conn.execute("DELETE FROM trend_pullback_previews WHERE expires_at_ms < ?", (ms,))
@@ -3030,6 +3213,236 @@ def get_live_position_exchange_metrics(exchange_symbol, direction):
return parse_ccxt_position_metrics(p)
def _unified_symbol_for_match(symbol_str):
"""统一 BTC/USDT:USDT 与 BTC/USDT 便于与 trade_records.symbol 比对。"""
x = (symbol_str or "").strip().upper()
if ":" in x:
x = x.split(":")[0]
return x
def exchange_position_sync_since_ms():
"""Gate fetch_positions_history 的 since(毫秒,含当日 0 点)。"""
s = EXCHANGE_POSITION_SYNC_FROM_BJ
if s:
for fmt, ln in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d", 10)):
try:
chunk = s[:ln] if len(s) >= ln else s[:10]
dt = datetime.strptime(chunk, fmt)
aware = dt.replace(tzinfo=APP_TZ)
return int(aware.timestamp() * 1000)
except Exception:
continue
dt0 = app_now() - timedelta(days=90)
try:
aware0 = datetime(dt0.year, dt0.month, dt0.day, 0, 0, 0, tzinfo=APP_TZ)
except Exception:
aware0 = datetime.now(APP_TZ)
return int(aware0.timestamp() * 1000)
def _coerce_ts_ms(val):
if val is None or val == "":
return None
try:
v = float(val)
except (TypeError, ValueError):
return None
if v > 1e12:
return int(v)
if v > 1e10:
return int(v)
return int(v * 1000.0)
def _normalize_gate_position_history_entry(p):
if not p or not isinstance(p, dict):
return None
info = p.get("info") or {}
sym = p.get("symbol") or ""
side = (p.get("side") or "").strip().lower()
if side not in ("long", "short"):
sz = info.get("accum_size") if info.get("accum_size") is not None else info.get("size")
try:
szf = float(sz)
if szf > 0:
side = "long"
elif szf < 0:
side = "short"
except (TypeError, ValueError):
side = ""
rp = p.get("realizedPnl")
if rp is None:
rp = info.get("pnl")
try:
rp_f = float(rp) if rp is not None and str(rp).strip() != "" else None
except (TypeError, ValueError):
rp_f = None
close_ms = _coerce_ts_ms(p.get("lastUpdateTimestamp"))
if close_ms is None:
close_ms = _coerce_ts_ms(info.get("time"))
open_ms = _coerce_ts_ms(p.get("timestamp"))
if open_ms is None:
open_ms = _coerce_ts_ms(info.get("first_open_time"))
c_raw = str(info.get("contract") or "").strip()
t_raw = info.get("time")
sync_key = f"{c_raw}|{t_raw}|{side}"
return {
"symbol_u": _unified_symbol_for_match(sym),
"side": side,
"close_ms": close_ms,
"open_ms": open_ms,
"pnl": rp_f,
"sync_key": sync_key,
}
def fetch_gate_positions_close_history():
if not exchange_private_api_configured():
return []
ensure_markets_loaded()
since_ms = exchange_position_sync_since_ms()
try:
rows = exchange.fetch_positions_history(
None,
since=int(since_ms),
limit=int(EXCHANGE_POSITION_HISTORY_LIMIT),
params={"settle": "usdt"},
)
except Exception:
try:
rows = exchange.fetch_positions_history(
None,
since=int(since_ms),
limit=int(EXCHANGE_POSITION_HISTORY_LIMIT),
params={},
)
except Exception:
return []
out = []
for p in rows or []:
h = _normalize_gate_position_history_entry(p)
if h and h["close_ms"] and h["side"] in ("long", "short") and h["symbol_u"]:
out.append(h)
return out
def sync_trend_trade_records_from_exchange(conn):
global _LAST_POSITION_HISTORY_SYNC_AT
if not exchange_private_api_configured():
return
now = time.time()
if now - _LAST_POSITION_HISTORY_SYNC_AT < 25.0:
return
try:
hist = fetch_gate_positions_close_history()
except Exception:
return
if not hist:
_LAST_POSITION_HISTORY_SYNC_AT = now
return
candidates = conn.execute(
"""
SELECT id, symbol, direction, closed_at, opened_at, trend_plan_id, exchange_sync_key
FROM trade_records
WHERE monitor_type = ? AND (exchange_sync_key IS NULL OR TRIM(exchange_sync_key) = '')
ORDER BY id DESC
LIMIT 120
""",
(MONITOR_TYPE_TREND,),
).fetchall()
if not candidates:
_LAST_POSITION_HISTORY_SYNC_AT = now
return
used = set()
for tr in candidates:
tid = None
if "trend_plan_id" in tr.keys() and tr["trend_plan_id"]:
try:
tid = int(tr["trend_plan_id"])
except (TypeError, ValueError):
tid = None
plan_open_ms = None
if tid:
prow = conn.execute("SELECT opened_at FROM trend_pullback_plans WHERE id=?", (tid,)).fetchone()
if prow and prow["opened_at"]:
plan_open_ms = opened_at_str_to_ms(prow["opened_at"])
close_ms_trade = opened_at_str_to_ms(tr["closed_at"]) or opened_at_str_to_ms(tr["opened_at"])
if close_ms_trade is None:
continue
best = None
best_d = None
for h in hist:
sk = h["sync_key"]
if not sk or sk in used:
continue
if h["symbol_u"] != _unified_symbol_for_match(tr["symbol"]):
continue
if h["side"] != (tr["direction"] or "long").strip().lower():
continue
cm = h["close_ms"]
if cm is None:
continue
if plan_open_ms is not None:
if cm < plan_open_ms - 15 * 60 * 1000:
continue
if cm > plan_open_ms + 15 * 86400 * 1000:
continue
else:
if abs(cm - close_ms_trade) > 3 * 86400 * 1000:
continue
d = abs(cm - close_ms_trade)
if best_d is None or d < best_d:
best_d = d
best = h
if best is None or best_d is None or best_d > 25 * 60 * 1000:
continue
sk = best["sync_key"]
if sk in used:
continue
eo = ms_to_app_local_str(best["open_ms"]) if best.get("open_ms") else None
ec = ms_to_app_local_str(best["close_ms"]) if best.get("close_ms") else None
pnl_val = best.get("pnl")
if pnl_val is None:
pnl_val = 0.0
conn.execute(
"""
UPDATE trade_records
SET exchange_realized_pnl = ?, exchange_opened_at = ?, exchange_closed_at = ?, exchange_sync_key = ?
WHERE id = ?
""",
(float(pnl_val), eo, ec, sk, int(tr["id"])),
)
used.add(sk)
_LAST_POSITION_HISTORY_SYNC_AT = now
conn.commit()
def trend_plan_history_status_label(status):
s = (status or "").strip().lower()
return {
"stopped_tp": "止盈结束",
"stopped_sl": "止损结束",
"stopped_manual": "手动结束",
}.get(s, status or "-")
def enrich_active_trend_plan_row(row):
d = row_to_dict(row)
ex_sym = d.get("exchange_symbol") or normalize_exchange_symbol(d.get("symbol") or "")
direction = (d.get("direction") or "long").lower()
m = get_live_position_exchange_metrics(ex_sym, direction)
if m and m.get("unrealized_pnl") is not None:
d["floating_pnl"] = float(m["unrealized_pnl"])
else:
d["floating_pnl"] = None
if m and m.get("mark_price") is not None:
d["floating_mark"] = float(m["mark_price"])
else:
d["floating_mark"] = None
return d
def opened_at_str_to_ms(opened_at_str):
if not opened_at_str:
return None
@@ -3795,6 +4208,7 @@ def _trend_finalize_plan(conn, row, result_label, exit_price, closed_at=None):
result=res,
opened_at=opened_at,
closed_at=closed_at,
trend_plan_id=int(row["id"]),
)
st = "stopped_tp" if result_label == "止盈" else ("stopped_sl" if result_label == "止损" else "stopped_manual")
conn.execute(
@@ -4417,9 +4831,9 @@ def render_main_page(page="trade"):
local_current_capital = float(session_row["current_capital"])
funding_capital, trading_capital = get_exchange_capitals()
# 资金账户:仅展示交易所读取结果(含 0)。不可用 TOTAL_CAPITAL 兜底,否则会与实盘不符。
funding_usdt = round(funding_capital, 4) if funding_capital is not None else None
current_capital = round(trading_capital, 4) if trading_capital is not None else round(local_current_capital, 4)
recommended_capital = get_recommended_capital(current_capital)
funding_usdt = round(funding_capital, 2) if funding_capital is not None else None
current_capital = round(trading_capital, 2) if trading_capital is not None else round(local_current_capital, 2)
recommended_capital = round(get_recommended_capital(current_capital), 2)
key_list = conn.execute("SELECT * FROM key_monitors").fetchall()
key_history = conn.execute("SELECT * FROM key_monitor_history ORDER BY id DESC LIMIT 80").fetchall()
stats_bundle = compute_stats_bundle(conn, trading_day, now)
@@ -4427,6 +4841,11 @@ def render_main_page(page="trade"):
order_list = []
for o in raw_order_list:
order_list.append(enrich_order_item(row_to_dict(o), current_capital))
if page in ("trade", "records", "plan_history"):
try:
sync_trend_trade_records_from_exchange(conn)
except Exception:
pass
raw_records = conn.execute("SELECT * FROM trade_records ORDER BY id DESC").fetchall()
records = [to_effective_trade_dict(r) for r in raw_records]
total = len(records)
@@ -4443,9 +4862,27 @@ def render_main_page(page="trade"):
trend_active = conn.execute(
"SELECT COUNT(*) FROM trend_pullback_plans WHERE status='active'"
).fetchone()[0]
trend_plans = conn.execute(
trend_plans_raw = conn.execute(
"SELECT * FROM trend_pullback_plans WHERE status='active' ORDER BY id DESC"
).fetchall()
trend_plans = [enrich_active_trend_plan_row(r) for r in trend_plans_raw]
plan_history = []
preview_snapshots = []
if page == "plan_history":
plan_history_raw = conn.execute(
"SELECT * FROM trend_pullback_plans WHERE status != 'active' ORDER BY id DESC LIMIT 100"
).fetchall()
for pr in plan_history_raw:
pd = row_to_dict(pr)
pd["status_label"] = trend_plan_history_status_label(pd.get("status"))
plan_history.append(pd)
snap_rows = conn.execute(
"SELECT * FROM trend_pullback_preview_snapshots ORDER BY id DESC LIMIT 150"
).fetchall()
for sr in snap_rows:
sd = row_to_dict(sr)
sd["outcome_label"] = preview_snapshot_outcome_label(sd.get("outcome"))
preview_snapshots.append(sd)
can_trade = (
trading_day_reset_allows_new_open(now)
and active_count == 0
@@ -4508,6 +4945,9 @@ def render_main_page(page="trade"):
active_count=active_count,
can_trade=can_trade,
trend_plans=trend_plans,
plan_history=plan_history,
preview_snapshots=preview_snapshots,
exchange_sync_from_label=(EXCHANGE_POSITION_SYNC_FROM_BJ or "最近90天"),
trend_pullback_dca_legs=TREND_PULLBACK_DCA_LEGS,
trend_pullback_preview_ttl=TREND_PULLBACK_PREVIEW_TTL_SECONDS,
trend_preview=trend_preview,
@@ -4518,13 +4958,15 @@ def render_main_page(page="trade"):
trend_preview_max_drift_pct=TREND_PREVIEW_MAX_BALANCE_DRIFT_PCT,
focus_key_id=(key_list[0]["id"] if key_list else None),
focus_order_id=(order_list[0]["id"] if order_list else None),
data_export_version=2,
data_export_version=3,
key_alert_max_times=KEY_ALERT_MAX_TIMES,
risk_percent=RISK_PERCENT,
breakeven_rr_trigger=BREAKEVEN_RR_TRIGGER,
breakeven_offset_pct=BREAKEVEN_OFFSET_PCT,
occupied_miss_total=occupied_miss_total,
price_fmt=format_price_for_symbol,
amt_fmt=format_amount_for_symbol,
money_fmt=format_money_usdt,
entry_reason_options=list(ENTRY_REASON_OPTIONS),
entry_reason_other_value=ENTRY_REASON_OTHER,
exchange_display=EXCHANGE_DISPLAY_NAME,
@@ -4555,6 +4997,25 @@ def stats_page():
return render_main_page("stats")
@app.route("/plan_history")
@login_required
def plan_history_page():
return render_main_page("plan_history")
@app.route("/api/preview_snapshot/<int:sid>")
@login_required
def api_preview_snapshot(sid):
conn = get_db()
row = conn.execute("SELECT * FROM trend_pullback_preview_snapshots WHERE id=?", (sid,)).fetchone()
conn.close()
if not row:
return jsonify({"ok": False, "msg": "not_found"}), 404
d = row_to_dict(row)
d["outcome_label"] = preview_snapshot_outcome_label(d.get("outcome"))
return jsonify({"ok": True, "snapshot": d})
@app.route("/api/account_snapshot")
@login_required
def api_account_snapshot():
@@ -4564,9 +5025,9 @@ def api_account_snapshot():
session_row = ensure_session(conn, trading_day)
local_current_capital = float(session_row["current_capital"])
funding_capital, trading_capital = get_exchange_capitals(force=True)
funding_usdt = round(funding_capital, 4) if funding_capital is not None else None
current_capital = round(trading_capital, 4) if trading_capital is not None else round(local_current_capital, 4)
recommended_capital = get_recommended_capital(current_capital)
funding_usdt = round(funding_capital, 2) if funding_capital is not None else None
current_capital = round(trading_capital, 2) if trading_capital is not None else round(local_current_capital, 2)
recommended_capital = round(get_recommended_capital(current_capital), 2)
active_count = conn.execute("SELECT COUNT(*) FROM order_monitors WHERE status='active'").fetchone()[0]
conn.close()
can_trade = trading_day_reset_allows_new_open(now) and active_count == 0
@@ -4574,7 +5035,7 @@ def api_account_snapshot():
return jsonify({
"funding_usdt": funding_usdt,
"current_capital": current_capital,
"available_trading_usdt": round(available_trading_usdt, 4) if available_trading_usdt is not None else None,
"available_trading_usdt": round(available_trading_usdt, 2) if available_trading_usdt is not None else None,
"recommended_capital": recommended_capital,
"active_count": active_count,
"can_trade": can_trade,
@@ -5366,6 +5827,7 @@ def preview_trend_pullback():
created,
),
)
insert_trend_preview_snapshot(conn, pid, created, exp_ms, payload)
conn.commit()
conn.close()
flash(f"预览已生成,有效期 {TREND_PULLBACK_PREVIEW_TTL_SECONDS} 秒,请核对后点击「确认执行」。")
@@ -5444,7 +5906,7 @@ def execute_trend_pullback():
trading_day = get_trading_day(now)
opened_at = app_now_str()
opened_ms = _to_ms_with_fallback(None, opened_at)
conn.execute(
cur = conn.execute(
"""INSERT INTO trend_pullback_plans (
status,symbol,exchange_symbol,direction,leverage,stop_loss,add_upper,take_profit,risk_percent,
snapshot_available_usdt,snapshot_at,plan_margin_capital,target_order_amount,first_order_amount,remainder_total,
@@ -5481,11 +5943,16 @@ def execute_trend_pullback():
f"预览ID:{pid[:8]}",
),
)
new_plan_id = int(cur.lastrowid)
conn.execute(
"UPDATE trend_pullback_preview_snapshots SET outcome='executed', executed_plan_id=? WHERE preview_id=?",
(new_plan_id, pid),
)
conn.execute("DELETE FROM trend_pullback_previews WHERE id=?", (pid,))
conn.commit()
conn.close()
flash(
f"趋势回调已执行:可用余额(执行时){round(snap, 4)}U;计划保证金约 {round(margin_plan, 4)}U"
f"趋势回调已执行:可用余额(执行时){round(snap, 2)}U;计划保证金约 {round(margin_plan, 2)}U"
f"总张数约 {target_amt},首仓 {first_amt},补仓 {n_legs} 档;已挂交易所止损,止盈由程序监控。"
)
return redirect(url_for("trade_page"))
@@ -5497,6 +5964,10 @@ def cancel_trend_pullback_preview():
pid = (request.form.get("preview_id") or "").strip()
conn = get_db()
if pid:
conn.execute(
"UPDATE trend_pullback_preview_snapshots SET outcome='cancelled' WHERE preview_id=? AND outcome='open'",
(pid,),
)
conn.execute("DELETE FROM trend_pullback_previews WHERE id=?", (pid,))
conn.commit()
conn.close()
@@ -5546,6 +6017,28 @@ def stop_trend_pullback(pid):
return redirect("/trade")
@app.route("/delete_trend_plan_history/<int:pid>", methods=["POST"])
@login_required
def delete_trend_plan_history(pid):
conn = get_db()
row = conn.execute("SELECT id, status FROM trend_pullback_plans WHERE id=?", (pid,)).fetchone()
if not row:
conn.close()
flash("计划不存在")
return redirect(request.referrer or url_for("plan_history_page"))
if (row["status"] or "").strip() == "active":
conn.close()
flash("运行中的计划请使用「结束计划」,不可从历史中删除")
return redirect(request.referrer or url_for("plan_history_page"))
conn.execute("DELETE FROM trade_records WHERE trend_plan_id=?", (pid,))
conn.execute("DELETE FROM trend_pullback_preview_snapshots WHERE executed_plan_id=?", (pid,))
conn.execute("DELETE FROM trend_pullback_plans WHERE id=?", (pid,))
conn.commit()
conn.close()
flash("已删除该计划历史及关联趋势交易记录(若有)")
return redirect(request.referrer or url_for("plan_history_page"))
@app.route("/delete_key_monitor/<int:kid>", methods=["POST"])
@login_required
def delete_key_monitor(kid):
@@ -5622,7 +6115,8 @@ def export_trade_records():
rows = conn.execute(
"SELECT id,symbol,monitor_type,direction,trigger_price,stop_loss,take_profit,margin_capital,leverage,"
"pnl_amount,hold_seconds,hold_minutes,opened_at,closed_at,result,miss_reason,"
"entry_reason,reviewed_entry_reason,created_at FROM trade_records ORDER BY id ASC"
"entry_reason,reviewed_entry_reason,created_at,trend_plan_id,exchange_realized_pnl,"
"exchange_opened_at,exchange_closed_at,exchange_sync_key FROM trade_records ORDER BY id ASC"
).fetchall()
conn.close()
head_base = [
@@ -5645,6 +6139,11 @@ def export_trade_records():
"entry_reason",
"reviewed_entry_reason",
"created_at",
"trend_plan_id",
"exchange_realized_pnl",
"exchange_opened_at",
"exchange_closed_at",
"exchange_sync_key",
]
head = head_base + ["开仓类型"]
data = []
+130 -36
View File
@@ -130,14 +130,14 @@
<div class="stat-item"><div class="label">开单次数</div><div class="value">{{ s.opens_count }}</div></div>
<div class="stat-item"><div class="label">平仓笔数</div><div class="value">{{ s.closed_count }}</div></div>
<div class="stat-item"><div class="label">胜率</div><div class="value">{% if s.win_rate_pct is not none %}{{ s.win_rate_pct }}%{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">净盈亏(U)</div><div class="value">{{ s.net_pnl_u }}</div></div>
<div class="stat-item"><div class="label">亏损额合计(U)</div><div class="value">{{ s.loss_sum_u }}</div></div>
<div class="stat-item"><div class="label">单笔最大亏损(U)</div><div class="value">{% if s.max_single_loss is not none %}{{ s.max_single_loss }}{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">单笔最大盈利(U)</div><div class="value">{% if s.max_single_profit is not none %}{{ s.max_single_profit }}{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">最大回撤(U)</div><div class="value">{{ s.max_drawdown_u }}</div></div>
<div class="stat-item"><div class="label">净盈亏(U)</div><div class="value">{{ money_fmt(s.net_pnl_u) }}</div></div>
<div class="stat-item"><div class="label">亏损额合计(U)</div><div class="value">{{ money_fmt(s.loss_sum_u) }}</div></div>
<div class="stat-item"><div class="label">单笔最大亏损(U)</div><div class="value">{% if s.max_single_loss is not none %}{{ money_fmt(s.max_single_loss) }}{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">单笔最大盈利(U)</div><div class="value">{% if s.max_single_profit is not none %}{{ money_fmt(s.max_single_profit) }}{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">最大回撤(U)</div><div class="value">{{ money_fmt(s.max_drawdown_u) }}</div></div>
<div class="stat-item"><div class="label">当前连续亏损笔数</div><div class="value">{{ s.consecutive_losses }}</div></div>
<div class="stat-item"><div class="label">最长连续亏损(交易日)</div><div class="value">{{ s.max_loss_streak_days }} 天</div></div>
<div class="stat-item"><div class="label">期内最大亏损日</div><div class="value">{% if s.worst_day %}{{ s.worst_day }}{{ s.worst_day_pnl }}U{% else %}-{% endif %}</div></div>
<div class="stat-item"><div class="label">期内最大亏损日</div><div class="value">{% if s.worst_day %}{{ s.worst_day }}{{ money_fmt(s.worst_day_pnl) }}U{% else %}-{% endif %}</div></div>
</div>
</div>
{% endmacro %}
@@ -149,12 +149,13 @@
<div class="top-nav">
<a href="/trade" class="{% if page == 'trade' %}active{% endif %}">交易执行</a>
<a href="/records" class="{% if page == 'records' %}active{% endif %}">交易记录</a>
<a href="/plan_history" class="{% if page == 'plan_history' %}active{% endif %}">计划历史</a>
<a href="/stats" class="{% if page == 'stats' %}active{% endif %}">统计分析</a>
</div>
{% with msg=get_flashed_messages() %}{% if msg %}<div class="flash">{{ msg[0] }}</div>{% endif %}{% endwith %}
<div class="export-bar">
<span style="color:#9aa">数据导出(v{{ data_export_version }} CSVUTF-8;交易记录含开仓类型列):</span>
<span style="color:#9aa">数据导出(v{{ data_export_version }} CSVUTF-8;交易记录含开仓类型列及交易所对齐字段):</span>
<a href="/export/trade_records">交易记录</a>
</div>
<div class="stat-box">
@@ -162,9 +163,9 @@
<div class="stat-item"><div class="label">总交易</div><div class="value">{{ total }}</div></div>
<div class="stat-item"><div class="label">错过次数</div><div class="value">{{ miss_count }}</div></div>
<div class="stat-item"><div class="label">胜率</div><div class="value">{{ rate }}%</div></div>
<div class="stat-item"><div class="label">资金账户(USDT)</div><div class="value" id="total-capital">{% if funding_usdt is not none %}{{ funding_usdt }}U{% else %}—{% endif %}</div></div>
<div class="stat-item"><div class="label">资金账户(USDT)</div><div class="value" id="total-capital">{% if funding_usdt is not none %}{{ money_fmt(funding_usdt) }}U{% else %}—{% endif %}</div></div>
<div class="stat-item"><div class="label">交易日</div><div class="value">{{ trading_day }}</div></div>
<div class="stat-item"><div class="label">当日资金(交易账户)</div><div class="value" id="current-capital">{{ current_capital }}U</div></div>
<div class="stat-item"><div class="label">当日资金(交易账户)</div><div class="value" id="current-capital">{{ money_fmt(current_capital) }}U</div></div>
</div>
<div class="rule-tip">实时价格更新时间:<span id="price-last-updated">--</span>(北京时间 UTC+8</div>
@@ -188,7 +189,7 @@
以损定仓:风险 {{ risk_percent }}% |移动保本:下单可勾选关闭;开启时 {{ breakeven_rr_trigger }}R 触发(每 1R 阶梯上移),偏移 {{ breakeven_offset_pct }}%
</div>
<div class="rule-tip">
划转:自动划转 {{ '开启' if auto_transfer_enabled else '关闭' }}(每天<strong>北京时间 {{ auto_transfer_bj_hour }}:00</strong>起该整点小时内尝试;账簿按 <strong>UTC 自然日</strong>去重;界面时间为北京;将 {{ auto_transfer_to }} 补足到 {{ auto_transfer_amount }}U,来自 {{ auto_transfer_from }}
划转:自动划转 {{ '开启' if auto_transfer_enabled else '关闭' }}(每天<strong>北京时间 {{ auto_transfer_bj_hour }}:00</strong>起该整点小时内尝试;账簿按 <strong>UTC 自然日</strong>去重;界面时间为北京;将 {{ auto_transfer_to }} 补足到 {{ money_fmt(auto_transfer_amount) }}U,来自 {{ auto_transfer_from }}
</div>
<form action="/manual_transfer" method="post" class="form-row">
<input name="amount" type="number" min="0.01" step="0.01" placeholder="手动划转金额U" required>
@@ -236,14 +237,14 @@
<div class="list-item">
<div><strong>{{ o.symbol }}</strong> | <span class="badge direction">{{ '做多' if o.direction == 'long' else '做空' }}</span></div>
<div>
风格:{{ o.trade_style or 'trend' }} | 风险:{{ o.risk_percent or '-' }}%≈{{ o.risk_amount or '-' }}U
| {% if o.breakeven_enabled %}移动保本:开 {{ o.breakeven_rr_trigger or '-' }}R→{{ o.breakeven_price or '-' }}{% else %}移动保本:关{% endif %}
风格:{{ o.trade_style or 'trend' }} | 风险:{{ o.risk_percent or '-' }}%≈{{ money_fmt(o.risk_amount) }}U
| {% if o.breakeven_enabled %}移动保本:开 {{ o.breakeven_rr_trigger or '-' }}R→{{ price_fmt(o.symbol, o.breakeven_price) }}{% else %}移动保本:关{% endif %}
<br>
成交:{{ o.trigger_price }} 止损:{{ o.stop_loss }} 止盈:{{ o.take_profit }}
成交:{{ price_fmt(o.symbol, o.trigger_price) }} 止损:{{ price_fmt(o.symbol, o.stop_loss) }} 止盈:{{ price_fmt(o.symbol, o.take_profit) }}
| 盈亏比:<span id="order-rr-{{ o.id }}">{% if o.rr_ratio is not none %}1:{{ '%.2f'|format(o.rr_ratio) }}{% else %}-{% endif %}</span>
| 现价:<span id="order-price-{{ o.id }}">-</span>
| 浮盈亏:<span id="order-pnl-{{ o.id }}">-</span>
| 计划基数:{{ o.margin_capital }}U | 所保证金:<span id="order-ex-margin-{{ o.id }}">-</span>
| 计划基数:{{ money_fmt(o.margin_capital) }}U | 所保证金:<span id="order-ex-margin-{{ o.id }}">-</span>
| 杠杆:{{ o.leverage }}x | 仓位占比:{{ o.position_ratio }}%
</div>
<a href="/del_order/{{ o.id }}" class="btn-del" onclick="return confirm('删除会触发手动平仓,继续?')">平仓</a>
@@ -282,15 +283,15 @@
</div>
<div style="font-size:.82rem;color:#cfd3ef;line-height:1.55;margin-bottom:10px">
{{ trend_preview.symbol }} {{ '做多' if trend_preview.direction == 'long' else '做空' }} {{ trend_preview.leverage }}x
预览可用快照 <strong>{{ trend_preview.snapshot_available_usdt }}</strong> U 参考价 {{ trend_preview.live_price_ref }}
计划保证金≈{{ trend_preview.plan_margin_capital }} U 总张≈{{ trend_preview.target_order_amount }}(首仓 {{ trend_preview.first_order_amount }} + 补仓 {{ trend_preview.remainder_total }}<br>
止损 {{ trend_preview.stop_loss }} 补仓上沿 {{ trend_preview.add_upper }} 止盈 {{ trend_preview.take_profit }} 风险比例 {{ trend_preview.risk_percent }}%
预览可用快照 <strong>{{ money_fmt(trend_preview.snapshot_available_usdt) }}</strong> U 参考价 {{ price_fmt(trend_preview.symbol, trend_preview.live_price_ref) }}
计划保证金≈{{ money_fmt(trend_preview.plan_margin_capital) }} U 总张≈{{ amt_fmt(trend_preview.symbol, trend_preview.target_order_amount) }}(首仓 {{ amt_fmt(trend_preview.symbol, trend_preview.first_order_amount) }} + 补仓 {{ amt_fmt(trend_preview.symbol, trend_preview.remainder_total) }}<br>
止损 {{ price_fmt(trend_preview.symbol, trend_preview.stop_loss) }} 补仓上沿 {{ price_fmt(trend_preview.symbol, trend_preview.add_upper) }} 止盈 {{ price_fmt(trend_preview.symbol, trend_preview.take_profit) }} 风险比例 {{ trend_preview.risk_percent }}%
</div>
<div class="table-wrap" style="margin-bottom:10px">
<table>
<tr><th>#</th><th>补仓触发价</th><th>该档张数</th></tr>
{% for row in trend_preview_levels %}
<tr><td>{{ row.i }}</td><td>{{ row.price }}</td><td>{{ row.contracts }}</td></tr>
<tr><td>{{ row.i }}</td><td>{{ price_fmt(trend_preview.symbol, row.price) }}</td><td>{{ amt_fmt(trend_preview.symbol, row.contracts) }}</td></tr>
{% endfor %}
</table>
</div>
@@ -331,9 +332,10 @@
<div class="list-item">
<div><strong>#{{ t.id }} {{ t.symbol }}</strong> | {{ '做多' if t.direction == 'long' else '做空' }} | {{ t.leverage }}x</div>
<div style="font-size:.82rem;color:#cfd3ef">
可用快照:{{ t.snapshot_available_usdt }}U | 计划保证金≈{{ t.plan_margin_capital }}U | 总张≈{{ t.target_order_amount }} 首仓{{ t.first_order_amount }} 补仓档{{ t.dca_legs }}
<br>止损:{{ t.stop_loss }} 补仓上沿:{{ t.add_upper }} 止盈:{{ t.take_profit }}
<br>均价:{{ t.avg_entry_price }} 已补仓:{{ t.legs_done }}/{{ t.dca_legs }}
可用快照:{{ money_fmt(t.snapshot_available_usdt) }}U | 计划保证金≈{{ money_fmt(t.plan_margin_capital) }}U | 总张≈{{ amt_fmt(t.symbol, t.target_order_amount) }} 首仓{{ amt_fmt(t.symbol, t.first_order_amount) }} 补仓档{{ t.dca_legs }}
<br>止损:{{ price_fmt(t.symbol, t.stop_loss) }} 补仓上沿:{{ price_fmt(t.symbol, t.add_upper) }} 止盈:{{ price_fmt(t.symbol, t.take_profit) }}
<br>均价:{{ price_fmt(t.symbol, t.avg_entry_price) }} 已补仓:{{ t.legs_done }}/{{ t.dca_legs }}
<br>浮盈亏(交易所): {% if t.floating_pnl is not none %}<span class="{{ 'pnl-profit' if t.floating_pnl > 0 else ('pnl-loss' if t.floating_pnl < 0 else '') }}">{{ money_fmt(t.floating_pnl) }} U</span>{% else %}—{% endif %}{% if t.floating_mark is not none %} 标记价: {{ price_fmt(t.symbol, t.floating_mark) }}{% endif %}
</div>
<a href="/stop_trend_pullback/{{ t.id }}" class="btn-del" onclick="return confirm('结束计划:市价平仓并撤掉该合约全部挂单,确定?')">结束计划</a>
</div>
@@ -349,25 +351,24 @@
<h2>交易记录</h2>
<div class="table-wrap">
<table>
<tr><th>品种</th><th>类型</th><th>方向</th><th>成交</th><th>止损</th><th>止盈</th><th>基数</th><th>杠杆</th><th>持仓分钟</th><th>开仓时间(北京)</th><th>平仓时间(北京)</th><th>盈亏U</th><th>结果</th><th>操作</th></tr>
<tr><th>品种</th><th>类型</th><th>方向</th><th>成交</th><th>止损</th><th>止盈</th><th>基数</th><th>杠杆</th><th>持仓分钟</th><th>开仓(展示)</th><th>平仓(展示)</th><th>盈亏U(展示)</th><th>结果</th><th>操作</th></tr>
{% for r in record %}
<tr id="trade-row-{{ r.id }}">
{% set pnl_val = (r.pnl_amount or 0)|float %}
<td>{{ r.symbol }}</td>
<td>{{ r.monitor_type }}</td>
<td><span class="badge {{ 'direction-long' if r.direction == 'long' else 'direction-short' }}">{{ '做多' if r.direction == 'long' else '做空' }}</span></td>
<td>{{ r.trigger_price }}</td>
<td>{{ price_fmt(r.symbol, r.trigger_price) }}</td>
{% set stop_show = r.effective_stop_loss or r.initial_stop_loss or r.stop_loss %}
{% set tp_show = r.effective_take_profit or r.take_profit %}
<td>{{ price_fmt(r.symbol, stop_show) }}</td>
<td>{{ price_fmt(r.symbol, tp_show) }}</td>
<td>{{ r.margin_capital or '-' }}</td>
<td>{% if r.margin_capital is not none and r.margin_capital != '' %}{{ money_fmt(r.margin_capital) }}{% else %}-{% endif %}</td>
<td>{{ r.leverage or '-' }}</td>
<td>{{ r.effective_hold_minutes or 0 }}</td>
<td>{{ (r.effective_opened_at or '-')[:16] }}</td>
<td>{{ (r.effective_closed_at or r.created_at or '-')[:16] }}</td>
{% set pnl_val = (r.effective_pnl_amount or 0)|float %}
<td><span class="{{ 'pnl-profit' if pnl_val > 0 else ('pnl-loss' if pnl_val < 0 else '') }}">{{ r.effective_pnl_amount or 0 }}</span></td>
<td>{{ r.display_opened_at }}</td>
<td>{{ r.display_closed_at }}</td>
{% set pnl_val = (r.display_pnl_amount or 0)|float %}
<td><span class="{{ 'pnl-profit' if pnl_val > 0 else ('pnl-loss' if pnl_val < 0 else '') }}">{{ money_fmt(r.display_pnl_amount) }}</span>{% if r.monitor_type == '趋势回调' and r.display_pnl_source == 'local' %}<span style="font-size:.68rem;color:#8892b0"></span>{% elif r.monitor_type == '趋势回调' and r.display_pnl_source == 'exchange' %}<span style="font-size:.68rem;color:#6ab88a"></span>{% endif %}</td>
<td>
{% set effective_result = r.effective_result %}
{% if effective_result in ["止盈","保本止盈","移动止盈"] %}<span class="badge profit">{{ effective_result }}</span>
@@ -407,6 +408,64 @@
{% endif %}
</div>
{% if page == 'plan_history' %}
<div class="card full" style="margin-bottom:12px">
<h2 style="margin-bottom:6px">已结束的趋势回调计划</h2>
<div class="rule-tip" style="margin-bottom:8px">删除将同时移除 <code>trend_plan_id</code> 关联的「趋势回调」交易记录及该计划对应的预览快照归档。交易所平仓同步起点(北京日期):<strong>{{ exchange_sync_from_label }}</strong><code>EXCHANGE_POSITION_SYNC_FROM_BJ</code>)。</div>
{% if plan_history and plan_history|length > 0 %}
<div class="table-wrap">
<table>
<tr><th>ID</th><th>品种</th><th>方向</th><th>杠杆</th><th>状态</th><th>结束</th><th>开仓时间</th><th>计划保证金≈</th><th>操作</th></tr>
{% for p in plan_history %}
<tr>
<td>{{ p.id }}</td>
<td>{{ p.symbol }}</td>
<td><span class="badge {{ 'direction-long' if p.direction == 'long' else 'direction-short' }}">{{ '做多' if p.direction == 'long' else '做空' }}</span></td>
<td>{{ p.leverage }}x</td>
<td>{{ p.status_label }}</td>
<td>{{ p.message or '-' }}</td>
<td>{{ (p.opened_at or '-')[:16] }}</td>
<td>{% if p.plan_margin_capital is not none %}{{ money_fmt(p.plan_margin_capital) }}{% else %}-{% endif %}</td>
<td>
<form action="{{ url_for('delete_trend_plan_history', pid=p.id) }}" method="post" style="display:inline" onsubmit="return confirm('确定删除该计划历史及关联趋势交易记录?');">
<button type="submit" class="table-del">删除</button>
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
{% else %}
<div class="rule-tip" style="color:#8892b0">暂无已结束的计划</div>
{% endif %}
</div>
<div class="card full" style="margin-bottom:12px">
<h2 style="margin-bottom:6px">预览快照(自本版本起留存)</h2>
<div class="rule-tip" style="margin-bottom:8px">每次「生成预览」自动归档;取消、过期或执行后仍可点开查看当时参数。执行后状态为「已执行」并带关联计划 ID。</div>
{% if preview_snapshots and preview_snapshots|length > 0 %}
<div class="table-wrap">
<table>
<tr><th>ID</th><th>时间</th><th>品种</th><th>方向</th><th>杠杆</th><th>状态</th><th>快照余额U</th><th>操作</th></tr>
{% for s in preview_snapshots %}
<tr>
<td>{{ s.id }}</td>
<td>{{ (s.preview_created_at or '-')[:16] }}</td>
<td>{{ s.symbol }}</td>
<td>{{ '多' if s.direction == 'long' else '空' }}</td>
<td>{{ s.leverage }}x</td>
<td>{{ s.outcome_label }}{% if s.executed_plan_id %} #{{ s.executed_plan_id }}{% endif %}</td>
<td>{{ money_fmt(s.snapshot_available_usdt) }}</td>
<td><button type="button" class="table-del" style="background:#1f3a5a;color:#8fc8ff" onclick="openPreviewSnapshotDetail({{ s.id }})">查看</button></td>
</tr>
{% endfor %}
</table>
</div>
{% else %}
<div class="rule-tip" style="color:#8892b0">暂无预览快照(新版本生成预览后将出现在此)</div>
{% endif %}
</div>
{% endif %}
{% if page == 'stats' %}
<div class="card stats-card full" id="stats-card">
<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">
@@ -484,6 +543,41 @@ function validateJournalEntryReason(){
function showImage(src){document.getElementById("bigImg").src=src;document.getElementById("imgModal").style.display="flex";}
function closeModal(){document.getElementById("imgModal").style.display="none";}
function forceCloseDetailModal(){document.getElementById("detailModal").style.display="none";}
function fmtU2(n){
if(n === null || n === undefined || n === "") return "-";
const x = Number(n);
if(Number.isNaN(x)) return String(n);
return x.toFixed(2);
}
function openPreviewSnapshotDetail(id){
fetch(`/api/preview_snapshot/${id}`).then(r=>r.json()).then(data=>{
if(!data.ok){ alert((data && data.msg) || "加载失败"); return; }
const s = data.snapshot;
const lines = [
`预览ID${s.preview_id || "-"}`,
`归档状态:${s.outcome_label || "-"}`,
`关联计划ID${s.executed_plan_id != null ? s.executed_plan_id : "-"}`,
"",
`${s.symbol || "-"} ${s.direction === "long" ? "做多" : "做空"} ${s.leverage || "-"}x`,
`可用快照U${fmtU2(s.snapshot_available_usdt)}`,
`参考价:${s.live_price_ref != null ? s.live_price_ref : "-"}`,
`计划保证金≈U${fmtU2(s.plan_margin_capital)}`,
`总张数:${s.target_order_amount != null ? s.target_order_amount : "-"}`,
`首仓/补仓余:${s.first_order_amount != null ? s.first_order_amount : "-"} / ${s.remainder_total != null ? s.remainder_total : "-"}`,
`补仓档数:${s.dca_legs != null ? s.dca_legs : "-"}`,
`止损 / 补仓上沿 / 止盈:${s.stop_loss} / ${s.add_upper} / ${s.take_profit}`,
`风险%${s.risk_percent != null ? s.risk_percent : "-"}`,
`网格价 JSON${s.grid_prices_json || "[]"}`,
`分档张数 JSON${s.leg_amounts_json || "[]"}`,
`创建时间:${s.preview_created_at || "-"}`,
`预览过期(ms)${s.expires_at_ms != null ? s.expires_at_ms : "-"}`,
].join("\n");
document.getElementById("detailTitle").innerText = `预览快照 #${id}`;
document.getElementById("detailBody").innerText = lines;
document.getElementById("detailImage").style.display = "none";
document.getElementById("detailModal").style.display = "flex";
}).catch(()=>{ alert("网络错误"); });
}
function closeDetailModal(e){if(e.target && e.target.id==="detailModal"){forceCloseDetailModal();}}
const journalCache = {};
@@ -1060,7 +1154,7 @@ function refreshPriceSnapshot(){
const mv = o.exchange_initial_margin;
const mn = (mv === null || mv === undefined || mv === "") ? NaN : Number(mv);
if(!Number.isNaN(mn)){
exM.innerText = `${mn.toFixed(4)}U`;
exM.innerText = `${mn.toFixed(2)}U`;
} else {
const prc = (typeof data.positions_raw_count === "number") ? data.positions_raw_count : null;
exM.innerText = (prc === 0) ? "无仓数据" : "-";
@@ -1068,7 +1162,7 @@ function refreshPriceSnapshot(){
}
const pnlEl = document.getElementById(`order-pnl-${o.id}`);
if(pnlEl){
pnlEl.innerText = `${formatSigned(o.float_pnl, 4)}U (${formatSigned(o.float_pct, 2)}%)`;
pnlEl.innerText = `${formatSigned(o.float_pnl, 2)}U (${formatSigned(o.float_pct, 2)}%)`;
pnlEl.classList.remove("price-up","price-down","price-flat");
if(Number(o.float_pnl) > 0) pnlEl.classList.add("price-up");
else if(Number(o.float_pnl) < 0) pnlEl.classList.add("price-down");
@@ -1102,7 +1196,7 @@ function refreshOrderDefaults(){
const fullEl = document.getElementById("use-full-margin");
const marginEl = document.getElementById("order-margin");
if(fullEl && marginEl && fullEl.checked){
const m = Math.max(latestAvailableUsdt * {{ full_margin_buffer_ratio }}, 0).toFixed(4);
const m = Math.max(latestAvailableUsdt * {{ full_margin_buffer_ratio }}, 0).toFixed(2);
marginEl.value = m;
}
}
@@ -1113,18 +1207,18 @@ function refreshAccountSnapshot(){
fetch("/api/account_snapshot").then(r=>r.json()).then(data=>{
if (typeof data.funding_usdt !== "undefined") {
const el = document.getElementById("total-capital");
if(el) el.innerText = (data.funding_usdt === null || data.funding_usdt === undefined) ? "—" : `${data.funding_usdt}U`;
if(el) el.innerText = (data.funding_usdt === null || data.funding_usdt === undefined) ? "—" : `${Number(data.funding_usdt).toFixed(2)}U`;
}
if (typeof data.current_capital !== "undefined") {
const el = document.getElementById("current-capital");
if(el) el.innerText = `${data.current_capital}U`;
if(el) el.innerText = `${Number(data.current_capital).toFixed(2)}U`;
}
if (typeof data.available_trading_usdt !== "undefined" && data.available_trading_usdt !== null) {
latestAvailableUsdt = Number(data.available_trading_usdt);
}
const canTradeText = data.can_trade ? "可开仓" : "不可开仓(有持仓或未到北京时间 {{ reset_hour }}:00";
const tip = document.getElementById("order-rule-tip");
const avail = (latestAvailableUsdt !== null && !Number.isNaN(latestAvailableUsdt)) ? `;交易账户可用约${latestAvailableUsdt}U` : "";
const avail = (latestAvailableUsdt !== null && !Number.isNaN(latestAvailableUsdt)) ? `;交易账户可用约${latestAvailableUsdt.toFixed(2)}U` : "";
if(tip){
tip.innerText = `规则:单仓;BTC {{ btc_leverage }}x / 山寨 {{ alt_leverage }}x${canTradeText}${avail}`;
}
@@ -1140,7 +1234,7 @@ if(fullMarginEl){
fullMarginEl.addEventListener("change", function(){
const marginEl = document.getElementById("order-margin");
if(marginEl && this.checked && latestAvailableUsdt !== null && !Number.isNaN(latestAvailableUsdt)){
marginEl.value = Math.max(latestAvailableUsdt * {{ full_margin_buffer_ratio }}, 0).toFixed(4);
marginEl.value = Math.max(latestAvailableUsdt * {{ full_margin_buffer_ratio }}, 0).toFixed(2);
}
});
}
@@ -50,6 +50,24 @@
用户可「取消预览」删除 `trend_pullback_previews` 中对应记录;过期记录会在新预览或页面加载时清理。
### 3.4 界面:计划历史与运行中浮动盈亏
- **计划历史(页顶卡片)**
- 仅展示 **`trend_pullback_plans` 中已结束的计划**`status != 'active'`,如止盈结束、止损结束、手动结束)。
- **不包含**仅存在于 `trend_pullback_previews`、从未「确认执行」的预览。
- 每行提供 **删除**:删除该计划行,并删除 `trade_records`**`trend_plan_id` 与之相同** 且类型为「趋势回调」的记录(用于与计划一一对应的新数据;历史旧行若无 `trend_plan_id` 则不会随删)。
- **运行中的计划(交易执行页)**
- 在计划摘要下方展示 **浮盈亏(交易所)**:来自 Gate 当前持仓接口的 **未实现盈亏**(及标记价,若可得);与本地按均价估算可能略有差异,以交易所为准便于对照。
### 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. 与「机器人下单监控」的差异
@@ -82,10 +100,16 @@
| `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`**已执行且运行中的计划;字段含快照可用余额、计划保证金、总张数、首仓张数、补仓 JSON、网格价 JSON、已补仓档数、均价、状态等。平仓结果写入 `trade_records``monitor_type`**`趋势回调`**。
- **`trend_pullback_plans`**趋势回调计划。执行后写入一行,`status='active'` 表示运行中;止盈 / 止损 / 手动结束后变为 **`stopped_tp` / `stopped_sl` / `stopped_manual`** 等非 `active` 状态,并出现在页顶 **计划历史**字段含快照可用余额、计划保证金、总张数、首仓张数、补仓 JSON、网格价 JSON、已补仓档数、均价、`opened_at``message`(结束说明)等。
- **`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`
+18
View File
@@ -150,6 +150,24 @@ 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(验证)