ab9987e4c7
Co-authored-by: Cursor <cursoragent@cursor.com>
72 lines
2.4 KiB
Python
72 lines
2.4 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
|
|
from vnpy_bridge import ctp_start_connect, ctp_status
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CHECK_INTERVAL_SEC = 60
|
|
DEFAULT_MINUTES_BEFORE = 30
|
|
|
|
|
|
def _premarket_enabled() -> bool:
|
|
return (os.getenv("CTP_PREMARKET_CONNECT", "true") or "true").strip().lower() in (
|
|
"1",
|
|
"true",
|
|
"yes",
|
|
)
|
|
|
|
|
|
def _minutes_before_open() -> int:
|
|
try:
|
|
return max(5, int(os.getenv("CTP_PREMARKET_MINUTES", str(DEFAULT_MINUTES_BEFORE))))
|
|
except (TypeError, ValueError):
|
|
return DEFAULT_MINUTES_BEFORE
|
|
|
|
|
|
def start_ctp_premarket_connect_worker(
|
|
*,
|
|
get_mode_fn: Callable[[], str],
|
|
interval: int = CHECK_INTERVAL_SEC,
|
|
) -> None:
|
|
"""在交易开始前若干分钟自动发起 CTP 连接。"""
|
|
|
|
def _loop() -> None:
|
|
time.sleep(10)
|
|
while True:
|
|
try:
|
|
if _premarket_enabled() and in_premarket_connect_window(
|
|
minutes_before=_minutes_before_open(),
|
|
):
|
|
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)
|
|
if info.get("started"):
|
|
logger.info(
|
|
"盘前自动连接 CTP [%s](开盘前 %d 分钟)",
|
|
mode,
|
|
_minutes_before_open(),
|
|
)
|
|
except Exception as exc:
|
|
logger.warning("CTP premarket connect worker: %s", exc)
|
|
time.sleep(max(30, interval))
|
|
|
|
threading.Thread(target=_loop, daemon=True, name="ctp-premarket-connect").start()
|