dev zt
This commit is contained in:
@@ -1,71 +1,94 @@
|
||||
"""日内先卖后买的做 T 规则。"""
|
||||
"""日内先卖后买的做 T 规则,不包含趋势补仓或整仓止盈。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import logging as log
|
||||
import math
|
||||
|
||||
from libs.grid_take_profit import GridState
|
||||
from sdk import OP_BUY, OP_SELL, PositionItem
|
||||
from strategy.trend.order import PlaceOrderRequest
|
||||
|
||||
from .state import BUYING, READY, SELLING, SOLD
|
||||
from .order import PlaceOrderRequest
|
||||
from .runtime import Runtime
|
||||
from .state import PendingOrder, READY, SOLD
|
||||
|
||||
|
||||
def manage_positions(run, ticks, positions: list[PositionItem], available: float, today: str, force_buy_back: bool = False) -> None:
|
||||
for position in positions:
|
||||
code = position.stock_code
|
||||
tick = ticks.get(code)
|
||||
if not code or code in run.account_cfg.excluded_codes or tick is None:
|
||||
continue
|
||||
price = tick.last_price
|
||||
if price <= 0 or price > run.account_cfg.zt_max_price:
|
||||
continue
|
||||
def manage_positions(run: Runtime, ticks, positions: list[PositionItem], 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(run.state.items.items()):
|
||||
try:
|
||||
state = run.state.get(code)
|
||||
except KeyError:
|
||||
continue
|
||||
if state.phase == READY and not force_buy_back:
|
||||
_try_sell(run, state, position, price, today)
|
||||
elif state.phase == SOLD:
|
||||
_try_buy_back(run, state, price, available, today, force_buy_back)
|
||||
now = datetime.now()
|
||||
if now.hour >= 15:
|
||||
break
|
||||
force_buy_back = force_buy_back or (now.hour, now.minute) >= (14, 50)
|
||||
if code in run.account_cfg.excluded_codes or run.state.busy(code):
|
||||
continue
|
||||
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
|
||||
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)
|
||||
continue
|
||||
if state.phase == SOLD:
|
||||
available = _try_buy_back(run, state, price, available, today, 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)
|
||||
except Exception:
|
||||
log.exception("[ZT 持仓] %s 处理异常,继续后续证券", code)
|
||||
return available
|
||||
|
||||
|
||||
def _try_sell(run, state, position: PositionItem, price: float, today: str) -> None:
|
||||
if state.base_cost <= 0 or run.orders.busy(state.code, "SELL"):
|
||||
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
|
||||
observation = run.sell_tracker.observe(f"{run.account_cfg.account_id}:{state.code}", pnl_rate)
|
||||
key = f"{run.account_cfg.account_id}:{state.code}:{today}"
|
||||
observation = run.sell_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) // 100 * 100)
|
||||
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(run.client, OP_SELL, state.code, volume, order_id, run.account_cfg.strategy)
|
||||
if not run.orders.place(request):
|
||||
return
|
||||
state.trade_date, state.phase = today, SELLING
|
||||
state.sell_order_id, state.sell_qty, state.sell_price = order_id, volume, price
|
||||
run.state.set(state)
|
||||
run.state.save()
|
||||
logging.info("[ZT 卖出] %s %d 股,网格回撤触发", state.code, volume)
|
||||
request = PlaceOrderRequest(OP_SELL, state.code, volume, order_id, "zt", kind="sell")
|
||||
run.state.new_order(PendingOrder(order_id, state.code, "sell", volume, today))
|
||||
if run.orders.place(run.client, request):
|
||||
log.info("[ZT 卖出] %s %d 股,等待成交后确定买回数量和价格", state.code, volume)
|
||||
|
||||
|
||||
def _try_buy_back(run, state, price: float, available: float, today: str, force: bool) -> None:
|
||||
def _try_buy_back(run: Runtime, state, price: float, available: float, today: str, force: bool) -> float:
|
||||
"""按实际卖出均价下跌后反弹买回;尾盘不再受下跌幅度、反弹及价格上限限制。"""
|
||||
target = state.sell_price * (1 - run.account_cfg.zt_buy_fall_pct / 100)
|
||||
if (not force and price > target) or run.orders.busy(state.code, "BUY"):
|
||||
return
|
||||
if state.sell_qty <= 0 or price * state.sell_qty > available:
|
||||
return
|
||||
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.buy_watch.triggered("ZT 买回", state.code, price):
|
||||
return
|
||||
return available
|
||||
order_id = run.orders.new_order_id("t-buy")
|
||||
request = PlaceOrderRequest(run.client, OP_BUY, state.code, state.sell_qty, order_id, run.account_cfg.strategy)
|
||||
if not run.orders.place(request):
|
||||
return
|
||||
state.trade_date, state.phase, state.buy_order_id = today, BUYING, order_id
|
||||
run.state.set(state)
|
||||
run.state.save()
|
||||
run.buy_watch.forget(state.code)
|
||||
reason = "尾盘强制买回" if force else f"回撤 {run.account_cfg.zt_buy_fall_pct:.2f}% 后反弹确认"
|
||||
logging.info("[ZT 买回] %s %d 股,%s", state.code, state.sell_qty, reason)
|
||||
request = PlaceOrderRequest(OP_BUY, state.code, volume, order_id, "zt", kind="buy")
|
||||
run.state.new_order(PendingOrder(order_id, state.code, "buy", volume, today))
|
||||
# pending 已落盘,任何请求结果都预留资金;下一轮再从柜台快照确认。
|
||||
available -= amount
|
||||
try:
|
||||
if run.orders.place(run.client, request):
|
||||
run.buy_watch.forget(state.code)
|
||||
log.info("[ZT 买回] %s %d 股,%s", state.code, volume, "尾盘强制买回" if force else "下跌后反弹")
|
||||
except Exception:
|
||||
log.exception("[ZT 买回] %s 请求结果未知,保留 pending 和预算", state.code)
|
||||
return available
|
||||
|
||||
Reference in New Issue
Block a user