Files
qihuo/ctp_premarket_connect.py
T
dekun 9875ee6d44 本地监控止盈止损、盘前自动连CTP,并完善保证金与推荐手数。
- 止盈止损改为程序本地监控,触发后市价平仓(含跳空)
- 交易前30分钟后台自动连接 CTP
- 保证金占用上限默认30%,可在系统设置修改
- K线标准蜡烛图红跌绿涨,费率表全宽固定表头
- 品种推荐按保证金比例×总资金计算推荐手数

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-25 12:18:18 +08:00

63 lines
2.0 KiB
Python

"""交易前自动连接 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"):
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()