2026-08-28 18:52:27 +08:00
|
|
|
|
"""趋势策略启动器。
|
|
|
|
|
|
|
|
|
|
|
|
该模块负责组合 SDK、配置、状态存储和趋势策略组件,供 main.py 调用。
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import time
|
2026-09-01 14:28:49 +08:00
|
|
|
|
import logging as log
|
2026-08-31 15:33:39 +08:00
|
|
|
|
from concurrent.futures import Future, ThreadPoolExecutor
|
2026-08-28 18:52:27 +08:00
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
import config
|
2026-08-31 13:00:22 +08:00
|
|
|
|
from libs.calc import trading_time
|
|
|
|
|
|
from libs.market import market_allow_open
|
|
|
|
|
|
from libs.signal import init_signals, SignalItem
|
2026-09-04 19:48:47 +08:00
|
|
|
|
from libs.collector import collector_push
|
2026-08-28 18:52:27 +08:00
|
|
|
|
from sdk import Client
|
2026-08-28 22:46:04 +08:00
|
|
|
|
from libs.grid_take_profit import GridTrailingTracker
|
2026-08-28 18:52:27 +08:00
|
|
|
|
from .state import State
|
|
|
|
|
|
from .order import OrderBook
|
|
|
|
|
|
from .watch import DipWatch
|
|
|
|
|
|
from .runtime import Runtime
|
|
|
|
|
|
from .open import open_signal
|
|
|
|
|
|
from .positions import manage_positions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def Overview(assets, positions, account_cfg=None) -> None:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
"""记录策略启动时的账户、资金和持仓概览。"""
|
2026-08-28 18:52:27 +08:00
|
|
|
|
account_cfg = account_cfg or config.account_config
|
|
|
|
|
|
|
|
|
|
|
|
if account_cfg is not None:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.info("[启动] 账户=%s,主机=%s,单笔金额=%.2f", account_cfg.account_id, account_cfg.host_key, account_cfg.buy_value)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
if assets is not None:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.info("[启动] 总资产=%.2f,可用资金=%.2f", assets.total, assets.available)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
else:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.warning("[启动] 获取资金概览失败")
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
for position in positions:
|
|
|
|
|
|
if position.volume <= 0:
|
|
|
|
|
|
continue
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.info("[启动] %s %s,持仓=%d,可用=%d,成本=%.2f,现价=%.2f,盈亏=%.2f%%", position.stock_code, position.stock_name, position.volume, position.can_use_volume, position.open_price, position.last_price, position.profit_rate * 100)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def StartTrend() -> None:
|
|
|
|
|
|
"""初始化趋势策略,并以 30 秒间隔持续执行。"""
|
|
|
|
|
|
client = Client(
|
|
|
|
|
|
config.global_config.qmt_base_url,
|
|
|
|
|
|
config.global_config.qmt_token,
|
|
|
|
|
|
config.HTTP_TIMEOUT,
|
|
|
|
|
|
)
|
2026-09-05 11:46:31 +08:00
|
|
|
|
executor = None
|
|
|
|
|
|
try:
|
|
|
|
|
|
portfolio = client.portfolio()
|
|
|
|
|
|
assets = portfolio.assets
|
|
|
|
|
|
positions = list(portfolio.positions.values())
|
|
|
|
|
|
storeState = State.for_strategy(
|
|
|
|
|
|
config.global_config.qmt_data_dir,
|
|
|
|
|
|
config.account_config.strategy,
|
|
|
|
|
|
config.account_config.account_id,
|
|
|
|
|
|
)
|
2026-09-05 13:53:26 +08:00
|
|
|
|
order_book = OrderBook(state=storeState)
|
|
|
|
|
|
order_book.refresh(client, portfolio.orders)
|
|
|
|
|
|
storeState.reconcile(positions, portfolio.orders)
|
2026-09-05 11:46:31 +08:00
|
|
|
|
|
|
|
|
|
|
# 获取本策略的信号开仓数据
|
|
|
|
|
|
signals = init_signals(
|
|
|
|
|
|
config.global_config,
|
|
|
|
|
|
config.account_config.signal_allow,
|
|
|
|
|
|
)
|
|
|
|
|
|
log.info("[启动] 趋势策略已启动,账户=%s,信号=%d,持仓=%d", config.account_config.account_id, len(signals), len(positions))
|
|
|
|
|
|
executor = ThreadPoolExecutor(max_workers=3, thread_name_prefix="trend")
|
|
|
|
|
|
run = Runtime(
|
|
|
|
|
|
client=client,
|
|
|
|
|
|
global_cfg=config.global_config,
|
|
|
|
|
|
account_cfg=config.account_config,
|
|
|
|
|
|
state=storeState,
|
|
|
|
|
|
orders=order_book,
|
|
|
|
|
|
open_watch=DipWatch(),
|
|
|
|
|
|
add_watch=DipWatch(),
|
|
|
|
|
|
profit_tracker=GridTrailingTracker(config.account_config.grid_step_pct),
|
|
|
|
|
|
executor=executor,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
Overview(assets, positions, config.account_config)
|
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_TICK_INTERVAL = 30
|
|
|
|
|
|
while True:
|
|
|
|
|
|
lt = time.localtime()
|
|
|
|
|
|
if (lt.tm_hour, lt.tm_min, lt.tm_sec) >= (15, 0, 0):
|
|
|
|
|
|
log.info("[Trend] 已到 15:00,结束趋势策略")
|
|
|
|
|
|
return
|
|
|
|
|
|
current_sec = lt.tm_sec
|
|
|
|
|
|
|
|
|
|
|
|
# 计算距离下一个目标时间点(0秒或30秒)的等待时间
|
|
|
|
|
|
if current_sec < DEFAULT_TICK_INTERVAL:
|
|
|
|
|
|
wait_seconds = DEFAULT_TICK_INTERVAL - current_sec
|
|
|
|
|
|
elif current_sec < 60:
|
|
|
|
|
|
wait_seconds = 60 - current_sec
|
|
|
|
|
|
else:
|
|
|
|
|
|
wait_seconds = DEFAULT_TICK_INTERVAL
|
|
|
|
|
|
|
|
|
|
|
|
# 等待到目标时间点
|
|
|
|
|
|
time.sleep(wait_seconds)
|
|
|
|
|
|
|
|
|
|
|
|
# 单轮失败不能杀死唯一的交易定时线程。
|
|
|
|
|
|
try:
|
|
|
|
|
|
RunOnce(run, signals)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
log.error(f"[Trend] 本 tick 执行失败,下一 tick 继续: {e}", exc_info=True)
|
|
|
|
|
|
finally:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
try:
|
2026-09-05 11:46:31 +08:00
|
|
|
|
if executor is not None:
|
|
|
|
|
|
executor.shutdown(wait=True)
|
|
|
|
|
|
finally:
|
|
|
|
|
|
client.close()
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-31 13:00:22 +08:00
|
|
|
|
def RunOnce(run: Runtime, signals:list[SignalItem]) -> None:
|
2026-08-28 18:52:27 +08:00
|
|
|
|
"""按固定步骤执行一轮趋势策略, ``RunOnce``。"""
|
|
|
|
|
|
if not trading_time(datetime.now()):
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2026-09-01 15:49:09 +08:00
|
|
|
|
print("=" * 40 + f" Ticker {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} " +"=" * 40)
|
2026-09-01 14:28:49 +08:00
|
|
|
|
|
|
|
|
|
|
started_at = time.monotonic()
|
|
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 1. 一次获取资产、持仓和订单,并清理过期订单。
|
2026-08-28 18:52:27 +08:00
|
|
|
|
try:
|
2026-09-03 11:33:43 +08:00
|
|
|
|
portfolio = run.client.portfolio()
|
|
|
|
|
|
assets = portfolio.assets
|
|
|
|
|
|
position_codes = list(portfolio.positions)
|
|
|
|
|
|
positions = list(portfolio.positions.values())
|
|
|
|
|
|
run.orders.refresh(run.client, portfolio.orders)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
except Exception:
|
2026-09-03 11:33:43 +08:00
|
|
|
|
log.exception("[Portfolio] 刷新账户快照失败")
|
2026-08-31 13:00:22 +08:00
|
|
|
|
return
|
|
|
|
|
|
|
2026-09-03 23:51:07 +08:00
|
|
|
|
futures: list[tuple[str, Future]] = [
|
|
|
|
|
|
(
|
|
|
|
|
|
"数据提交",
|
|
|
|
|
|
run.executor.submit(
|
2026-09-04 19:48:47 +08:00
|
|
|
|
collector_push,
|
|
|
|
|
|
run.account_cfg.account_id,
|
2026-09-03 23:51:07 +08:00
|
|
|
|
assets,
|
|
|
|
|
|
positions,
|
|
|
|
|
|
),
|
|
|
|
|
|
)
|
|
|
|
|
|
]
|
|
|
|
|
|
|
2026-08-28 18:52:27 +08:00
|
|
|
|
# 2. 验证可用资金;低于资金安全线时禁止开新仓。
|
2026-08-28 22:46:04 +08:00
|
|
|
|
allow_open_by_cash = assets.available >= assets.total * run.account_cfg.min_cash_ratio
|
|
|
|
|
|
if not allow_open_by_cash:
|
2026-09-01 15:49:09 +08:00
|
|
|
|
log.info("[Status] 禁止开仓:可用资金不足,可用=%.2f,总资产=%.2f", assets.available, assets.total)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
|
|
|
|
|
# 3. 获取大盘状态,只有大盘信号允许时才执行开仓。
|
2026-09-01 14:28:49 +08:00
|
|
|
|
market_ok = market_allow_open()
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 4. 验证有效开仓信号:排除已有持仓和未决订单。
|
2026-08-31 13:00:22 +08:00
|
|
|
|
allow_open: list[SignalItem] = []
|
|
|
|
|
|
allow_codes: list[str] = []
|
2026-08-28 22:46:04 +08:00
|
|
|
|
for signal in signals:
|
2026-08-31 13:00:22 +08:00
|
|
|
|
if signal.code not in position_codes:
|
2026-08-28 22:46:04 +08:00
|
|
|
|
allow_open.append(signal)
|
2026-08-31 13:00:22 +08:00
|
|
|
|
allow_codes.append(signal.code)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-09-01 14:28:49 +08:00
|
|
|
|
if allow_open and not market_ok:
|
|
|
|
|
|
log.info("[开仓] 禁止开仓:大盘信号不允许,候选=%d", len(allow_open))
|
|
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 5. 获取持仓和待开仓证券的实时行情 tick。
|
2026-08-31 15:33:39 +08:00
|
|
|
|
all_codes = list(dict.fromkeys(position_codes + allow_codes))
|
2026-08-28 18:52:27 +08:00
|
|
|
|
try:
|
2026-08-31 13:00:22 +08:00
|
|
|
|
ticks = run.client.full_tick(all_codes)
|
2026-08-28 18:52:27 +08:00
|
|
|
|
except Exception:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.exception("[行情] 获取行情失败,代码数量=%d", len(all_codes))
|
2026-08-28 18:52:27 +08:00
|
|
|
|
return
|
|
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 6. 更新状态机
|
2026-08-31 15:33:39 +08:00
|
|
|
|
try:
|
2026-09-05 13:53:26 +08:00
|
|
|
|
run.state.reconcile(positions, portfolio.orders)
|
2026-08-31 15:33:39 +08:00
|
|
|
|
except Exception:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.exception("[状态] 订单状态对账失败")
|
2026-08-31 15:33:39 +08:00
|
|
|
|
return
|
|
|
|
|
|
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.info("[RunOnce] 本轮就绪,持仓=%d,候选=%d,大盘允许=%s,资金允许=%s", len(positions), len(allow_open), market_ok, allow_open_by_cash)
|
|
|
|
|
|
|
2026-08-31 15:33:39 +08:00
|
|
|
|
# 启动线程,开始计算
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 7. 持仓计算。
|
2026-09-03 23:51:07 +08:00
|
|
|
|
futures.append(("持仓计算",run.executor.submit(manage_positions,run,ticks,positions,market_ok,assets.available)))
|
2026-08-31 15:33:39 +08:00
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 8. 开仓计算:必须同时存在有效信号且大盘允许开仓。
|
2026-08-28 22:46:04 +08:00
|
|
|
|
if allow_open and market_ok and allow_open_by_cash:
|
2026-08-31 15:33:39 +08:00
|
|
|
|
futures.append(("开仓计算", run.executor.submit(open_signal, run, ticks, allow_open)))
|
|
|
|
|
|
|
2026-09-03 11:33:43 +08:00
|
|
|
|
# 9. 开始执行
|
2026-08-31 15:33:39 +08:00
|
|
|
|
for name, future in futures:
|
|
|
|
|
|
_wait_worker(name, future)
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.info("[RunOnce] 本轮完成,耗时=%d毫秒", int((time.monotonic() - started_at) * 1000))
|
2026-08-31 15:33:39 +08:00
|
|
|
|
|
2026-08-28 18:52:27 +08:00
|
|
|
|
|
2026-08-31 15:33:39 +08:00
|
|
|
|
def _wait_worker(name: str, future: Future) -> None:
|
|
|
|
|
|
"""保留单轮继续运行的语义,分别记录工作线程异常。"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
future.result()
|
|
|
|
|
|
except Exception:
|
2026-09-01 14:28:49 +08:00
|
|
|
|
log.exception("[运行] %s线程失败", name)
|