fix bug
This commit is contained in:
@@ -5,18 +5,21 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
import logging as log
|
||||
import time
|
||||
from datetime import datetime, time as clock_time
|
||||
from pathlib import Path
|
||||
|
||||
import config
|
||||
from libs.calc import trading_time
|
||||
from libs.market import market_allow_open
|
||||
from libs.signal import init_signals
|
||||
from libs.signal import SignalItem, init_signals
|
||||
from libs.collector import collector_push
|
||||
from libs.grid_take_profit import GridTrailingTracker
|
||||
from sdk import Client
|
||||
from libs.order import OrderBook
|
||||
from libs.overview import Overview
|
||||
from libs.order import BUSY_STATUSES, OrderBook
|
||||
from libs.watch import DipWatch
|
||||
from libs.runtime import Runtime
|
||||
from .state import TState, SOLD
|
||||
@@ -31,9 +34,11 @@ def StartZT() -> None:
|
||||
config.global_config.qmt_token,
|
||||
config.HTTP_TIMEOUT,
|
||||
) as client:
|
||||
state = TState.for_strategy(
|
||||
config.global_config.qmt_data_dir, "zt", config.account_config.account_id
|
||||
state = TState(
|
||||
Path(config.global_config.qmt_data_dir)
|
||||
/ f"zt_{config.account_config.account_id}_state.db"
|
||||
)
|
||||
executor = ThreadPoolExecutor(max_workers=3, thread_name_prefix="zt")
|
||||
run = Runtime(
|
||||
client=client,
|
||||
global_cfg=config.global_config,
|
||||
@@ -42,110 +47,153 @@ def StartZT() -> None:
|
||||
open_watch=DipWatch(),
|
||||
add_watch=DipWatch(),
|
||||
profit_tracker=GridTrailingTracker(config.account_config.grid_step_pct),
|
||||
executor=executor
|
||||
)
|
||||
log.info(
|
||||
"[ZT 启动] 账户=%s,底仓信号=dcm,状态文件=%s",
|
||||
run.account_cfg.account_id,
|
||||
state.path,
|
||||
|
||||
portfolio = client.portfolio()
|
||||
assets = portfolio.assets
|
||||
positions = list(portfolio.positions.values())
|
||||
run.orders.refresh(client, portfolio.orders)
|
||||
|
||||
# 获取本策略的信号开仓数据
|
||||
signals = init_signals(config.global_config,["dcm"])
|
||||
log.info("[启动] ZT 策略已启动,账户=%s,信号=%d,持仓=%d",
|
||||
config.account_config.account_id,
|
||||
len(signals),
|
||||
len(positions),
|
||||
)
|
||||
|
||||
Overview(assets, positions, config.account_config)
|
||||
|
||||
DEFAULT_TICK_INTERVAL = 30
|
||||
while True:
|
||||
now = datetime.now()
|
||||
if now.time() >= clock_time(15):
|
||||
# 收盘前最后一次只读对账,不发新单;未完成买回继续持久保存。
|
||||
try:
|
||||
portfolio = client.portfolio()
|
||||
deals = client.deals()
|
||||
state.reconcile(
|
||||
list(portfolio.positions.values()),
|
||||
deals,
|
||||
now.date().isoformat(),
|
||||
)
|
||||
except Exception:
|
||||
log.exception("[ZT] 收盘对账失败,保留本地待确认记录")
|
||||
for item in state.items.values():
|
||||
if item.phase == SOLD or state.busy(item.code):
|
||||
log.warning("[ZT] 收盘仍有待完成轮次:%s", item.code)
|
||||
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, state)
|
||||
except Exception:
|
||||
log.exception("[ZT] 本 tick 执行失败,下一个 tick 继续")
|
||||
# 计算距离下一个目标时间点(0秒或30秒)的等待时间。
|
||||
time.sleep(30 - datetime.now().second % 30)
|
||||
RunOnce(run, state, signals)
|
||||
except Exception as e:
|
||||
log.error(
|
||||
f"[Trend] 本 tick 执行失败,下一 tick 继续: {e}", exc_info=True
|
||||
)
|
||||
|
||||
|
||||
def RunOnce(run: Runtime, state: TState) -> None:
|
||||
def RunOnce(run: Runtime, state: TState, signals: list[SignalItem]) -> None:
|
||||
"""账户快照 → 成交对账 → 做 T 管理 → dcm 建仓,共用一份资金预算。"""
|
||||
now = datetime.now()
|
||||
if not trading_time(now) or now.time() >= clock_time(15):
|
||||
if not trading_time(now):
|
||||
return
|
||||
today = now.date().isoformat()
|
||||
|
||||
started_at = time.monotonic()
|
||||
|
||||
# 1. 一次获取资产、持仓和订单,并清理过期订单。
|
||||
portfolio = run.client.portfolio()
|
||||
deals = run.client.deals()
|
||||
positions = list(portfolio.positions.values())
|
||||
run.orders.refresh(run.client, portfolio.orders)
|
||||
# 状态只按真实成交记账,不使用委托状态推算数量和成本。
|
||||
state.reconcile(positions, deals, today)
|
||||
|
||||
# 2. 获取本策略的信号开仓数据;信号失败不阻断已有做 T 买回。
|
||||
try:
|
||||
signals = init_signals(run.global_cfg, ["dcm"])
|
||||
portfolio = run.client.portfolio()
|
||||
assets = portfolio.assets
|
||||
deals = run.client.deals()
|
||||
position_codes = list(portfolio.positions)
|
||||
positions = list(portfolio.positions.values())
|
||||
run.orders.refresh(run.client, portfolio.orders)
|
||||
state.reconcile(positions,deals)
|
||||
except Exception:
|
||||
log.exception("[ZT] 获取 dcm 信号失败,本轮只管理已有底仓")
|
||||
signals = []
|
||||
position_codes = {
|
||||
position.stock_code for position in positions if position.volume > 0
|
||||
}
|
||||
candidates = [
|
||||
signal
|
||||
for signal in signals
|
||||
if signal.signal_key == "dcm" and signal.code not in position_codes
|
||||
]
|
||||
|
||||
# 3. 获取持仓和待开仓证券的实时行情 tick,零持仓的待买回证券也包含在内。
|
||||
codes = list(
|
||||
dict.fromkeys(
|
||||
list(position_codes)
|
||||
+ list(state.items)
|
||||
+ [signal.code for signal in candidates]
|
||||
)
|
||||
)
|
||||
ticks = run.client.full_tick(codes) if codes else {}
|
||||
now = datetime.now() # 网络请求可能跨过尾盘边界,提交前重新判断。
|
||||
if not trading_time(now) or now.time() >= clock_time(15):
|
||||
log.exception("[Portfolio] 刷新账户快照失败")
|
||||
return
|
||||
|
||||
# 4. 先完成买回,避免开底仓抢占资金;交易逻辑串行,状态无需多线程写入。
|
||||
available = max(0.0, portfolio.assets.available)
|
||||
# 未确认买单可能尚未反映在资金快照中,保守预留,宁可少买也不重复使用。
|
||||
for pending in state.pending.values():
|
||||
if pending.kind != "sell":
|
||||
tick = ticks.get(pending.code)
|
||||
if tick is None or tick.last_price <= 0:
|
||||
available = 0.0
|
||||
break
|
||||
available = max(0.0, available - pending.qty * tick.last_price * 1.01)
|
||||
force = now.time() >= clock_time(14, 50)
|
||||
available = manage_positions(run, state, ticks, positions, available, today, force)
|
||||
futures: list[tuple[str, Future]] = [
|
||||
(
|
||||
"数据提交",
|
||||
run.executor.submit(
|
||||
collector_push,
|
||||
run.account_cfg.account_id,
|
||||
assets,
|
||||
positions,
|
||||
),
|
||||
)
|
||||
]
|
||||
|
||||
# 5. 验证可用资金;低于资金安全线时禁止开新仓,尾盘只完成做 T 买回。
|
||||
reserve = max(0.0, portfolio.assets.total * run.account_cfg.min_cash_ratio)
|
||||
# 未完成的卖出/买回可能继续占用资金,不再额外开底仓。
|
||||
outstanding = bool(state.pending) or any(
|
||||
item.phase == SOLD for item in state.items.values()
|
||||
# 2. 验证可用资金;低于资金安全线时禁止开新仓。
|
||||
allow_open_by_cash = (
|
||||
assets.available >= assets.total * run.account_cfg.min_cash_ratio
|
||||
)
|
||||
if not force and not outstanding and market_allow_open() and available > reserve:
|
||||
open_signal(run, state, ticks, candidates, available - reserve)
|
||||
if not allow_open_by_cash:
|
||||
log.info(
|
||||
"[Status] 禁止开仓:可用资金不足,可用=%.2f,总资产=%.2f",
|
||||
assets.available,
|
||||
assets.total,
|
||||
)
|
||||
|
||||
# 3. 获取大盘状态,只有大盘信号允许时才执行开仓。
|
||||
market_ok = market_allow_open()
|
||||
|
||||
# 4. 验证有效开仓信号:排除已有持仓和未决订单。
|
||||
allow_open: list[SignalItem] = []
|
||||
allow_codes: list[str] = []
|
||||
for signal in signals:
|
||||
if signal.code not in position_codes:
|
||||
allow_open.append(signal)
|
||||
allow_codes.append(signal.code)
|
||||
|
||||
if allow_open and not market_ok:
|
||||
log.info("[开仓] 禁止开仓:大盘信号不允许,候选=%d", len(allow_open))
|
||||
|
||||
# 5. 获取持仓和待开仓证券的实时行情 tick。
|
||||
all_codes = list(dict.fromkeys(position_codes + allow_codes))
|
||||
try:
|
||||
ticks = run.client.full_tick(all_codes)
|
||||
except Exception:
|
||||
log.exception("[行情] 获取行情失败,代码数量=%d", len(all_codes))
|
||||
return
|
||||
|
||||
# 6. 数据采集不与交易逻辑争用状态;采集函数自身隔离传输异常。
|
||||
collector_push(run.account_cfg.account_id, portfolio.assets, positions)
|
||||
log.info(
|
||||
"[ZT] 本轮完成,底仓=%d,待确认=%d,耗时=%d毫秒",
|
||||
len(state.items),
|
||||
len(state.pending),
|
||||
int((time.monotonic() - started_at) * 1000),
|
||||
"[RunOnce] 本轮就绪,持仓=%d,候选=%d,大盘允许=%s,资金允许=%s",
|
||||
len(positions),
|
||||
len(allow_open),
|
||||
market_ok,
|
||||
allow_open_by_cash,
|
||||
)
|
||||
|
||||
# 启动线程,开始计算
|
||||
# 7. 持仓计算。
|
||||
futures.append(
|
||||
(
|
||||
"持仓计算",
|
||||
run.executor.submit(
|
||||
manage_positions, run, ticks, positions, market_ok, assets.available
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
# 8. 开仓计算:必须同时存在有效信号且大盘允许开仓。
|
||||
if allow_open and market_ok and allow_open_by_cash:
|
||||
futures.append(
|
||||
("开仓计算", run.executor.submit(open_signal, run, ticks, allow_open))
|
||||
)
|
||||
|
||||
# 9. 开始执行
|
||||
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:
|
||||
"""保留单轮继续运行的语义,分别记录工作线程异常。"""
|
||||
try:
|
||||
future.result()
|
||||
except Exception:
|
||||
log.exception("[运行] %s线程失败", name)
|
||||
Reference in New Issue
Block a user