94c566fbe5
Co-authored-by: Cursor <cursoragent@cursor.com>
89 lines
3.2 KiB
Python
89 lines
3.2 KiB
Python
# Copyright (c) 2025-2026 马建军. All rights reserved.
|
|
# 专有软件 — 未经授权禁止复制、传播、转售。
|
|
# 严禁用于:带单/代客理财、向他人推荐期货品种或买卖建议、融资配资等业务。
|
|
# 详见 LICENSE.zh-CN.txt 与 docs/软件购买与使用协议.md
|
|
|
|
"""交易前自动连接 CTP(默认开盘前 30 分钟)。"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import threading
|
|
import time
|
|
from typing import Callable
|
|
|
|
from market_sessions import in_premarket_connect_window, is_trading_session
|
|
from vnpy_bridge import ctp_start_connect, ctp_status
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CHECK_INTERVAL_SEC = 60
|
|
DEFAULT_MINUTES_BEFORE = 30
|
|
|
|
|
|
def premarket_minutes_before() -> int:
|
|
try:
|
|
return max(5, int(os.getenv("CTP_PREMARKET_MINUTES", str(DEFAULT_MINUTES_BEFORE))))
|
|
except (TypeError, ValueError):
|
|
return DEFAULT_MINUTES_BEFORE
|
|
|
|
|
|
def _premarket_enabled() -> bool:
|
|
return (os.getenv("CTP_PREMARKET_CONNECT", "true") or "true").strip().lower() in (
|
|
"1",
|
|
"true",
|
|
"yes",
|
|
)
|
|
|
|
|
|
def should_auto_connect_now(*, minutes_before: int | None = None) -> bool:
|
|
"""交易时段内,或距下一段开盘 <= minutes_before 且尚未开盘。"""
|
|
mins = premarket_minutes_before() if minutes_before is None else minutes_before
|
|
if is_trading_session():
|
|
return True
|
|
if not _premarket_enabled():
|
|
return False
|
|
return in_premarket_connect_window(minutes_before=mins)
|
|
|
|
|
|
def start_ctp_premarket_connect_worker(
|
|
*,
|
|
get_mode_fn: Callable[[], str],
|
|
get_setting_fn: Callable[[str, str], str] | None = None,
|
|
interval: int = CHECK_INTERVAL_SEC,
|
|
) -> None:
|
|
"""在交易开始前若干分钟自动发起 CTP 连接。"""
|
|
|
|
def _loop() -> None:
|
|
time.sleep(10)
|
|
while True:
|
|
sleep_sec = max(30, interval)
|
|
try:
|
|
if should_auto_connect_now():
|
|
mode = get_mode_fn()
|
|
st = ctp_status(mode)
|
|
if (
|
|
not st.get("connected")
|
|
and not st.get("connecting")
|
|
and int(st.get("login_cooldown_sec") or 0) <= 0
|
|
):
|
|
info = ctp_start_connect(mode, force=False, scheduled=True)
|
|
if info.get("started"):
|
|
if is_trading_session():
|
|
logger.info("交易时段内自动连接 CTP [%s]", mode)
|
|
else:
|
|
logger.info(
|
|
"盘前自动连接 CTP [%s](开盘前 %d 分钟)",
|
|
mode,
|
|
premarket_minutes_before(),
|
|
)
|
|
if not is_trading_session() and in_premarket_connect_window(
|
|
minutes_before=premarket_minutes_before(),
|
|
):
|
|
sleep_sec = 30
|
|
except Exception as exc:
|
|
logger.warning("CTP premarket connect worker: %s", exc)
|
|
time.sleep(sleep_sec)
|
|
|
|
threading.Thread(target=_loop, daemon=True, name="ctp-premarket-connect").start()
|