This commit is contained in:
2026-09-07 00:27:33 +08:00
parent fdcbdc7869
commit d37f9edefc
11 changed files with 839 additions and 384 deletions

View File

@@ -2,7 +2,6 @@
from __future__ import annotations
from datetime import datetime
import logging as log
import math
@@ -10,7 +9,7 @@ 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 .state import PendingOrder, READY, SOLD, TState
from .state import READY, SOLD, TState
def manage_positions(
@@ -26,11 +25,7 @@ def manage_positions(
by_code = {position.stock_code: position for position in positions}
for code, state in list(state_store.items.items()):
try:
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 state_store.busy(code):
if code in run.account_cfg.excluded_codes:
continue
if run.orders.busy(code, "BUY") or run.orders.busy(code, "SELL"):
continue
@@ -52,11 +47,11 @@ def manage_positions(
continue
if state.phase == SOLD:
available = _try_buy_back(
run, state_store, state, price, available, today, force_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_store, state, position, price, today)
_try_sell(run, state, position, price, today)
except Exception:
log.exception("[ZT 持仓] %s 处理异常,继续后续证券", code)
return available
@@ -64,7 +59,6 @@ def manage_positions(
def _try_sell(
run: Runtime,
state_store: TState,
state,
position: PositionItem,
price: float,
@@ -88,18 +82,15 @@ def _try_sell(
request = PlaceOrderRequest(
OP_SELL, state.code, volume, order_id, "zt", kind="sell"
)
state_store.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: Runtime,
state_store: TState,
state,
price: float,
available: float,
today: str,
force: bool,
) -> float:
"""按实际卖出均价下跌后反弹买回;尾盘不再受下跌幅度、反弹及价格上限限制。"""
@@ -115,18 +106,14 @@ def _try_buy_back(
return available
order_id = run.orders.new_order_id("t-buy")
request = PlaceOrderRequest(OP_BUY, state.code, volume, order_id, "zt", kind="buy")
state_store.new_order(PendingOrder(order_id, state.code, "buy", volume, today))
# pending 已落盘,任何请求结果都预留资金;下一轮再从柜台快照确认。
# 本轮预留资金;状态簿只在取得实际成交后入账。
available -= amount
try:
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 "下跌后反弹",
)
except Exception:
log.exception("[ZT 买回] %s 请求结果未知,保留 pending 和预算", state.code)
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 "下跌后反弹",
)
return available