This commit is contained in:
2026-09-10 12:50:40 +08:00
parent 72a49bc741
commit d837250bcb
10 changed files with 423 additions and 458 deletions

View File

@@ -1,196 +1,96 @@
"""做 T 策略启动器。
"""ZT 启动与串行调度:成交同步、买回、卖出、建仓。"""
该模块负责组合 SDK、配置、状态存储和做 T 策略组件,供 main.py 调用。
"""
from concurrent.futures import Future, ThreadPoolExecutor
import logging as log
import time
from datetime import datetime, time as clock_time
from datetime import datetime
from pathlib import Path
import config
from libs.calc import trading_time
from libs.market import market_allow_open
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.market import market_allow_open
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 libs.signal import SignalItem, init_signals
from libs.state import State
from libs.watch import DipWatch
from sdk import Client, DealItem, PositionItem
from .open import open_signal
from .positions import manage_positions
from .positions import manage_positions, t_rounds
def StartZT() -> None:
"""初始化做 T 策略,并以 30 秒间隔持续执行。"""
with Client(
config.global_config.qmt_base_url,
config.global_config.qmt_token,
config.HTTP_TIMEOUT,
) as client:
# 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")
with Client(config.global_config.qmt_base_url, config.global_config.qmt_token, config.HTTP_TIMEOUT) as client:
state = State(Path(config.global_config.qmt_data_dir) / f'zt_{config.account_config.account_id}_state.db')
run = Runtime(
client=client,
global_cfg=config.global_config,
account_cfg=config.account_config,
orders=OrderBook("zt"),
open_watch=DipWatch(),
add_watch=DipWatch(),
client=client, global_cfg=config.global_config, account_cfg=config.account_config,
orders=OrderBook('zt'), open_watch=DipWatch(), add_watch=DipWatch(),
profit_tracker=GridTrailingTracker(config.account_config.grid_step_pct),
executor=executor
)
# 先读取成交,再读取持仓,减少成交已入账而快照仍未更新的情况。
deals = client.deals()
portfolio = client.portfolio()
assets = portfolio.assets
positions = list(portfolio.positions.values())
sync_account_state(state, positions, deals, initialize=not state.state and not state.deals)
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:
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)
# 单轮失败不能杀死唯一的交易定时线程。
signals = init_signals(config.global_config, ['dcm'])
Overview(portfolio.assets, positions, config.account_config)
log.info('[ZT] 启动,账户=%s,信号=%d', config.account_config.account_id, len(signals))
while datetime.now().hour < 15:
try:
RunOnce(run, state, signals)
except Exception as e:
log.error(
f"[Trend] 本 tick 执行失败,下一 tick 继续: {e}", exc_info=True
)
except Exception:
log.exception('[ZT] 本轮失败,下一轮重试')
time.sleep(30 - time.time() % 30)
# 收盘后补记最后一轮成交,不再下单。
sync_account_state(state, list(client.portfolio().positions.values()), client.deals())
def RunOnce(run: Runtime, state: TState, signals: list[SignalItem]) -> None:
"""账户快照 → 成交对账 → 做 T 管理 → dcm 建仓,共用一份资金预算。"""
def RunOnce(run: Runtime, state: State, signals: list[SignalItem]) -> None:
now = datetime.now()
if not trading_time(now):
return
started_at = time.monotonic()
# 1. 一次获取资产、持仓和订单,并清理过期订单。
try:
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("[Portfolio] 刷新账户快照失败")
deals = run.client.deals()
portfolio = run.client.portfolio()
assets = portfolio.assets
positions = list(portfolio.positions.values())
run.orders.refresh(run.client, portfolio.orders)
sync_account_state(state, positions, deals)
# 收盘集合竞价前停止提交新委托,继续保存成交。
if (now.hour, now.minute) >= (14, 57):
return
futures: list[tuple[str, Future]] = [
(
"数据提交",
run.executor.submit(
collector_push,
run.account_cfg.account_id,
assets,
positions,
),
)
]
# 2. 验证可用资金;低于资金安全线时禁止开新仓。
allow_open_by_cash = (
assets.available >= assets.total * run.account_cfg.min_cash_ratio
)
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 portfolio.positions:
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))
rounds = t_rounds(state)
pending = {code for code, item in rounds.items() if item['sold'] > item['bought']}
candidates = {s.code: s for s in signals if s.code not in portfolio.positions
and s.code not in state.state and s.code not in pending}
codes = list(dict.fromkeys(list(state.state) + sorted(pending) + list(candidates)))
ticks = run.client.full_tick(codes) if codes else {}
force = (now.hour, now.minute) >= (14, 50)
available = manage_positions(run, state, ticks, positions, rounds, assets.available, now.date().isoformat(), force)
# 尚未买回时不分走资金;买回与新建仓使用同一份剩余资金。
if not force and not pending and available >= assets.total * run.account_cfg.min_cash_ratio:
if candidates and market_allow_open():
budget = max(0.0, available - assets.total * run.account_cfg.min_cash_ratio)
open_signal(run, ticks, list(candidates.values()), budget)
try:
ticks = run.client.full_tick(all_codes)
collector_push(run.account_cfg.account_id, assets, positions)
except Exception:
log.exception("[行情] 获取行情失败,代码数量=%d", len(all_codes))
log.exception('[ZT] 持仓上报失败')
def sync_account_state(
state: State, positions: list[PositionItem], deals: list[DealItem], *, initialize: bool = False,
) -> None:
"""初次持仓作为底仓;后续只按成交减仓,避免延迟快照删除持仓。"""
zt_deals = [d for d in deals if d.get_local_order_id.startswith('zt-')]
state.sync_deals(zt_deals, archived=initialize)
if initialize:
state.sync_state(positions)
return
log.info(
"[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)
errors = state.archiving(base_order_prefix='zt-base-')
if errors:
raise ValueError(f'ZT 成交归档失败:{errors}')
traded = {d['stock_code'] for d in state.deals.values()}
state.sync_state([p for p in positions if p.stock_code not in traded], remove_missing=False)

View File

@@ -4,7 +4,6 @@ from datetime import datetime
import logging as log
import math
from libs.calc import calc_buy_volume
from sdk import OP_BUY
from libs.runtime import Runtime
from libs.order import PlaceOrderRequest
@@ -12,11 +11,11 @@ from libs.order import PlaceOrderRequest
def open_signal(run: Runtime, ticks, signals, available: float) -> float:
"""逐个验证开仓信号并提交买入委托,返回本轮剩余资金。"""
now = datetime.now()
if (now.hour, now.minute) >= (14, 50):
return available
for item in signals:
try:
now = datetime.now()
if (now.hour, now.minute) >= (14, 50):
break
if item.code in run.account_cfg.excluded_codes:
continue
# 由委托簿检查活动委托,防止重复下单。
@@ -36,16 +35,16 @@ def open_signal(run: Runtime, ticks, signals, available: float) -> float:
continue
# 根据单笔买入金额计算整手数量,并预留少量价差和费用。
budget = min(run.account_cfg.buy_value, available)
volume = calc_buy_volume(price, budget)
volume = int(budget / (price * 1.01)) // 100 * 100
amount = price * volume * 1.01
if volume <= 0 or price * volume > budget or amount > available:
if volume < (200 if item.code.startswith('688') else 100):
continue
# 等待价格从观察低点反弹,防止直接接下跌中的“飞刀”。
if not run.open_watch.triggered("ZT 建仓", item.code, price):
continue
order_id = run.orders.new_order_id("base")
request = PlaceOrderRequest(
OP_BUY, item.code, volume, order_id, "zt", kind="base"
OP_BUY, item.code, volume, order_id, "zt"
)
# 即使响应丢失,本轮也预留资金;状态簿只在取得实际成交后入账。
available -= amount

View File

@@ -1,115 +1,101 @@
"""日内先卖后买做 T 规则,不包含趋势补仓或整仓止盈"""
"""先卖后买做 T;持仓存在 State未买回数量从实际成交计算"""
import logging as log
import math
from libs.grid_take_profit import GridState
from sdk import OP_BUY, OP_SELL, PositionItem
from libs.order import PlaceOrderRequest
from libs.runtime import Runtime
from libs.state import State
from sdk import OP_BUY, OP_SELL, PositionItem
def t_rounds(store: State) -> dict[str, dict]:
"""每只证券保留最近一轮 T跨日未买回的数量继续保留。"""
rounds = {}
for deal in sorted(store.deals.values(), key=lambda d: (
d['trade_date'], d['trade_time'].replace(':', ''), d['id']
)):
order = deal['order_local_id']
code = deal['stock_code']
if order.startswith('zt-t-sell-') and deal['offset_flag'] in (24, 49):
item = rounds.get(code)
if item is None or item['bought'] >= item['sold']:
item = rounds[code] = dict(sold=0, bought=0, amount=0.0, date='')
item['sold'] += deal['volume']
item['amount'] += deal['trade_amount']
item['date'] = deal['trade_date']
elif order.startswith('zt-t-buy-') and deal['offset_flag'] in (23, 48) and code in rounds:
rounds[code]['bought'] += deal['volume']
rounds[code]['date'] = deal['trade_date']
return rounds
def manage_positions(
run: Runtime,
ticks,
positions: list[PositionItem],
available: float,
today: str,
force_buy_back: bool = False,
run: Runtime, store: State, ticks, positions: list[PositionItem],
rounds: dict[str, dict], available: float, today: str, force_buy_back: bool = False,
) -> float:
"""遍历本地底仓记录;全部卖出后即使持仓快照为空,也必须处理买回"""
by_code = {position.stock_code: position for position in positions}
for code, state in list(state_store.items.items()):
"""先偿还买回欠仓;同一证券当天完成一轮后不再卖出"""
by_code = {p.stock_code: p for p in positions}
codes = dict.fromkeys(list(rounds) + list(store.state))
for code in sorted(codes, key=lambda c: not (c in rounds and rounds[c]['sold'] > rounds[c]['bought'])):
try:
if code in run.account_cfg.excluded_codes:
continue
if run.orders.busy(code, "BUY") or run.orders.busy(code, "SELL"):
if run.orders.busy(code, 'BUY') or run.orders.busy(code, 'SELL'):
continue
tick = ticks.get(code)
price = tick.last_price if tick else 0.0
if not math.isfinite(price) or price <= 0:
continue
item = rounds.get(code)
row = store.state.get(code, {})
position = by_code.get(code)
actual_qty = position.volume if position else 0
expected_qty = state.base_qty - state.sell_qty + state.buy_qty
# 快照延迟或手动增减仓不能当作新的做 T 信号,先核对数量差异。
if actual_qty != expected_qty:
log.warning(
"[ZT 持仓] %s 数量不符,记录=%d,实际=%d,暂停交易",
code,
expected_qty,
actual_qty,
)
recorded = row.get('base_qty', 0) + row.get('added_qty', 0)
if recorded != (position.volume if position else 0):
log.warning('[ZT] %s 持仓快照与成交未对齐,等待下一轮', code)
continue
if state.phase == SOLD:
available = _try_buy_back(
run, state, price, available, force_buy_back
)
elif state.phase == READY and position and not force_buy_back:
if price <= run.account_cfg.zt_max_price:
_try_sell(run, state, position, price, today)
if item and item['sold'] > item['bought']:
volume = item['sold'] - item['bought']
# 部分成交后的零股欠仓不能按普通买入申报,不扩大买回数量。
minimum = 200 if code.startswith('688') else 100
if not code.startswith('688'):
volume = volume // 100 * 100
if volume < minimum:
log.warning('[ZT] %s 剩余买回 %d 股不满足申报数量,保留欠仓', code, item['sold'] - item['bought'])
continue
target = item['amount'] / item['sold'] * (1 - run.account_cfg.zt_buy_fall_pct / 100)
if not force_buy_back and price > target:
continue
amount = price * volume * 1.01
if amount > available:
log.warning('[ZT] %s 买回资金不足,需要 %.2f,可用 %.2f', code, amount, available)
continue
if not force_buy_back and not run.add_watch.triggered('ZT 买回', code, price):
continue
available -= amount
request = PlaceOrderRequest(OP_BUY, code, volume, run.orders.new_order_id('t-buy'), 'zt')
if run.orders.place(run.client, request):
run.add_watch.forget(code)
log.info('[ZT 买回] %s %d%s', code, volume, ',尾盘买回' if force_buy_back else '')
continue
if force_buy_back or (item and item['date'] >= today) or not position or recorded <= 0:
continue
if price > run.account_cfg.zt_max_price:
continue
cost = (row['base_qty'] * row['base_price'] + row['added_qty'] * row['added_price']) / recorded
if cost <= 0:
continue
pnl = (price / cost - 1) * 100
observation = run.profit_tracker.observe(f'{run.account_cfg.account_id}:{code}:{today}', pnl)
if observation.state != GridState.RETREAT or pnl < run.account_cfg.min_profit_pct:
continue
volume = int(min(position.can_use_volume, recorded * run.account_cfg.zt_sell_ratio)) // 100 * 100
if volume < (200 if code.startswith('688') else 100):
continue
request = PlaceOrderRequest(OP_SELL, code, volume, run.orders.new_order_id('t-sell'), 'zt')
if run.orders.place(run.client, request):
log.info('[ZT 卖出] %s %d 股,按实际成交买回', code, volume)
except Exception:
log.exception("[ZT 持仓] %s 处理异常,继续后续证券", code)
return available
def _try_sell(
run: Runtime,
state,
position: PositionItem,
price: float,
today: str,
) -> None:
"""基于独立保存的底仓成本,用跨轮最高盈利网格判断做 T 卖出。"""
if state.base_cost <= 0:
return
pnl_rate = (price - state.base_cost) / state.base_cost * 100
key = f"{run.account_cfg.account_id}:{state.code}:{today}"
observation = run.profit_tracker.observe(key, pnl_rate)
if observation.state != GridState.RETREAT:
return
volume = min(
position.can_use_volume, int(state.base_qty * run.account_cfg.zt_sell_ratio)
)
volume = volume // 100 * 100
if volume <= 0:
return
order_id = run.orders.new_order_id("t-sell")
request = PlaceOrderRequest(
OP_SELL, state.code, volume, order_id, "zt", kind="sell"
)
if run.orders.place(run.client, request):
log.info("[ZT 卖出] %s %d 股,等待成交后确定买回数量和价格", state.code, volume)
def _try_buy_back(
run: Runtime,
state,
price: float,
available: float,
force: bool,
) -> float:
"""按实际卖出均价下跌后反弹买回;尾盘不再受下跌幅度、反弹及价格上限限制。"""
target = state.sell_price * (1 - run.account_cfg.zt_buy_fall_pct / 100)
if not force and (price > target or price > run.account_cfg.zt_max_price):
return available
volume = state.sell_qty - state.buy_qty
amount = price * volume * 1.01
if volume <= 0 or amount > available:
log.warning("[ZT 买回] %s 买回资金不足或数量无效,保留未完成轮次", state.code)
return available
if not force and not run.add_watch.triggered("ZT 买回", state.code, price):
return available
order_id = run.orders.new_order_id("t-buy")
request = PlaceOrderRequest(OP_BUY, state.code, volume, order_id, "zt", kind="buy")
# 本轮预留资金;状态簿只在取得实际成交后入账。
available -= amount
if run.orders.place(run.client, request):
run.add_watch.forget(state.code)
log.info(
"[ZT 买回] %s %d 股,%s",
state.code,
volume,
"尾盘强制买回" if force else "下跌后反弹",
)
log.exception('[ZT 持仓] %s 处理失败', code)
return available