Files
qihuo/ctp_reconnect.py
T
dekun b02c9d6ca0 Fix empty recommend list and CTP premarket auto-connect.
Correct main_code order in product refresh, refresh on CTP connect, and limit reconnect to trading or premarket windows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 08:24:10 +08:00

59 lines
1.9 KiB
Python

# Copyright (c) 2025-2026 马建军. All rights reserved.
# 专有软件 — 未经授权禁止复制、传播、转售。
# 严禁用于:带单/代客理财、向他人推荐期货品种或买卖建议、融资配资等业务。
# 详见 LICENSE.zh-CN.txt 与 docs/软件购买与使用协议.md
"""CTP 断线自动重连(后台线程)。"""
from __future__ import annotations
import logging
import os
import threading
import time
from typing import Callable
from ctp_premarket_connect import should_auto_connect_now
from ctp_settings import is_ctp_auto_connect_enabled
from vnpy_bridge import ctp_try_auto_reconnect
logger = logging.getLogger(__name__)
RECONNECT_INTERVAL_SEC = 60
def _auto_reconnect_enabled() -> bool:
return (os.getenv("CTP_AUTO_RECONNECT", "true") or "true").strip().lower() in (
"1",
"true",
"yes",
)
def start_ctp_reconnect_worker(
*,
get_mode_fn: Callable[[], str],
get_setting_fn: Callable[[str, str], str] | None = None,
interval: int = RECONNECT_INTERVAL_SEC,
) -> None:
"""定时检测 CTP 连接;仅在交易时段或盘前窗口内尝试重连,避免非交易时段反复登录。"""
def _loop() -> None:
while True:
try:
gs = get_setting_fn
if gs is None:
from fee_specs import get_setting as gs
if (
is_ctp_auto_connect_enabled(gs)
and _auto_reconnect_enabled()
and should_auto_connect_now()
):
mode = get_mode_fn()
if ctp_try_auto_reconnect(mode):
logger.debug("CTP 连接正常 [%s]", mode)
except Exception as exc:
logger.warning("CTP reconnect worker: %s", exc)
time.sleep(max(5, interval))
threading.Thread(target=_loop, daemon=True, name="ctp-reconnect-worker").start()