feat dev6

This commit is contained in:
2026-09-01 14:28:49 +08:00
parent dedbf63a92
commit 556e21d624
27 changed files with 334 additions and 144 deletions

View File

@@ -5,8 +5,8 @@
from __future__ import annotations
import logging
import time
import logging as log
from concurrent.futures import Future, ThreadPoolExecutor
from datetime import datetime
@@ -25,42 +25,22 @@ from .positions import manage_positions
def Overview(assets, positions, account_cfg=None) -> None:
"""打印策略启动时的账户、资金和持仓概览。
"""
"""记录策略启动时的账户、资金和持仓概览。"""
account_cfg = account_cfg or config.account_config
print("\n" + "=" * 80)
print(f"【时间】{datetime.now():%Y-%m-%d %H:%M:%S}")
if account_cfg is not None:
print(
"【配置】"
f"account_id: {account_cfg.account_id} "
f"host_key: {account_cfg.host_key} "
f"buy_value: {account_cfg.buy_value:.0f}"
)
log.info("[启动] 账户=%s,主机=%s,单笔金额=%.2f", account_cfg.account_id, account_cfg.host_key, account_cfg.buy_value)
if assets is not None:
print(
f"【资金】总资产:{assets.total:.2f}元,"
f"可用资金:{assets.available:.2f}"
)
log.info("[启动] 总资产=%.2f,可用资金=%.2f", assets.total, assets.available)
else:
print("【资金】查询失败")
log.warning("[启动] 获取资金概览失败")
print(f"【持仓】{len(positions)}")
print("=" * 80)
log.info("[启动] 持仓数量=%d", len(positions))
for position in positions:
if position.volume <= 0:
continue
print(
f"【持仓】{position.stock_code} {position.stock_name} "
f"持仓={position.volume} 可用={position.can_use_volume} "
f"冻结={position.frozen_volume} 在途={position.on_road_volume} "
f"昨仓={position.yesterday_volume} 成本={position.open_price:.3f} "
f"现价={position.last_price:.3f} 市值={position.market_value:.2f} "
f"浮盈={position.float_profit:.2f} "
f"盈亏比例={position.profit_rate * 100:.2f}%"
)
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)
@@ -88,6 +68,7 @@ def StartTrend() -> None:
config.global_config,
config.account_config.signal_allow,
)
log.info("[启动] 趋势策略已启动,账户=%s,信号=%d,持仓=%d", config.account_config.account_id, len(signals), len(positions))
run = Runtime(
client=client,
global_cfg=config.global_config,
@@ -102,31 +83,43 @@ def StartTrend() -> None:
Overview(assets, positions, config.account_config)
try:
while True:
started_at = time.monotonic()
try:
RunOnce(run, signals)
except Exception:
# 单轮错误只记录日志,下一轮仍继续运行。
logging.exception("趋势策略本轮执行失败")
elapsed = time.monotonic() - started_at
time.sleep(max(0.0, 30.0 - elapsed))
finally:
run.executor.shutdown(wait=True, cancel_futures=True)
DEFAULT_TICK_INTERVAL = 30
while True:
current_sec = time.localtime().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)
def RunOnce(run: Runtime, signals:list[SignalItem]) -> None:
"""按固定步骤执行一轮趋势策略, ``RunOnce``。"""
if not trading_time(datetime.now()):
log.info("[运行] 非交易时间,跳过本轮")
return
print("=" * 40 + f" RunOnce {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} " +"=" * 40)
started_at = time.monotonic()
# 1. 刷新订单数据,清理过期订单。
try:
run.orders.refresh(run.client)
except Exception:
logging.exception("取消过期订单失败")
log.exception("[订单] 刷新订单失败")
return
@@ -134,20 +127,20 @@ def RunOnce(run: Runtime, signals:list[SignalItem]) -> None:
try:
assets = run.client.assets()
except Exception:
logging.exception("获取资产失败")
log.exception("[资金] 获取资产失败")
return
allow_open_by_cash = assets.available >= assets.total * run.account_cfg.min_cash_ratio
if not allow_open_by_cash:
logging.info("资金总闸:可用金额太少,禁止开新仓")
log.info("[开仓] 禁止开仓:可用资金不足,可用=%.2f,总资产=%.2f", assets.available, assets.total)
# 3. 获取大盘状态,只有大盘信号允许时才执行开仓。
market_ok = market_allow_open(run.global_cfg.api_host)
market_ok = market_allow_open()
# 4. 获取当前持仓及持仓证券代码。
try:
position_codes, positions = run.client.positions()
except Exception:
logging.exception("获取持仓失败")
log.exception("[持仓] 获取持仓失败")
return
# 5. 验证有效开仓信号:排除已有持仓和未决订单。
@@ -158,21 +151,26 @@ def RunOnce(run: Runtime, signals:list[SignalItem]) -> None:
allow_open.append(signal)
allow_codes.append(signal.code)
if allow_open and not market_ok:
log.info("[开仓] 禁止开仓:大盘信号不允许,候选=%d", len(allow_open))
# 6. 获取持仓和待开仓证券的实时行情 tick。
all_codes = list(dict.fromkeys(position_codes + allow_codes))
try:
ticks = run.client.full_tick(all_codes)
except Exception:
logging.exception("获取行情失败")
log.exception("[行情] 获取行情失败,代码数量=%d", len(all_codes))
return
# 7. 更新状态机
try:
run.state.reconcile(positions, run.orders.data)
except Exception:
logging.exception("订单状态对账失败,本轮禁止自动交易")
log.exception("[状态] 订单状态对账失败")
return
log.info("[RunOnce] 本轮就绪,持仓=%d,候选=%d,大盘允许=%s,资金允许=%s", len(positions), len(allow_open), market_ok, allow_open_by_cash)
# 启动线程,开始计算
# 9. 持仓计算。
futures: list[tuple[str, Future]] = [
@@ -196,6 +194,7 @@ def RunOnce(run: Runtime, signals:list[SignalItem]) -> None:
# 11. 开始执行
for name, future in futures:
_wait_worker(name, future)
log.info("[RunOnce] 本轮完成,耗时=%d毫秒", int((time.monotonic() - started_at) * 1000))
def _wait_worker(name: str, future: Future) -> None:
@@ -203,4 +202,4 @@ def _wait_worker(name: str, future: Future) -> None:
try:
future.result()
except Exception:
logging.exception("趋势策略%s线程失败", name)
log.exception("[运行] %s线程失败", name)