59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
from typing import Any
|
|
|
|
from base.base_task import base_task
|
|
from kit.kit import DataHelper
|
|
from task.process_pending_buys_func_task import process_pending_buys_func_task
|
|
|
|
|
|
class check_remain_amount_func_task(base_task):
|
|
"""
|
|
检查账户资金与持仓数量:
|
|
如果因涨停破板卖出导致持仓不足,则从目标股票中筛选未买入股票,进行补仓操作。
|
|
参数:
|
|
context: 聚宽平台传入的交易上下文对象
|
|
"""
|
|
|
|
def __init__(self, strategy: Any, sub_task=None):
|
|
super().__init__(strategy, sub_task)
|
|
|
|
def init(self, context: Any):
|
|
self.name = "check_remain_amount_func_task"
|
|
self.remark = "检查剩余可用资金任务"
|
|
self.memo = "检查是否有剩余可用资金进行补仓"
|
|
|
|
def begin(self, context: Any):
|
|
self.stock_num = self.strategy_config.config['stock_num']
|
|
self.reason_to_sell = self.strategy.get_reason_to_sell()
|
|
self.target_list = self.strategy.get_target_list()
|
|
self.not_buy_again = self.position_manager.get_not_buy_again()
|
|
|
|
def run(self, context: Any):
|
|
if self.reason_to_sell[0]:
|
|
# 更新持仓列表
|
|
self.hold_list = [position.security for position in list(context.portfolio.positions.values())]
|
|
|
|
if len(self.hold_list) < self.stock_num:
|
|
# 处理卖出后的补仓需求
|
|
target_list = DataHelper.filter_not_buy_again(self.target_list, self.not_buy_again)
|
|
if target_list:
|
|
# 将候选股票加入待买入队列
|
|
self.position_manager.register_buy_request(target_list[:self.stock_num - len(self.hold_list)])
|
|
self.log.info(
|
|
f"检测到补仓需求,可用资金 {round(context.portfolio.cash, 2)},添加 {len(target_list[:self.stock_num - len(self.hold_list)])} 只股票到待买入队列")
|
|
|
|
# 立即处理待买入请求
|
|
task = process_pending_buys_func_task(self.strategy, self.name)
|
|
task.process(context)
|
|
|
|
# 重置卖出原因
|
|
self.reason_to_sell = ['']
|
|
else:
|
|
self.log.info("未检测到涨停破板或止损卖出事件,不进行补仓买入。")
|
|
|
|
def handle(self, context: Any):
|
|
pass
|
|
|
|
def end(self, context: Any):
|
|
pass
|
|
|