Files

327 lines
14 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""扫描主循环(独立进程,systemd 单实例 + flock)。
单轮六步:
0. 补发 pending 推送(独立事务外)
1. 逐品种 refresh → bars_cache
2. 定型过滤 close_time <= now-60s
3. 新闭合K检测 + 增量判定(指标全序列重算)
4. signals + notifications + checkpoint 同一事务
5. dispatch 推送(事务外) + refresh_log
时间口径:全部业务时间为 Asia/Shanghai naive 字符串("YYYY-MM-DD HH:MM")。
"""
from __future__ import annotations
import fcntl
import json
import sys
import threading
import traceback
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from app import db # noqa: E402
from app.algo import divergence, ignition # noqa: E402
from app.algo.lx94 import indicators # noqa: E402
from app.config import settings # noqa: E402
from app.market import service # noqa: E402
from app.market.calendar import is_trading_day # noqa: E402
from app.services import dispatch # noqa: E402
LOCK_PATH = "/tmp/xuanlong-scan.lock" # 生产环境: /var/lock/xuanlong-scan.lock
PERIODS = ("30m", "60m", "1d", "90m", "120m") # 90/120 为30m合成周期
IND_CACHE: dict[tuple, tuple[str, dict]] = {}
_cache_lock = threading.Lock()
def now_bj() -> datetime:
return datetime.now(timezone(timedelta(hours=8)))
def _bj(v: datetime | str) -> str:
if isinstance(v, str):
return v
return v.strftime("%Y-%m-%d %H:%M")
def _load_symbols() -> list[dict]:
return json.loads(Path(settings.symbols_json).read_text(encoding="utf-8"))
def _indicators_cached(symbol: str, interval: str, bars: list[dict]) -> dict:
key = (symbol, interval)
last_dt = bars[-1]["dt"]
with _cache_lock:
hit = IND_CACHE.get(key)
if hit and hit[0] == last_dt:
return hit[1]
ind = indicators(bars)
with _cache_lock:
IND_CACHE[key] = (last_dt, ind)
return ind
def _judged_upto(symbol: str, interval: str) -> str | None:
rows = db.query(
"SELECT last_judged_dt FROM scan_checkpoint WHERE symbol=? AND interval=?",
(symbol, interval),
)
return rows[0]["last_judged_dt"] if rows else None
def scan_round() -> None:
"""一轮扫描。预算超时则跳过剩余品种(checkpoint 不动,下一轮补扫)。"""
start = now_bj().replace(tzinfo=None)
hits = 0
errors = 0
skipped = 0
symbols = _load_symbols()
deadline = start + timedelta(seconds=settings.scan_budget_seconds)
cutoff = (now_bj() - timedelta(seconds=settings.settle_buffer_seconds)).strftime("%Y-%m-%d %H:%M")
for sym in symbols:
if (now_bj().replace(tzinfo=None)) > deadline:
skipped += 1
continue
try:
# 15m 是 30m/90m/120m 的合成源,必须先刷新——PERIODS 已无 15m(产品决策
# 不判定15m信号),若无此行 15m 缓存冻结导致三个合成周期全部停更(2026-11-23)
service.refresh(sym["code"], sym["market"], "15m")
service.refresh(sym["code"], sym["market"], "30m") # 基础周期
service.refresh_derived(sym["code"]) # 合成 90m/120m
except Exception as exc:
errors += 1
print(f"[refresh失败] {sym['code']}: {exc!r}\n{traceback.format_exc()}", flush=True)
for interval in PERIODS:
try:
bars = service.refresh(sym["code"], sym["market"], interval) if interval not in ("30m", "90m", "120m") else service.load_cached(sym["code"], interval)
ind = _indicators_cached(sym["code"], interval, bars)
hits += _judge(sym, interval, bars, ind, cutoff)
except Exception as exc:
errors += 1
print(f"[判定失败] {sym['code']} {interval}: {exc!r}\n{traceback.format_exc()}", flush=True)
dispatch.push_pending()
dispatch.send_signal_sms()
db.execute(
"INSERT INTO refresh_log(round_at, scanned, hits, errors, seconds, skipped) VALUES(?,?,?,?,?,?)",
(start.strftime("%Y-%m-%d %H:%M:%S"), len(symbols), hits, errors,
(now_bj().replace(tzinfo=None) - start).total_seconds(), skipped),
)
@dataclass
class Judgement:
"""一次判定的分类结果(纯数据,不碰库)。
formal: 封根后正式信号(已定型 K 上的命中,dt > checkpoint)
preliminary: 封根前提醒(最后一根未定型 K 上的命中),dt 已替换为最终封根时间
resolved: 本轮封根的 K 对应的封根前提醒如何收场 [(封根时间, 是否复现)]
new_checkpoint: 推进到最后一根**已定型**的 K;未定型 K 不推进
"""
formal: list[dict] = field(default_factory=list)
preliminary: list[dict] = field(default_factory=list)
resolved: list[tuple[str, bool]] = field(default_factory=list)
new_checkpoint: str | None = None
def classify_signals(bars: list[dict], hits: list[dict], upto: str | None) -> Judgement:
"""把算法命中分到「封根后正式信号」与「封根前提醒」两条独立通道。
规则(用户 2026-11-25):
- 封根前命中立即报,divergence_time 用 expected_close(最终封根时间)而非盘中
临时标签;同一封根点只出一条;量价背离/做空起爆/BD 共振同样适用
- 封根后仍是信号则再报一次正式信号,与封根前提醒互不替代
- 封根后未复现的封根前提醒由调用方标记失效(见 resolved)
bars 须带 synthesize_traded 输出的 expected_close / is_closed;原生周期
(60m/1d)的 K 不带这两个字段,视为全部已定型(没有封根前提醒)。
"""
out = Judgement()
if not bars:
return out
tail = bars[-1]
has_meta = "is_closed" in tail
tail_is_open = has_meta and tail["is_closed"] is False
closed_bars = bars[:-1] if tail_is_open else bars
if not closed_bars:
return out
out.new_checkpoint = closed_bars[-1]["dt"]
def after_ckpt(dt: str) -> bool:
return upto is None or service.sort_key(dt) > service.sort_key(upto)
# ---- 封根后正式信号 ----
seen_formal: set[str] = set()
for s in hits:
dt = s["dt"]
if tail_is_open and service.sort_key(dt) >= service.sort_key(tail["dt"]):
continue # 落在未定型 K 上,不进正式通道
if not after_ckpt(dt) or dt in seen_formal:
continue
seen_formal.add(dt)
out.formal.append({**s, "is_preliminary": False})
# ---- 封根前提醒:只看最后一根未定型 K ----
if tail_is_open:
final = tail["expected_close"]
for s in hits:
if service.sort_key(s["dt"]) >= service.sort_key(tail["dt"]):
out.preliminary.append({**s, "dt": final, "is_preliminary": True})
break # 同一封根点只出一条
# ---- 本轮新封根的 K:收场它对应的封根前提醒 ----
# checkpoint(upto) 之后、已定型 的 K 就是本轮新封根的。它们上轮还是未定型 K,
# 可能带着封根前提醒;现在定型了,看正式信号里有没有复现。
if upto is not None:
for b in closed_bars:
if after_ckpt(b["dt"]):
reproduced = any(f["dt"] == b["dt"] for f in out.formal)
out.resolved.append((b["dt"], reproduced))
return out
def _judge(symbol: dict, interval: str, bars: list[dict], ind: dict, cutoff: str) -> int:
"""对 (checkpoint, 最后已定型K] 区间做判定;返回本轮命中数。"""
symbol_code = symbol["code"]
upto = _judged_upto(symbol_code, interval)
# 已定型K:dt 的收盘时刻 <= cutoff
period_min = {"30m": 30, "60m": 60, "1d": 1440, "90m": 90, "120m": 120}[interval]
closed = [b for b in bars if _close_time(b["dt"], period_min, symbol_code) <= cutoff]
if not closed:
return 0
last_dt = closed[-1]["dt"]
# 夜盘排序不是字符串序(同一标签日 21:00-23:59 在 00:00-02:30 之前),
# checkpoint 比较必须用 service.sort_key,否则凌晨段会被误判为已处理。
if upto is not None and service.sort_key(last_dt) <= service.sort_key(upto):
return 0
sigs = divergence.scan(closed, ind)
if upto is not None:
sigs = [s for s in sigs if service.sort_key(s["dt"]) > service.sort_key(upto)]
sigs += ignition.scan(closed, ind, upto=None) # 起爆点:内部已做波段去重,再过 checkpoint
sigs += ignition.scan_bd(closed, ind) # BD 共振(卖出):同样按 checkpoint 过滤
if upto is not None:
sigs = [s for s in sigs if service.sort_key(s["dt"]) > service.sort_key(upto)]
created = now_bj().strftime("%Y-%m-%d %H:%M:%S")
with db.tx() as conn:
new_ids = []
# divergence_time = 背离 K 的标签时间(TDX 约定 = 该 K 最后更新时刻),
# 与消息弹出/确认时间无关;确认时刻另存 confirmation_time
for s in sigs:
kind = s.get("kind", "divergence")
sig_fields = (
(symbol_code, interval, s["dt"], kind, created, s["path"], s["close"],
s.get("heap_len"), s.get("prev_heap_len"), s.get("after_high"), s.get("prev_high"),
s.get("after_area"), s.get("prev_area"), created),
)
if kind == "divergence":
cur = conn.execute(
"INSERT OR IGNORE INTO signals(symbol, interval, divergence_time, kind, confirmation_time,"
" path, trigger_close, heap_len, prev_heap_len, after_high, prev_high,"
" after_area, prev_area, verified, created_at)"
" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,1,?)",
sig_fields[0],
)
else: # 起爆点:堆证据列为 NULL
cur = conn.execute(
"INSERT OR IGNORE INTO signals(symbol, interval, divergence_time, kind, confirmation_time,"
" path, trigger_close, verified, created_at)"
" VALUES(?,?,?,?,?,?,?,1,?)",
(symbol_code, interval, s["dt"], kind, created, s["path"], s["close"], created),
)
if cur.rowcount:
new_ids.append(cur.lastrowid)
if new_ids:
dispatch.enqueue(conn, new_ids)
conn.execute(
"INSERT OR REPLACE INTO scan_checkpoint(symbol, interval, last_judged_dt, updated_at)"
" VALUES(?,?,?,?)",
(symbol_code, interval, last_dt, created),
)
return len(new_ids)
def _prev_trading_day(day: str) -> str:
"""day 的上一个交易日(含周末与节假日回退)。"""
d = datetime.strptime(day, "%Y-%m-%d") - timedelta(days=1)
while not is_trading_day(d.strftime("%Y-%m-%d")):
d -= timedelta(days=1)
return d.strftime("%Y-%m-%d")
def _to_physical(dt: str) -> str:
"""TDX 标签时间 → 物理时间。
TDX 把夜盘 K 标注为所属交易日:标签 D 21:00-23:30 物理上是 D 的前一交易
日晚上;标签 D 00:00-02:30 物理上是前一交易日的次日凌晨(如周五夜盘跨到
周六凌晨,标注为周一)。日盘时间标签与物理一致。
"""
day, hm = dt.split(" ")
if hm >= "21:00":
return _prev_trading_day(day) + " " + hm
if hm < "06:00":
nd = datetime.strptime(_prev_trading_day(day), "%Y-%m-%d") + timedelta(days=1)
return nd.strftime("%Y-%m-%d") + " " + hm
return dt
def _close_time(dt: str, period_min: int, symbol_code: str = "") -> str:
"""K 线定型(收盘)的物理时刻。cutoff 是物理当前时间,二者必须同一时基——
若直接用标签时间比较,夜盘 K(标签=下一交易日)会被推迟约 24 小时才判定。
分钟 K 的标签即收盘时刻(15:00/23:00/02:30 均为时段终点),不再额外加周期。
日线(2026-11-23 修正):TDX 按交易日标注,标签 D 的日线 = D 前一晚夜盘 +
D 白盘,D 天 15:00 即定型(当晚 21:00 起的行情计入标签 D+1 的新日线)——
实证:TAL9 夜盘进行中正在形成的日线标签为次一交易日,其开盘价=当晚
夜盘 15m 首根开盘价。旧实现误按「自然日口径」压到标签日 23:00/贵金属
次日 02:30,导致日线信号系统性迟到 8 小时。"""
if period_min == 1440:
return dt # 标签 "D 15:00" 本身即定型时刻(夜盘归次一交易日)
return _to_physical(dt)
def acquire_lock() -> None:
fh = open(LOCK_PATH, "w") # noqa: SIM115
try:
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("另一个扫描进程已在运行,退出", flush=True)
sys.exit(0)
globals()["_lock_fh"] = fh # 保持引用防止 GC 释放锁
def main() -> None:
db.init_db()
acquire_lock()
sched = BlockingScheduler(timezone=settings.timezone)
minutes = ",".join(m.strip() for m in settings.scan_minute.split(","))
sched.add_job(
scan_round,
CronTrigger(minute=minutes, timezone=settings.timezone),
max_instances=1,
misfire_grace_time=120,
coalesce=True,
)
from app.services import maintenance
sched.add_job(maintenance.expiry_reminders, CronTrigger(hour=9, minute=0, timezone=settings.timezone))
sched.add_job(maintenance.maintenance, CronTrigger(hour=3, minute=0, timezone=settings.timezone))
print(f"扫描器启动:cron minute={minutes},品种目录 {len(_load_symbols())}", flush=True)
# 启动即补扫一轮
scan_round()
sched.start()
if __name__ == "__main__":
main()